babylon.no-module.max.js 5.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249
  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. /**
  1242. * Gather the list of keyboard event types as constants.
  1243. */
  1244. var KeyboardEventTypes = /** @class */ (function () {
  1245. function KeyboardEventTypes() {
  1246. }
  1247. /**
  1248. * The keydown event is fired when a key becomes active (pressed).
  1249. */
  1250. KeyboardEventTypes.KEYDOWN = 0x01;
  1251. /**
  1252. * The keyup event is fired when a key has been released.
  1253. */
  1254. KeyboardEventTypes.KEYUP = 0x02;
  1255. return KeyboardEventTypes;
  1256. }());
  1257. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1258. /**
  1259. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1260. */
  1261. var KeyboardInfo = /** @class */ (function () {
  1262. /**
  1263. * Instantiates a new keyboard info.
  1264. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1265. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1266. * @param event Defines the related dom event
  1267. */
  1268. function KeyboardInfo(
  1269. /**
  1270. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1271. */
  1272. type,
  1273. /**
  1274. * Defines the related dom event
  1275. */
  1276. event) {
  1277. this.type = type;
  1278. this.event = event;
  1279. }
  1280. return KeyboardInfo;
  1281. }());
  1282. BABYLON.KeyboardInfo = KeyboardInfo;
  1283. /**
  1284. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1285. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1286. */
  1287. var KeyboardInfoPre = /** @class */ (function (_super) {
  1288. __extends(KeyboardInfoPre, _super);
  1289. /**
  1290. * Instantiates a new keyboard pre info.
  1291. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1292. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1293. * @param event Defines the related dom event
  1294. */
  1295. function KeyboardInfoPre(
  1296. /**
  1297. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1298. */
  1299. type,
  1300. /**
  1301. * Defines the related dom event
  1302. */
  1303. event) {
  1304. var _this = _super.call(this, type, event) || this;
  1305. _this.type = type;
  1306. _this.event = event;
  1307. _this.skipOnPointerObservable = false;
  1308. return _this;
  1309. }
  1310. return KeyboardInfoPre;
  1311. }(KeyboardInfo));
  1312. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1313. })(BABYLON || (BABYLON = {}));
  1314. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1315. var BABYLON;
  1316. (function (BABYLON) {
  1317. /**
  1318. * Gather the list of pointer event types as constants.
  1319. */
  1320. var PointerEventTypes = /** @class */ (function () {
  1321. function PointerEventTypes() {
  1322. }
  1323. /**
  1324. * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.
  1325. */
  1326. PointerEventTypes.POINTERDOWN = 0x01;
  1327. /**
  1328. * The pointerup event is fired when a pointer is no longer active.
  1329. */
  1330. PointerEventTypes.POINTERUP = 0x02;
  1331. /**
  1332. * The pointermove event is fired when a pointer changes coordinates.
  1333. */
  1334. PointerEventTypes.POINTERMOVE = 0x04;
  1335. /**
  1336. * The pointerwheel event is fired when a mouse wheel has been rotated.
  1337. */
  1338. PointerEventTypes.POINTERWHEEL = 0x08;
  1339. /**
  1340. * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
  1341. */
  1342. PointerEventTypes.POINTERPICK = 0x10;
  1343. /**
  1344. * The pointertap event is fired when a the object has been touched and released without drag.
  1345. */
  1346. PointerEventTypes.POINTERTAP = 0x20;
  1347. /**
  1348. * The pointertap event is fired when a the object has been touched and released twice without drag.
  1349. */
  1350. PointerEventTypes.POINTERDOUBLETAP = 0x40;
  1351. return PointerEventTypes;
  1352. }());
  1353. BABYLON.PointerEventTypes = PointerEventTypes;
  1354. /**
  1355. * Base class of pointer info types.
  1356. */
  1357. var PointerInfoBase = /** @class */ (function () {
  1358. /**
  1359. * Instantiates the base class of pointers info.
  1360. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1361. * @param event Defines the related dom event
  1362. */
  1363. function PointerInfoBase(
  1364. /**
  1365. * Defines the type of event (BABYLON.PointerEventTypes)
  1366. */
  1367. type,
  1368. /**
  1369. * Defines the related dom event
  1370. */
  1371. event) {
  1372. this.type = type;
  1373. this.event = event;
  1374. }
  1375. return PointerInfoBase;
  1376. }());
  1377. BABYLON.PointerInfoBase = PointerInfoBase;
  1378. /**
  1379. * This class is used to store pointer related info for the onPrePointerObservable event.
  1380. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1381. */
  1382. var PointerInfoPre = /** @class */ (function (_super) {
  1383. __extends(PointerInfoPre, _super);
  1384. /**
  1385. * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
  1386. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1387. * @param event Defines the related dom event
  1388. * @param localX Defines the local x coordinates of the pointer when the event occured
  1389. * @param localY Defines the local y coordinates of the pointer when the event occured
  1390. */
  1391. function PointerInfoPre(type, event, localX, localY) {
  1392. var _this = _super.call(this, type, event) || this;
  1393. /**
  1394. * Ray from a pointer if availible (eg. 6dof controller)
  1395. */
  1396. _this.ray = null;
  1397. _this.skipOnPointerObservable = false;
  1398. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1399. return _this;
  1400. }
  1401. return PointerInfoPre;
  1402. }(PointerInfoBase));
  1403. BABYLON.PointerInfoPre = PointerInfoPre;
  1404. /**
  1405. * This type contains all the data related to a pointer event in Babylon.js.
  1406. * 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.
  1407. */
  1408. var PointerInfo = /** @class */ (function (_super) {
  1409. __extends(PointerInfo, _super);
  1410. /**
  1411. * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
  1412. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1413. * @param event Defines the related dom event
  1414. * @param pickInfo Defines the picking info associated to the info (if any)\
  1415. */
  1416. function PointerInfo(type, event,
  1417. /**
  1418. * Defines the picking info associated to the info (if any)\
  1419. */
  1420. pickInfo) {
  1421. var _this = _super.call(this, type, event) || this;
  1422. _this.pickInfo = pickInfo;
  1423. return _this;
  1424. }
  1425. return PointerInfo;
  1426. }(PointerInfoBase));
  1427. BABYLON.PointerInfo = PointerInfo;
  1428. })(BABYLON || (BABYLON = {}));
  1429. //# sourceMappingURL=babylon.pointerEvents.js.map
  1430. var BABYLON;
  1431. (function (BABYLON) {
  1432. /**
  1433. * Constant used to convert a value to gamma space
  1434. * @ignorenaming
  1435. */
  1436. BABYLON.ToGammaSpace = 1 / 2.2;
  1437. /**
  1438. * Constant used to convert a value to linear space
  1439. * @ignorenaming
  1440. */
  1441. BABYLON.ToLinearSpace = 2.2;
  1442. /**
  1443. * Constant used to define the minimal number value in Babylon.js
  1444. * @ignorenaming
  1445. */
  1446. BABYLON.Epsilon = 0.001;
  1447. /**
  1448. * Class used to hold a RBG color
  1449. */
  1450. var Color3 = /** @class */ (function () {
  1451. /**
  1452. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1453. * @param r defines the red component (between 0 and 1, default is 0)
  1454. * @param g defines the green component (between 0 and 1, default is 0)
  1455. * @param b defines the blue component (between 0 and 1, default is 0)
  1456. */
  1457. function Color3(
  1458. /**
  1459. * Defines the red component (between 0 and 1, default is 0)
  1460. */
  1461. r,
  1462. /**
  1463. * Defines the green component (between 0 and 1, default is 0)
  1464. */
  1465. g,
  1466. /**
  1467. * Defines the blue component (between 0 and 1, default is 0)
  1468. */
  1469. b) {
  1470. if (r === void 0) { r = 0; }
  1471. if (g === void 0) { g = 0; }
  1472. if (b === void 0) { b = 0; }
  1473. this.r = r;
  1474. this.g = g;
  1475. this.b = b;
  1476. }
  1477. /**
  1478. * Creates a string with the Color3 current values
  1479. * @returns the string representation of the Color3 object
  1480. */
  1481. Color3.prototype.toString = function () {
  1482. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1483. };
  1484. /**
  1485. * Returns the string "Color3"
  1486. * @returns "Color3"
  1487. */
  1488. Color3.prototype.getClassName = function () {
  1489. return "Color3";
  1490. };
  1491. /**
  1492. * Compute the Color3 hash code
  1493. * @returns an unique number that can be used to hash Color3 objects
  1494. */
  1495. Color3.prototype.getHashCode = function () {
  1496. var hash = this.r || 0;
  1497. hash = (hash * 397) ^ (this.g || 0);
  1498. hash = (hash * 397) ^ (this.b || 0);
  1499. return hash;
  1500. };
  1501. // Operators
  1502. /**
  1503. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1504. * @param array defines the array where to store the r,g,b components
  1505. * @param index defines an optional index in the target array to define where to start storing values
  1506. * @returns the current Color3 object
  1507. */
  1508. Color3.prototype.toArray = function (array, index) {
  1509. if (index === undefined) {
  1510. index = 0;
  1511. }
  1512. array[index] = this.r;
  1513. array[index + 1] = this.g;
  1514. array[index + 2] = this.b;
  1515. return this;
  1516. };
  1517. /**
  1518. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1519. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1520. * @returns a new {BABYLON.Color4} object
  1521. */
  1522. Color3.prototype.toColor4 = function (alpha) {
  1523. if (alpha === void 0) { alpha = 1; }
  1524. return new Color4(this.r, this.g, this.b, alpha);
  1525. };
  1526. /**
  1527. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1528. * @returns the new array
  1529. */
  1530. Color3.prototype.asArray = function () {
  1531. var result = new Array();
  1532. this.toArray(result, 0);
  1533. return result;
  1534. };
  1535. /**
  1536. * Returns the luminance value
  1537. * @returns a float value
  1538. */
  1539. Color3.prototype.toLuminance = function () {
  1540. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1541. };
  1542. /**
  1543. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1544. * @param otherColor defines the second operand
  1545. * @returns the new Color3 object
  1546. */
  1547. Color3.prototype.multiply = function (otherColor) {
  1548. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1549. };
  1550. /**
  1551. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1552. * @param otherColor defines the second operand
  1553. * @param result defines the Color3 object where to store the result
  1554. * @returns the current Color3
  1555. */
  1556. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1557. result.r = this.r * otherColor.r;
  1558. result.g = this.g * otherColor.g;
  1559. result.b = this.b * otherColor.b;
  1560. return this;
  1561. };
  1562. /**
  1563. * Determines equality between Color3 objects
  1564. * @param otherColor defines the second operand
  1565. * @returns true if the rgb values are equal to the given ones
  1566. */
  1567. Color3.prototype.equals = function (otherColor) {
  1568. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1569. };
  1570. /**
  1571. * Determines equality between the current Color3 object and a set of r,b,g values
  1572. * @param r defines the red component to check
  1573. * @param g defines the green component to check
  1574. * @param b defines the blue component to check
  1575. * @returns true if the rgb values are equal to the given ones
  1576. */
  1577. Color3.prototype.equalsFloats = function (r, g, b) {
  1578. return this.r === r && this.g === g && this.b === b;
  1579. };
  1580. /**
  1581. * Multiplies in place each rgb value by scale
  1582. * @param scale defines the scaling factor
  1583. * @returns the updated Color3
  1584. */
  1585. Color3.prototype.scale = function (scale) {
  1586. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1587. };
  1588. /**
  1589. * Multiplies the rgb values by scale and stores the result into "result"
  1590. * @param scale defines the scaling factor
  1591. * @param result defines the Color3 object where to store the result
  1592. * @returns the unmodified current Color3
  1593. */
  1594. Color3.prototype.scaleToRef = function (scale, result) {
  1595. result.r = this.r * scale;
  1596. result.g = this.g * scale;
  1597. result.b = this.b * scale;
  1598. return this;
  1599. };
  1600. /**
  1601. * Scale the current Color3 values by a factor and add the result to a given Color3
  1602. * @param scale defines the scale factor
  1603. * @param result defines color to store the result into
  1604. * @returns the unmodified current Color3
  1605. */
  1606. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1607. result.r += this.r * scale;
  1608. result.g += this.g * scale;
  1609. result.b += this.b * scale;
  1610. return this;
  1611. };
  1612. /**
  1613. * Clamps the rgb values by the min and max values and stores the result into "result"
  1614. * @param min defines minimum clamping value (default is 0)
  1615. * @param max defines maximum clamping value (default is 1)
  1616. * @param result defines color to store the result into
  1617. * @returns the original Color3
  1618. */
  1619. Color3.prototype.clampToRef = function (min, max, result) {
  1620. if (min === void 0) { min = 0; }
  1621. if (max === void 0) { max = 1; }
  1622. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1623. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1624. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1625. return this;
  1626. };
  1627. /**
  1628. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1629. * @param otherColor defines the second operand
  1630. * @returns the new Color3
  1631. */
  1632. Color3.prototype.add = function (otherColor) {
  1633. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1634. };
  1635. /**
  1636. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1637. * @param otherColor defines the second operand
  1638. * @param result defines Color3 object to store the result into
  1639. * @returns the unmodified current Color3
  1640. */
  1641. Color3.prototype.addToRef = function (otherColor, result) {
  1642. result.r = this.r + otherColor.r;
  1643. result.g = this.g + otherColor.g;
  1644. result.b = this.b + otherColor.b;
  1645. return this;
  1646. };
  1647. /**
  1648. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1649. * @param otherColor defines the second operand
  1650. * @returns the new Color3
  1651. */
  1652. Color3.prototype.subtract = function (otherColor) {
  1653. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1654. };
  1655. /**
  1656. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1657. * @param otherColor defines the second operand
  1658. * @param result defines Color3 object to store the result into
  1659. * @returns the unmodified current Color3
  1660. */
  1661. Color3.prototype.subtractToRef = function (otherColor, result) {
  1662. result.r = this.r - otherColor.r;
  1663. result.g = this.g - otherColor.g;
  1664. result.b = this.b - otherColor.b;
  1665. return this;
  1666. };
  1667. /**
  1668. * Copy the current object
  1669. * @returns a new Color3 copied the current one
  1670. */
  1671. Color3.prototype.clone = function () {
  1672. return new Color3(this.r, this.g, this.b);
  1673. };
  1674. /**
  1675. * Copies the rgb values from the source in the current Color3
  1676. * @param source defines the source Color3 object
  1677. * @returns the updated Color3 object
  1678. */
  1679. Color3.prototype.copyFrom = function (source) {
  1680. this.r = source.r;
  1681. this.g = source.g;
  1682. this.b = source.b;
  1683. return this;
  1684. };
  1685. /**
  1686. * Updates the Color3 rgb values from the given floats
  1687. * @param r defines the red component to read from
  1688. * @param g defines the green component to read from
  1689. * @param b defines the blue component to read from
  1690. * @returns the current Color3 object
  1691. */
  1692. Color3.prototype.copyFromFloats = function (r, g, b) {
  1693. this.r = r;
  1694. this.g = g;
  1695. this.b = b;
  1696. return this;
  1697. };
  1698. /**
  1699. * Updates the Color3 rgb values from the given floats
  1700. * @param r defines the red component to read from
  1701. * @param g defines the green component to read from
  1702. * @param b defines the blue component to read from
  1703. * @returns the current Color3 object
  1704. */
  1705. Color3.prototype.set = function (r, g, b) {
  1706. return this.copyFromFloats(r, g, b);
  1707. };
  1708. /**
  1709. * Compute the Color3 hexadecimal code as a string
  1710. * @returns a string containing the hexadecimal representation of the Color3 object
  1711. */
  1712. Color3.prototype.toHexString = function () {
  1713. var intR = (this.r * 255) | 0;
  1714. var intG = (this.g * 255) | 0;
  1715. var intB = (this.b * 255) | 0;
  1716. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1717. };
  1718. /**
  1719. * Computes a new Color3 converted from the current one to linear space
  1720. * @returns a new Color3 object
  1721. */
  1722. Color3.prototype.toLinearSpace = function () {
  1723. var convertedColor = new Color3();
  1724. this.toLinearSpaceToRef(convertedColor);
  1725. return convertedColor;
  1726. };
  1727. /**
  1728. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1729. * @param convertedColor defines the Color3 object where to store the linear space version
  1730. * @returns the unmodified Color3
  1731. */
  1732. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1733. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1734. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1735. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1736. return this;
  1737. };
  1738. /**
  1739. * Computes a new Color3 converted from the current one to gamma space
  1740. * @returns a new Color3 object
  1741. */
  1742. Color3.prototype.toGammaSpace = function () {
  1743. var convertedColor = new Color3();
  1744. this.toGammaSpaceToRef(convertedColor);
  1745. return convertedColor;
  1746. };
  1747. /**
  1748. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1749. * @param convertedColor defines the Color3 object where to store the gamma space version
  1750. * @returns the unmodified Color3
  1751. */
  1752. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1753. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1754. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1755. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1756. return this;
  1757. };
  1758. // Statics
  1759. /**
  1760. * Creates a new Color3 from the string containing valid hexadecimal values
  1761. * @param hex defines a string containing valid hexadecimal values
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.FromHexString = function (hex) {
  1765. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1766. return new Color3(0, 0, 0);
  1767. }
  1768. var r = parseInt(hex.substring(1, 3), 16);
  1769. var g = parseInt(hex.substring(3, 5), 16);
  1770. var b = parseInt(hex.substring(5, 7), 16);
  1771. return Color3.FromInts(r, g, b);
  1772. };
  1773. /**
  1774. * Creates a new Vector3 from the starting index of the given array
  1775. * @param array defines the source array
  1776. * @param offset defines an offset in the source array
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.FromArray = function (array, offset) {
  1780. if (offset === void 0) { offset = 0; }
  1781. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1782. };
  1783. /**
  1784. * Creates a new Color3 from integer values (< 256)
  1785. * @param r defines the red component to read from (value between 0 and 255)
  1786. * @param g defines the green component to read from (value between 0 and 255)
  1787. * @param b defines the blue component to read from (value between 0 and 255)
  1788. * @returns a new Color3 object
  1789. */
  1790. Color3.FromInts = function (r, g, b) {
  1791. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1792. };
  1793. /**
  1794. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1795. * @param start defines the start Color3 value
  1796. * @param end defines the end Color3 value
  1797. * @param amount defines the gradient value between start and end
  1798. * @returns a new Color3 object
  1799. */
  1800. Color3.Lerp = function (start, end, amount) {
  1801. var result = new Color3(0.0, 0.0, 0.0);
  1802. Color3.LerpToRef(start, end, amount, result);
  1803. return result;
  1804. };
  1805. /**
  1806. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1807. * @param left defines the start value
  1808. * @param right defines the end value
  1809. * @param amount defines the gradient factor
  1810. * @param result defines the Color3 object where to store the result
  1811. */
  1812. Color3.LerpToRef = function (left, right, amount, result) {
  1813. result.r = left.r + ((right.r - left.r) * amount);
  1814. result.g = left.g + ((right.g - left.g) * amount);
  1815. result.b = left.b + ((right.b - left.b) * amount);
  1816. };
  1817. /**
  1818. * Returns a Color3 value containing a red color
  1819. * @returns a new Color3 object
  1820. */
  1821. Color3.Red = function () { return new Color3(1, 0, 0); };
  1822. /**
  1823. * Returns a Color3 value containing a green color
  1824. * @returns a new Color3 object
  1825. */
  1826. Color3.Green = function () { return new Color3(0, 1, 0); };
  1827. /**
  1828. * Returns a Color3 value containing a blue color
  1829. * @returns a new Color3 object
  1830. */
  1831. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1832. /**
  1833. * Returns a Color3 value containing a black color
  1834. * @returns a new Color3 object
  1835. */
  1836. Color3.Black = function () { return new Color3(0, 0, 0); };
  1837. /**
  1838. * Returns a Color3 value containing a white color
  1839. * @returns a new Color3 object
  1840. */
  1841. Color3.White = function () { return new Color3(1, 1, 1); };
  1842. /**
  1843. * Returns a Color3 value containing a purple color
  1844. * @returns a new Color3 object
  1845. */
  1846. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1847. /**
  1848. * Returns a Color3 value containing a magenta color
  1849. * @returns a new Color3 object
  1850. */
  1851. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1852. /**
  1853. * Returns a Color3 value containing a yellow color
  1854. * @returns a new Color3 object
  1855. */
  1856. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1857. /**
  1858. * Returns a Color3 value containing a gray color
  1859. * @returns a new Color3 object
  1860. */
  1861. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1862. /**
  1863. * Returns a Color3 value containing a teal color
  1864. * @returns a new Color3 object
  1865. */
  1866. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1867. /**
  1868. * Returns a Color3 value containing a random color
  1869. * @returns a new Color3 object
  1870. */
  1871. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1872. return Color3;
  1873. }());
  1874. BABYLON.Color3 = Color3;
  1875. /**
  1876. * Class used to hold a RBGA color
  1877. */
  1878. var Color4 = /** @class */ (function () {
  1879. /**
  1880. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1881. * @param r defines the red component (between 0 and 1, default is 0)
  1882. * @param g defines the green component (between 0 and 1, default is 0)
  1883. * @param b defines the blue component (between 0 and 1, default is 0)
  1884. * @param a defines the alpha component (between 0 and 1, default is 1)
  1885. */
  1886. function Color4(
  1887. /**
  1888. * Defines the red component (between 0 and 1, default is 0)
  1889. */
  1890. r,
  1891. /**
  1892. * Defines the green component (between 0 and 1, default is 0)
  1893. */
  1894. g,
  1895. /**
  1896. * Defines the blue component (between 0 and 1, default is 0)
  1897. */
  1898. b,
  1899. /**
  1900. * Defines the alpha component (between 0 and 1, default is 1)
  1901. */
  1902. a) {
  1903. if (r === void 0) { r = 0; }
  1904. if (g === void 0) { g = 0; }
  1905. if (b === void 0) { b = 0; }
  1906. if (a === void 0) { a = 1; }
  1907. this.r = r;
  1908. this.g = g;
  1909. this.b = b;
  1910. this.a = a;
  1911. }
  1912. // Operators
  1913. /**
  1914. * Adds in place the given Color4 values to the current Color4 object
  1915. * @param right defines the second operand
  1916. * @returns the current updated Color4 object
  1917. */
  1918. Color4.prototype.addInPlace = function (right) {
  1919. this.r += right.r;
  1920. this.g += right.g;
  1921. this.b += right.b;
  1922. this.a += right.a;
  1923. return this;
  1924. };
  1925. /**
  1926. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1927. * @returns the new array
  1928. */
  1929. Color4.prototype.asArray = function () {
  1930. var result = new Array();
  1931. this.toArray(result, 0);
  1932. return result;
  1933. };
  1934. /**
  1935. * Stores from the starting index in the given array the Color4 successive values
  1936. * @param array defines the array where to store the r,g,b components
  1937. * @param index defines an optional index in the target array to define where to start storing values
  1938. * @returns the current Color4 object
  1939. */
  1940. Color4.prototype.toArray = function (array, index) {
  1941. if (index === undefined) {
  1942. index = 0;
  1943. }
  1944. array[index] = this.r;
  1945. array[index + 1] = this.g;
  1946. array[index + 2] = this.b;
  1947. array[index + 3] = this.a;
  1948. return this;
  1949. };
  1950. /**
  1951. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1952. * @param right defines the second operand
  1953. * @returns a new Color4 object
  1954. */
  1955. Color4.prototype.add = function (right) {
  1956. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1957. };
  1958. /**
  1959. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1960. * @param right defines the second operand
  1961. * @returns a new Color4 object
  1962. */
  1963. Color4.prototype.subtract = function (right) {
  1964. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1965. };
  1966. /**
  1967. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1968. * @param right defines the second operand
  1969. * @param result defines the Color4 object where to store the result
  1970. * @returns the current Color4 object
  1971. */
  1972. Color4.prototype.subtractToRef = function (right, result) {
  1973. result.r = this.r - right.r;
  1974. result.g = this.g - right.g;
  1975. result.b = this.b - right.b;
  1976. result.a = this.a - right.a;
  1977. return this;
  1978. };
  1979. /**
  1980. * Creates a new Color4 with the current Color4 values multiplied by scale
  1981. * @param scale defines the scaling factor to apply
  1982. * @returns a new Color4 object
  1983. */
  1984. Color4.prototype.scale = function (scale) {
  1985. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1986. };
  1987. /**
  1988. * Multiplies the current Color4 values by scale and stores the result in "result"
  1989. * @param scale defines the scaling factor to apply
  1990. * @param result defines the Color4 object where to store the result
  1991. * @returns the current unmodified Color4
  1992. */
  1993. Color4.prototype.scaleToRef = function (scale, result) {
  1994. result.r = this.r * scale;
  1995. result.g = this.g * scale;
  1996. result.b = this.b * scale;
  1997. result.a = this.a * scale;
  1998. return this;
  1999. };
  2000. /**
  2001. * Scale the current Color4 values by a factor and add the result to a given Color4
  2002. * @param scale defines the scale factor
  2003. * @param result defines the Color4 object where to store the result
  2004. * @returns the unmodified current Color4
  2005. */
  2006. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2007. result.r += this.r * scale;
  2008. result.g += this.g * scale;
  2009. result.b += this.b * scale;
  2010. result.a += this.a * scale;
  2011. return this;
  2012. };
  2013. /**
  2014. * Clamps the rgb values by the min and max values and stores the result into "result"
  2015. * @param min defines minimum clamping value (default is 0)
  2016. * @param max defines maximum clamping value (default is 1)
  2017. * @param result defines color to store the result into.
  2018. * @returns the cuurent Color4
  2019. */
  2020. Color4.prototype.clampToRef = function (min, max, result) {
  2021. if (min === void 0) { min = 0; }
  2022. if (max === void 0) { max = 1; }
  2023. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2024. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2025. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2026. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2027. return this;
  2028. };
  2029. /**
  2030. * Multipy an Color4 value by another and return a new Color4 object
  2031. * @param color defines the Color4 value to multiply by
  2032. * @returns a new Color4 object
  2033. */
  2034. Color4.prototype.multiply = function (color) {
  2035. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2036. };
  2037. /**
  2038. * Multipy a Color4 value by another and push the result in a reference value
  2039. * @param color defines the Color4 value to multiply by
  2040. * @param result defines the Color4 to fill the result in
  2041. * @returns the result Color4
  2042. */
  2043. Color4.prototype.multiplyToRef = function (color, result) {
  2044. result.r = this.r * color.r;
  2045. result.g = this.g * color.g;
  2046. result.b = this.b * color.b;
  2047. result.a = this.a * color.a;
  2048. return result;
  2049. };
  2050. /**
  2051. * Creates a string with the Color4 current values
  2052. * @returns the string representation of the Color4 object
  2053. */
  2054. Color4.prototype.toString = function () {
  2055. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2056. };
  2057. /**
  2058. * Returns the string "Color4"
  2059. * @returns "Color4"
  2060. */
  2061. Color4.prototype.getClassName = function () {
  2062. return "Color4";
  2063. };
  2064. /**
  2065. * Compute the Color4 hash code
  2066. * @returns an unique number that can be used to hash Color4 objects
  2067. */
  2068. Color4.prototype.getHashCode = function () {
  2069. var hash = this.r || 0;
  2070. hash = (hash * 397) ^ (this.g || 0);
  2071. hash = (hash * 397) ^ (this.b || 0);
  2072. hash = (hash * 397) ^ (this.a || 0);
  2073. return hash;
  2074. };
  2075. /**
  2076. * Creates a new Color4 copied from the current one
  2077. * @returns a new Color4 object
  2078. */
  2079. Color4.prototype.clone = function () {
  2080. return new Color4(this.r, this.g, this.b, this.a);
  2081. };
  2082. /**
  2083. * Copies the given Color4 values into the current one
  2084. * @param source defines the source Color4 object
  2085. * @returns the current updated Color4 object
  2086. */
  2087. Color4.prototype.copyFrom = function (source) {
  2088. this.r = source.r;
  2089. this.g = source.g;
  2090. this.b = source.b;
  2091. this.a = source.a;
  2092. return this;
  2093. };
  2094. /**
  2095. * Copies the given float values into the current one
  2096. * @param r defines the red component to read from
  2097. * @param g defines the green component to read from
  2098. * @param b defines the blue component to read from
  2099. * @param a defines the alpha component to read from
  2100. * @returns the current updated Color4 object
  2101. */
  2102. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2103. this.r = r;
  2104. this.g = g;
  2105. this.b = b;
  2106. this.a = a;
  2107. return this;
  2108. };
  2109. /**
  2110. * Copies the given float values into the current one
  2111. * @param r defines the red component to read from
  2112. * @param g defines the green component to read from
  2113. * @param b defines the blue component to read from
  2114. * @param a defines the alpha component to read from
  2115. * @returns the current updated Color4 object
  2116. */
  2117. Color4.prototype.set = function (r, g, b, a) {
  2118. return this.copyFromFloats(r, g, b, a);
  2119. };
  2120. /**
  2121. * Compute the Color4 hexadecimal code as a string
  2122. * @returns a string containing the hexadecimal representation of the Color4 object
  2123. */
  2124. Color4.prototype.toHexString = function () {
  2125. var intR = (this.r * 255) | 0;
  2126. var intG = (this.g * 255) | 0;
  2127. var intB = (this.b * 255) | 0;
  2128. var intA = (this.a * 255) | 0;
  2129. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2130. };
  2131. /**
  2132. * Computes a new Color4 converted from the current one to linear space
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.prototype.toLinearSpace = function () {
  2136. var convertedColor = new Color4();
  2137. this.toLinearSpaceToRef(convertedColor);
  2138. return convertedColor;
  2139. };
  2140. /**
  2141. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2142. * @param convertedColor defines the Color4 object where to store the linear space version
  2143. * @returns the unmodified Color4
  2144. */
  2145. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2146. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2147. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2148. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2149. convertedColor.a = this.a;
  2150. return this;
  2151. };
  2152. /**
  2153. * Computes a new Color4 converted from the current one to gamma space
  2154. * @returns a new Color4 object
  2155. */
  2156. Color4.prototype.toGammaSpace = function () {
  2157. var convertedColor = new Color4();
  2158. this.toGammaSpaceToRef(convertedColor);
  2159. return convertedColor;
  2160. };
  2161. /**
  2162. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2163. * @param convertedColor defines the Color4 object where to store the gamma space version
  2164. * @returns the unmodified Color4
  2165. */
  2166. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2167. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2168. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2169. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2170. convertedColor.a = this.a;
  2171. return this;
  2172. };
  2173. // Statics
  2174. /**
  2175. * Creates a new Color4 from the string containing valid hexadecimal values
  2176. * @param hex defines a string containing valid hexadecimal values
  2177. * @returns a new Color4 object
  2178. */
  2179. Color4.FromHexString = function (hex) {
  2180. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2181. return new Color4(0.0, 0.0, 0.0, 0.0);
  2182. }
  2183. var r = parseInt(hex.substring(1, 3), 16);
  2184. var g = parseInt(hex.substring(3, 5), 16);
  2185. var b = parseInt(hex.substring(5, 7), 16);
  2186. var a = parseInt(hex.substring(7, 9), 16);
  2187. return Color4.FromInts(r, g, b, a);
  2188. };
  2189. /**
  2190. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2191. * @param left defines the start value
  2192. * @param right defines the end value
  2193. * @param amount defines the gradient factor
  2194. * @returns a new Color4 object
  2195. */
  2196. Color4.Lerp = function (left, right, amount) {
  2197. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2198. Color4.LerpToRef(left, right, amount, result);
  2199. return result;
  2200. };
  2201. /**
  2202. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2203. * @param left defines the start value
  2204. * @param right defines the end value
  2205. * @param amount defines the gradient factor
  2206. * @param result defines the Color4 object where to store data
  2207. */
  2208. Color4.LerpToRef = function (left, right, amount, result) {
  2209. result.r = left.r + (right.r - left.r) * amount;
  2210. result.g = left.g + (right.g - left.g) * amount;
  2211. result.b = left.b + (right.b - left.b) * amount;
  2212. result.a = left.a + (right.a - left.a) * amount;
  2213. };
  2214. /**
  2215. * Creates a new Color4 from a Color3 and an alpha value
  2216. * @param color3 defines the source Color3 to read from
  2217. * @param alpha defines the alpha component (1.0 by default)
  2218. * @returns a new Color4 object
  2219. */
  2220. Color4.FromColor3 = function (color3, alpha) {
  2221. if (alpha === void 0) { alpha = 1.0; }
  2222. return new Color4(color3.r, color3.g, color3.b, alpha);
  2223. };
  2224. /**
  2225. * Creates a new Color4 from the starting index element of the given array
  2226. * @param array defines the source array to read from
  2227. * @param offset defines the offset in the source array
  2228. * @returns a new Color4 object
  2229. */
  2230. Color4.FromArray = function (array, offset) {
  2231. if (offset === void 0) { offset = 0; }
  2232. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2233. };
  2234. /**
  2235. * Creates a new Color3 from integer values (< 256)
  2236. * @param r defines the red component to read from (value between 0 and 255)
  2237. * @param g defines the green component to read from (value between 0 and 255)
  2238. * @param b defines the blue component to read from (value between 0 and 255)
  2239. * @param a defines the alpha component to read from (value between 0 and 255)
  2240. * @returns a new Color3 object
  2241. */
  2242. Color4.FromInts = function (r, g, b, a) {
  2243. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2244. };
  2245. /**
  2246. * Check the content of a given array and convert it to an array containing RGBA data
  2247. * If the original array was already containing count * 4 values then it is returned directly
  2248. * @param colors defines the array to check
  2249. * @param count defines the number of RGBA data to expect
  2250. * @returns an array containing count * 4 values (RGBA)
  2251. */
  2252. Color4.CheckColors4 = function (colors, count) {
  2253. // Check if color3 was used
  2254. if (colors.length === count * 3) {
  2255. var colors4 = [];
  2256. for (var index = 0; index < colors.length; index += 3) {
  2257. var newIndex = (index / 3) * 4;
  2258. colors4[newIndex] = colors[index];
  2259. colors4[newIndex + 1] = colors[index + 1];
  2260. colors4[newIndex + 2] = colors[index + 2];
  2261. colors4[newIndex + 3] = 1.0;
  2262. }
  2263. return colors4;
  2264. }
  2265. return colors;
  2266. };
  2267. return Color4;
  2268. }());
  2269. BABYLON.Color4 = Color4;
  2270. /**
  2271. * Class representing a vector containing 2 coordinates
  2272. */
  2273. var Vector2 = /** @class */ (function () {
  2274. /**
  2275. * Creates a new Vector2 from the given x and y coordinates
  2276. * @param x defines the first coordinate
  2277. * @param y defines the second coordinate
  2278. */
  2279. function Vector2(
  2280. /** defines the first coordinate */
  2281. x,
  2282. /** defines the second coordinate */
  2283. y) {
  2284. if (x === void 0) { x = 0; }
  2285. if (y === void 0) { y = 0; }
  2286. this.x = x;
  2287. this.y = y;
  2288. }
  2289. /**
  2290. * Gets a string with the Vector2 coordinates
  2291. * @returns a string with the Vector2 coordinates
  2292. */
  2293. Vector2.prototype.toString = function () {
  2294. return "{X: " + this.x + " Y:" + this.y + "}";
  2295. };
  2296. /**
  2297. * Gets class name
  2298. * @returns the string "Vector2"
  2299. */
  2300. Vector2.prototype.getClassName = function () {
  2301. return "Vector2";
  2302. };
  2303. /**
  2304. * Gets current vector hash code
  2305. * @returns the Vector2 hash code as a number
  2306. */
  2307. Vector2.prototype.getHashCode = function () {
  2308. var hash = this.x || 0;
  2309. hash = (hash * 397) ^ (this.y || 0);
  2310. return hash;
  2311. };
  2312. // Operators
  2313. /**
  2314. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2315. * @param array defines the source array
  2316. * @param index defines the offset in source array
  2317. * @returns the current Vector2
  2318. */
  2319. Vector2.prototype.toArray = function (array, index) {
  2320. if (index === void 0) { index = 0; }
  2321. array[index] = this.x;
  2322. array[index + 1] = this.y;
  2323. return this;
  2324. };
  2325. /**
  2326. * Copy the current vector to an array
  2327. * @returns a new array with 2 elements: the Vector2 coordinates.
  2328. */
  2329. Vector2.prototype.asArray = function () {
  2330. var result = new Array();
  2331. this.toArray(result, 0);
  2332. return result;
  2333. };
  2334. /**
  2335. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2336. * @param source defines the source Vector2
  2337. * @returns the current updated Vector2
  2338. */
  2339. Vector2.prototype.copyFrom = function (source) {
  2340. this.x = source.x;
  2341. this.y = source.y;
  2342. return this;
  2343. };
  2344. /**
  2345. * Sets the Vector2 coordinates with the given floats
  2346. * @param x defines the first coordinate
  2347. * @param y defines the second coordinate
  2348. * @returns the current updated Vector2
  2349. */
  2350. Vector2.prototype.copyFromFloats = function (x, y) {
  2351. this.x = x;
  2352. this.y = y;
  2353. return this;
  2354. };
  2355. /**
  2356. * Sets the Vector2 coordinates with the given floats
  2357. * @param x defines the first coordinate
  2358. * @param y defines the second coordinate
  2359. * @returns the current updated Vector2
  2360. */
  2361. Vector2.prototype.set = function (x, y) {
  2362. return this.copyFromFloats(x, y);
  2363. };
  2364. /**
  2365. * Add another vector with the current one
  2366. * @param otherVector defines the other vector
  2367. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2368. */
  2369. Vector2.prototype.add = function (otherVector) {
  2370. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2371. };
  2372. /**
  2373. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2374. * @param otherVector defines the other vector
  2375. * @param result defines the target vector
  2376. * @returns the unmodified current Vector2
  2377. */
  2378. Vector2.prototype.addToRef = function (otherVector, result) {
  2379. result.x = this.x + otherVector.x;
  2380. result.y = this.y + otherVector.y;
  2381. return this;
  2382. };
  2383. /**
  2384. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2385. * @param otherVector defines the other vector
  2386. * @returns the current updated Vector2
  2387. */
  2388. Vector2.prototype.addInPlace = function (otherVector) {
  2389. this.x += otherVector.x;
  2390. this.y += otherVector.y;
  2391. return this;
  2392. };
  2393. /**
  2394. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2395. * @param otherVector defines the other vector
  2396. * @returns a new Vector2
  2397. */
  2398. Vector2.prototype.addVector3 = function (otherVector) {
  2399. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2400. };
  2401. /**
  2402. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2403. * @param otherVector defines the other vector
  2404. * @returns a new Vector2
  2405. */
  2406. Vector2.prototype.subtract = function (otherVector) {
  2407. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2408. };
  2409. /**
  2410. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2411. * @param otherVector defines the other vector
  2412. * @param result defines the target vector
  2413. * @returns the unmodified current Vector2
  2414. */
  2415. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2416. result.x = this.x - otherVector.x;
  2417. result.y = this.y - otherVector.y;
  2418. return this;
  2419. };
  2420. /**
  2421. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2422. * @param otherVector defines the other vector
  2423. * @returns the current updated Vector2
  2424. */
  2425. Vector2.prototype.subtractInPlace = function (otherVector) {
  2426. this.x -= otherVector.x;
  2427. this.y -= otherVector.y;
  2428. return this;
  2429. };
  2430. /**
  2431. * Multiplies in place the current Vector2 coordinates by the given ones
  2432. * @param otherVector defines the other vector
  2433. * @returns the current updated Vector2
  2434. */
  2435. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2436. this.x *= otherVector.x;
  2437. this.y *= otherVector.y;
  2438. return this;
  2439. };
  2440. /**
  2441. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2442. * @param otherVector defines the other vector
  2443. * @returns a new Vector2
  2444. */
  2445. Vector2.prototype.multiply = function (otherVector) {
  2446. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2447. };
  2448. /**
  2449. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2450. * @param otherVector defines the other vector
  2451. * @param result defines the target vector
  2452. * @returns the unmodified current Vector2
  2453. */
  2454. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2455. result.x = this.x * otherVector.x;
  2456. result.y = this.y * otherVector.y;
  2457. return this;
  2458. };
  2459. /**
  2460. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2461. * @param x defines the first coordinate
  2462. * @param y defines the second coordinate
  2463. * @returns a new Vector2
  2464. */
  2465. Vector2.prototype.multiplyByFloats = function (x, y) {
  2466. return new Vector2(this.x * x, this.y * y);
  2467. };
  2468. /**
  2469. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2470. * @param otherVector defines the other vector
  2471. * @returns a new Vector2
  2472. */
  2473. Vector2.prototype.divide = function (otherVector) {
  2474. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2475. };
  2476. /**
  2477. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2478. * @param otherVector defines the other vector
  2479. * @param result defines the target vector
  2480. * @returns the unmodified current Vector2
  2481. */
  2482. Vector2.prototype.divideToRef = function (otherVector, result) {
  2483. result.x = this.x / otherVector.x;
  2484. result.y = this.y / otherVector.y;
  2485. return this;
  2486. };
  2487. /**
  2488. * Divides the current Vector2 coordinates by the given ones
  2489. * @param otherVector defines the other vector
  2490. * @returns the current updated Vector2
  2491. */
  2492. Vector2.prototype.divideInPlace = function (otherVector) {
  2493. return this.divideToRef(otherVector, this);
  2494. };
  2495. /**
  2496. * Gets a new Vector2 with current Vector2 negated coordinates
  2497. * @returns a new Vector2
  2498. */
  2499. Vector2.prototype.negate = function () {
  2500. return new Vector2(-this.x, -this.y);
  2501. };
  2502. /**
  2503. * Multiply the Vector2 coordinates by scale
  2504. * @param scale defines the scaling factor
  2505. * @returns the current updated Vector2
  2506. */
  2507. Vector2.prototype.scaleInPlace = function (scale) {
  2508. this.x *= scale;
  2509. this.y *= scale;
  2510. return this;
  2511. };
  2512. /**
  2513. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2514. * @param scale defines the scaling factor
  2515. * @returns a new Vector2
  2516. */
  2517. Vector2.prototype.scale = function (scale) {
  2518. var result = new Vector2(0, 0);
  2519. this.scaleToRef(scale, result);
  2520. return result;
  2521. };
  2522. /**
  2523. * Scale the current Vector2 values by a factor to a given Vector2
  2524. * @param scale defines the scale factor
  2525. * @param result defines the Vector2 object where to store the result
  2526. * @returns the unmodified current Vector2
  2527. */
  2528. Vector2.prototype.scaleToRef = function (scale, result) {
  2529. result.x = this.x * scale;
  2530. result.y = this.y * scale;
  2531. return this;
  2532. };
  2533. /**
  2534. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2535. * @param scale defines the scale factor
  2536. * @param result defines the Vector2 object where to store the result
  2537. * @returns the unmodified current Vector2
  2538. */
  2539. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2540. result.x += this.x * scale;
  2541. result.y += this.y * scale;
  2542. return this;
  2543. };
  2544. /**
  2545. * Gets a boolean if two vectors are equals
  2546. * @param otherVector defines the other vector
  2547. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2548. */
  2549. Vector2.prototype.equals = function (otherVector) {
  2550. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2551. };
  2552. /**
  2553. * Gets a boolean if two vectors are equals (using an epsilon value)
  2554. * @param otherVector defines the other vector
  2555. * @param epsilon defines the minimal distance to consider equality
  2556. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2557. */
  2558. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2559. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2560. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2561. };
  2562. /**
  2563. * Gets a new Vector2 from current Vector2 floored values
  2564. * @returns a new Vector2
  2565. */
  2566. Vector2.prototype.floor = function () {
  2567. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2568. };
  2569. /**
  2570. * Gets a new Vector2 from current Vector2 floored values
  2571. * @returns a new Vector2
  2572. */
  2573. Vector2.prototype.fract = function () {
  2574. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2575. };
  2576. // Properties
  2577. /**
  2578. * Gets the length of the vector
  2579. * @returns the vector length (float)
  2580. */
  2581. Vector2.prototype.length = function () {
  2582. return Math.sqrt(this.x * this.x + this.y * this.y);
  2583. };
  2584. /**
  2585. * Gets the vector squared length
  2586. * @returns the vector squared length (float)
  2587. */
  2588. Vector2.prototype.lengthSquared = function () {
  2589. return (this.x * this.x + this.y * this.y);
  2590. };
  2591. // Methods
  2592. /**
  2593. * Normalize the vector
  2594. * @returns the current updated Vector2
  2595. */
  2596. Vector2.prototype.normalize = function () {
  2597. var len = this.length();
  2598. if (len === 0)
  2599. return this;
  2600. var num = 1.0 / len;
  2601. this.x *= num;
  2602. this.y *= num;
  2603. return this;
  2604. };
  2605. /**
  2606. * Gets a new Vector2 copied from the Vector2
  2607. * @returns a new Vector2
  2608. */
  2609. Vector2.prototype.clone = function () {
  2610. return new Vector2(this.x, this.y);
  2611. };
  2612. // Statics
  2613. /**
  2614. * Gets a new Vector2(0, 0)
  2615. * @returns a new Vector2
  2616. */
  2617. Vector2.Zero = function () {
  2618. return new Vector2(0, 0);
  2619. };
  2620. /**
  2621. * Gets a new Vector2(1, 1)
  2622. * @returns a new Vector2
  2623. */
  2624. Vector2.One = function () {
  2625. return new Vector2(1, 1);
  2626. };
  2627. /**
  2628. * Gets a new Vector2 set from the given index element of the given array
  2629. * @param array defines the data source
  2630. * @param offset defines the offset in the data source
  2631. * @returns a new Vector2
  2632. */
  2633. Vector2.FromArray = function (array, offset) {
  2634. if (offset === void 0) { offset = 0; }
  2635. return new Vector2(array[offset], array[offset + 1]);
  2636. };
  2637. /**
  2638. * Sets "result" from the given index element of the given array
  2639. * @param array defines the data source
  2640. * @param offset defines the offset in the data source
  2641. * @param result defines the target vector
  2642. */
  2643. Vector2.FromArrayToRef = function (array, offset, result) {
  2644. result.x = array[offset];
  2645. result.y = array[offset + 1];
  2646. };
  2647. /**
  2648. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2649. * @param value1 defines 1st point of control
  2650. * @param value2 defines 2nd point of control
  2651. * @param value3 defines 3rd point of control
  2652. * @param value4 defines 4th point of control
  2653. * @param amount defines the interpolation factor
  2654. * @returns a new Vector2
  2655. */
  2656. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2657. var squared = amount * amount;
  2658. var cubed = amount * squared;
  2659. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2660. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2661. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2662. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2663. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2664. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2665. return new Vector2(x, y);
  2666. };
  2667. /**
  2668. * 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".
  2669. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2670. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2671. * @param value defines the value to clamp
  2672. * @param min defines the lower limit
  2673. * @param max defines the upper limit
  2674. * @returns a new Vector2
  2675. */
  2676. Vector2.Clamp = function (value, min, max) {
  2677. var x = value.x;
  2678. x = (x > max.x) ? max.x : x;
  2679. x = (x < min.x) ? min.x : x;
  2680. var y = value.y;
  2681. y = (y > max.y) ? max.y : y;
  2682. y = (y < min.y) ? min.y : y;
  2683. return new Vector2(x, y);
  2684. };
  2685. /**
  2686. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2687. * @param value1 defines the 1st control point
  2688. * @param tangent1 defines the outgoing tangent
  2689. * @param value2 defines the 2nd control point
  2690. * @param tangent2 defines the incoming tangent
  2691. * @param amount defines the interpolation factor
  2692. * @returns a new Vector2
  2693. */
  2694. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2695. var squared = amount * amount;
  2696. var cubed = amount * squared;
  2697. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2698. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2699. var part3 = (cubed - (2.0 * squared)) + amount;
  2700. var part4 = cubed - squared;
  2701. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2702. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2703. return new Vector2(x, y);
  2704. };
  2705. /**
  2706. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2707. * @param start defines the start vector
  2708. * @param end defines the end vector
  2709. * @param amount defines the interpolation factor
  2710. * @returns a new Vector2
  2711. */
  2712. Vector2.Lerp = function (start, end, amount) {
  2713. var x = start.x + ((end.x - start.x) * amount);
  2714. var y = start.y + ((end.y - start.y) * amount);
  2715. return new Vector2(x, y);
  2716. };
  2717. /**
  2718. * Gets the dot product of the vector "left" and the vector "right"
  2719. * @param left defines first vector
  2720. * @param right defines second vector
  2721. * @returns the dot product (float)
  2722. */
  2723. Vector2.Dot = function (left, right) {
  2724. return left.x * right.x + left.y * right.y;
  2725. };
  2726. /**
  2727. * Returns a new Vector2 equal to the normalized given vector
  2728. * @param vector defines the vector to normalize
  2729. * @returns a new Vector2
  2730. */
  2731. Vector2.Normalize = function (vector) {
  2732. var newVector = vector.clone();
  2733. newVector.normalize();
  2734. return newVector;
  2735. };
  2736. /**
  2737. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2738. * @param left defines 1st vector
  2739. * @param right defines 2nd vector
  2740. * @returns a new Vector2
  2741. */
  2742. Vector2.Minimize = function (left, right) {
  2743. var x = (left.x < right.x) ? left.x : right.x;
  2744. var y = (left.y < right.y) ? left.y : right.y;
  2745. return new Vector2(x, y);
  2746. };
  2747. /**
  2748. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2749. * @param left defines 1st vector
  2750. * @param right defines 2nd vector
  2751. * @returns a new Vector2
  2752. */
  2753. Vector2.Maximize = function (left, right) {
  2754. var x = (left.x > right.x) ? left.x : right.x;
  2755. var y = (left.y > right.y) ? left.y : right.y;
  2756. return new Vector2(x, y);
  2757. };
  2758. /**
  2759. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2760. * @param vector defines the vector to transform
  2761. * @param transformation defines the matrix to apply
  2762. * @returns a new Vector2
  2763. */
  2764. Vector2.Transform = function (vector, transformation) {
  2765. var r = Vector2.Zero();
  2766. Vector2.TransformToRef(vector, transformation, r);
  2767. return r;
  2768. };
  2769. /**
  2770. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2771. * @param vector defines the vector to transform
  2772. * @param transformation defines the matrix to apply
  2773. * @param result defines the target vector
  2774. */
  2775. Vector2.TransformToRef = function (vector, transformation, result) {
  2776. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2777. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2778. result.x = x;
  2779. result.y = y;
  2780. };
  2781. /**
  2782. * Determines if a given vector is included in a triangle
  2783. * @param p defines the vector to test
  2784. * @param p0 defines 1st triangle point
  2785. * @param p1 defines 2nd triangle point
  2786. * @param p2 defines 3rd triangle point
  2787. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2788. */
  2789. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2790. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2791. var sign = a < 0 ? -1 : 1;
  2792. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2793. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2794. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2795. };
  2796. /**
  2797. * Gets the distance between the vectors "value1" and "value2"
  2798. * @param value1 defines first vector
  2799. * @param value2 defines second vector
  2800. * @returns the distance between vectors
  2801. */
  2802. Vector2.Distance = function (value1, value2) {
  2803. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2804. };
  2805. /**
  2806. * Returns the squared distance between the vectors "value1" and "value2"
  2807. * @param value1 defines first vector
  2808. * @param value2 defines second vector
  2809. * @returns the squared distance between vectors
  2810. */
  2811. Vector2.DistanceSquared = function (value1, value2) {
  2812. var x = value1.x - value2.x;
  2813. var y = value1.y - value2.y;
  2814. return (x * x) + (y * y);
  2815. };
  2816. /**
  2817. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2818. * @param value1 defines first vector
  2819. * @param value2 defines second vector
  2820. * @returns a new Vector2
  2821. */
  2822. Vector2.Center = function (value1, value2) {
  2823. var center = value1.add(value2);
  2824. center.scaleInPlace(0.5);
  2825. return center;
  2826. };
  2827. /**
  2828. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2829. * @param p defines the middle point
  2830. * @param segA defines one point of the segment
  2831. * @param segB defines the other point of the segment
  2832. * @returns the shortest distance
  2833. */
  2834. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2835. var l2 = Vector2.DistanceSquared(segA, segB);
  2836. if (l2 === 0.0) {
  2837. return Vector2.Distance(p, segA);
  2838. }
  2839. var v = segB.subtract(segA);
  2840. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2841. var proj = segA.add(v.multiplyByFloats(t, t));
  2842. return Vector2.Distance(p, proj);
  2843. };
  2844. return Vector2;
  2845. }());
  2846. BABYLON.Vector2 = Vector2;
  2847. /**
  2848. * Classed used to store (x,y,z) vector representation
  2849. * A Vector3 is the main object used in 3D geometry
  2850. * It can represent etiher the coordinates of a point the space, either a direction
  2851. * Reminder: Babylon.js uses a left handed forward facing system
  2852. */
  2853. var Vector3 = /** @class */ (function () {
  2854. /**
  2855. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2856. * @param x defines the first coordinates (on X axis)
  2857. * @param y defines the second coordinates (on Y axis)
  2858. * @param z defines the third coordinates (on Z axis)
  2859. */
  2860. function Vector3(
  2861. /**
  2862. * Defines the first coordinates (on X axis)
  2863. */
  2864. x,
  2865. /**
  2866. * Defines the second coordinates (on Y axis)
  2867. */
  2868. y,
  2869. /**
  2870. * Defines the third coordinates (on Z axis)
  2871. */
  2872. z) {
  2873. if (x === void 0) { x = 0; }
  2874. if (y === void 0) { y = 0; }
  2875. if (z === void 0) { z = 0; }
  2876. this.x = x;
  2877. this.y = y;
  2878. this.z = z;
  2879. }
  2880. /**
  2881. * Creates a string representation of the Vector3
  2882. * @returns a string with the Vector3 coordinates.
  2883. */
  2884. Vector3.prototype.toString = function () {
  2885. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2886. };
  2887. /**
  2888. * Gets the class name
  2889. * @returns the string "Vector3"
  2890. */
  2891. Vector3.prototype.getClassName = function () {
  2892. return "Vector3";
  2893. };
  2894. /**
  2895. * Creates the Vector3 hash code
  2896. * @returns a number which tends to be unique between Vector3 instances
  2897. */
  2898. Vector3.prototype.getHashCode = function () {
  2899. var hash = this.x || 0;
  2900. hash = (hash * 397) ^ (this.y || 0);
  2901. hash = (hash * 397) ^ (this.z || 0);
  2902. return hash;
  2903. };
  2904. // Operators
  2905. /**
  2906. * Creates an array containing three elements : the coordinates of the Vector3
  2907. * @returns a new array of numbers
  2908. */
  2909. Vector3.prototype.asArray = function () {
  2910. var result = [];
  2911. this.toArray(result, 0);
  2912. return result;
  2913. };
  2914. /**
  2915. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2916. * @param array defines the destination array
  2917. * @param index defines the offset in the destination array
  2918. * @returns the current Vector3
  2919. */
  2920. Vector3.prototype.toArray = function (array, index) {
  2921. if (index === void 0) { index = 0; }
  2922. array[index] = this.x;
  2923. array[index + 1] = this.y;
  2924. array[index + 2] = this.z;
  2925. return this;
  2926. };
  2927. /**
  2928. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2929. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2930. */
  2931. Vector3.prototype.toQuaternion = function () {
  2932. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2933. };
  2934. /**
  2935. * Adds the given vector to the current Vector3
  2936. * @param otherVector defines the second operand
  2937. * @returns the current updated Vector3
  2938. */
  2939. Vector3.prototype.addInPlace = function (otherVector) {
  2940. this.x += otherVector.x;
  2941. this.y += otherVector.y;
  2942. this.z += otherVector.z;
  2943. return this;
  2944. };
  2945. /**
  2946. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2947. * @param otherVector defines the second operand
  2948. * @returns the resulting Vector3
  2949. */
  2950. Vector3.prototype.add = function (otherVector) {
  2951. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2952. };
  2953. /**
  2954. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2955. * @param otherVector defines the second operand
  2956. * @param result defines the Vector3 object where to store the result
  2957. * @returns the current Vector3
  2958. */
  2959. Vector3.prototype.addToRef = function (otherVector, result) {
  2960. result.x = this.x + otherVector.x;
  2961. result.y = this.y + otherVector.y;
  2962. result.z = this.z + otherVector.z;
  2963. return this;
  2964. };
  2965. /**
  2966. * Subtract the given vector from the current Vector3
  2967. * @param otherVector defines the second operand
  2968. * @returns the current updated Vector3
  2969. */
  2970. Vector3.prototype.subtractInPlace = function (otherVector) {
  2971. this.x -= otherVector.x;
  2972. this.y -= otherVector.y;
  2973. this.z -= otherVector.z;
  2974. return this;
  2975. };
  2976. /**
  2977. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2978. * @param otherVector defines the second operand
  2979. * @returns the resulting Vector3
  2980. */
  2981. Vector3.prototype.subtract = function (otherVector) {
  2982. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2983. };
  2984. /**
  2985. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2986. * @param otherVector defines the second operand
  2987. * @param result defines the Vector3 object where to store the result
  2988. * @returns the current Vector3
  2989. */
  2990. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2991. result.x = this.x - otherVector.x;
  2992. result.y = this.y - otherVector.y;
  2993. result.z = this.z - otherVector.z;
  2994. return this;
  2995. };
  2996. /**
  2997. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2998. * @param x defines the x coordinate of the operand
  2999. * @param y defines the y coordinate of the operand
  3000. * @param z defines the z coordinate of the operand
  3001. * @returns the resulting Vector3
  3002. */
  3003. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  3004. return new Vector3(this.x - x, this.y - y, this.z - z);
  3005. };
  3006. /**
  3007. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3008. * @param x defines the x coordinate of the operand
  3009. * @param y defines the y coordinate of the operand
  3010. * @param z defines the z coordinate of the operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3015. result.x = this.x - x;
  3016. result.y = this.y - y;
  3017. result.z = this.z - z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3022. * @returns a new Vector3
  3023. */
  3024. Vector3.prototype.negate = function () {
  3025. return new Vector3(-this.x, -this.y, -this.z);
  3026. };
  3027. /**
  3028. * Multiplies the Vector3 coordinates by the float "scale"
  3029. * @param scale defines the multiplier factor
  3030. * @returns the current updated Vector3
  3031. */
  3032. Vector3.prototype.scaleInPlace = function (scale) {
  3033. this.x *= scale;
  3034. this.y *= scale;
  3035. this.z *= scale;
  3036. return this;
  3037. };
  3038. /**
  3039. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3040. * @param scale defines the multiplier factor
  3041. * @returns a new Vector3
  3042. */
  3043. Vector3.prototype.scale = function (scale) {
  3044. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3045. };
  3046. /**
  3047. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3048. * @param scale defines the multiplier factor
  3049. * @param result defines the Vector3 object where to store the result
  3050. * @returns the current Vector3
  3051. */
  3052. Vector3.prototype.scaleToRef = function (scale, result) {
  3053. result.x = this.x * scale;
  3054. result.y = this.y * scale;
  3055. result.z = this.z * scale;
  3056. return this;
  3057. };
  3058. /**
  3059. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3060. * @param scale defines the scale factor
  3061. * @param result defines the Vector3 object where to store the result
  3062. * @returns the unmodified current Vector3
  3063. */
  3064. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3065. result.x += this.x * scale;
  3066. result.y += this.y * scale;
  3067. result.z += this.z * scale;
  3068. return this;
  3069. };
  3070. /**
  3071. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3072. * @param otherVector defines the second operand
  3073. * @returns true if both vectors are equals
  3074. */
  3075. Vector3.prototype.equals = function (otherVector) {
  3076. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3077. };
  3078. /**
  3079. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3080. * @param otherVector defines the second operand
  3081. * @param epsilon defines the minimal distance to define values as equals
  3082. * @returns true if both vectors are distant less than epsilon
  3083. */
  3084. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3085. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3086. 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);
  3087. };
  3088. /**
  3089. * Returns true if the current Vector3 coordinates equals the given floats
  3090. * @param x defines the x coordinate of the operand
  3091. * @param y defines the y coordinate of the operand
  3092. * @param z defines the z coordinate of the operand
  3093. * @returns true if both vectors are equals
  3094. */
  3095. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3096. return this.x === x && this.y === y && this.z === z;
  3097. };
  3098. /**
  3099. * Multiplies the current Vector3 coordinates by the given ones
  3100. * @param otherVector defines the second operand
  3101. * @returns the current updated Vector3
  3102. */
  3103. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3104. this.x *= otherVector.x;
  3105. this.y *= otherVector.y;
  3106. this.z *= otherVector.z;
  3107. return this;
  3108. };
  3109. /**
  3110. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3111. * @param otherVector defines the second operand
  3112. * @returns the new Vector3
  3113. */
  3114. Vector3.prototype.multiply = function (otherVector) {
  3115. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3116. };
  3117. /**
  3118. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3119. * @param otherVector defines the second operand
  3120. * @param result defines the Vector3 object where to store the result
  3121. * @returns the current Vector3
  3122. */
  3123. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3124. result.x = this.x * otherVector.x;
  3125. result.y = this.y * otherVector.y;
  3126. result.z = this.z * otherVector.z;
  3127. return this;
  3128. };
  3129. /**
  3130. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3131. * @param x defines the x coordinate of the operand
  3132. * @param y defines the y coordinate of the operand
  3133. * @param z defines the z coordinate of the operand
  3134. * @returns the new Vector3
  3135. */
  3136. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3137. return new Vector3(this.x * x, this.y * y, this.z * z);
  3138. };
  3139. /**
  3140. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3141. * @param otherVector defines the second operand
  3142. * @returns the new Vector3
  3143. */
  3144. Vector3.prototype.divide = function (otherVector) {
  3145. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3146. };
  3147. /**
  3148. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3149. * @param otherVector defines the second operand
  3150. * @param result defines the Vector3 object where to store the result
  3151. * @returns the current Vector3
  3152. */
  3153. Vector3.prototype.divideToRef = function (otherVector, result) {
  3154. result.x = this.x / otherVector.x;
  3155. result.y = this.y / otherVector.y;
  3156. result.z = this.z / otherVector.z;
  3157. return this;
  3158. };
  3159. /**
  3160. * Divides the current Vector3 coordinates by the given ones.
  3161. * @param otherVector defines the second operand
  3162. * @returns the current updated Vector3
  3163. */
  3164. Vector3.prototype.divideInPlace = function (otherVector) {
  3165. return this.divideToRef(otherVector, this);
  3166. };
  3167. /**
  3168. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3169. * @param other defines the second operand
  3170. * @returns the current updated Vector3
  3171. */
  3172. Vector3.prototype.minimizeInPlace = function (other) {
  3173. return this.minimizeInPlaceFromFloats(other.x, other.y, other.z);
  3174. };
  3175. /**
  3176. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3177. * @param other defines the second operand
  3178. * @returns the current updated Vector3
  3179. */
  3180. Vector3.prototype.maximizeInPlace = function (other) {
  3181. return this.maximizeInPlaceFromFloats(other.x, other.y, other.z);
  3182. };
  3183. /**
  3184. * Updates the current Vector3 with the minimal coordinate values between its and the given coordinates
  3185. * @param x defines the x coordinate of the operand
  3186. * @param y defines the y coordinate of the operand
  3187. * @param z defines the z coordinate of the operand
  3188. * @returns the current updated Vector3
  3189. */
  3190. Vector3.prototype.minimizeInPlaceFromFloats = function (x, y, z) {
  3191. this.x = Math.min(this.x, x);
  3192. this.y = Math.min(this.y, y);
  3193. this.z = Math.min(this.z, z);
  3194. return this;
  3195. };
  3196. /**
  3197. * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates.
  3198. * @param x defines the x coordinate of the operand
  3199. * @param y defines the y coordinate of the operand
  3200. * @param z defines the z coordinate of the operand
  3201. * @returns the current updated Vector3
  3202. */
  3203. Vector3.prototype.maximizeInPlaceFromFloats = function (x, y, z) {
  3204. this.x = Math.max(this.x, x);
  3205. this.y = Math.max(this.y, y);
  3206. this.z = Math.max(this.z, z);
  3207. return this;
  3208. };
  3209. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3210. /**
  3211. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3212. */
  3213. get: function () {
  3214. var absX = Math.abs(this.x);
  3215. var absY = Math.abs(this.y);
  3216. if (absX !== absY) {
  3217. return true;
  3218. }
  3219. var absZ = Math.abs(this.z);
  3220. if (absX !== absZ) {
  3221. return true;
  3222. }
  3223. if (absY !== absZ) {
  3224. return true;
  3225. }
  3226. return false;
  3227. },
  3228. enumerable: true,
  3229. configurable: true
  3230. });
  3231. /**
  3232. * Gets a new Vector3 from current Vector3 floored values
  3233. * @returns a new Vector3
  3234. */
  3235. Vector3.prototype.floor = function () {
  3236. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3237. };
  3238. /**
  3239. * Gets a new Vector3 from current Vector3 floored values
  3240. * @returns a new Vector3
  3241. */
  3242. Vector3.prototype.fract = function () {
  3243. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3244. };
  3245. // Properties
  3246. /**
  3247. * Gets the length of the Vector3
  3248. * @returns the length of the Vecto3
  3249. */
  3250. Vector3.prototype.length = function () {
  3251. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3252. };
  3253. /**
  3254. * Gets the squared length of the Vector3
  3255. * @returns squared length of the Vector3
  3256. */
  3257. Vector3.prototype.lengthSquared = function () {
  3258. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3259. };
  3260. /**
  3261. * Normalize the current Vector3.
  3262. * Please note that this is an in place operation.
  3263. * @returns the current updated Vector3
  3264. */
  3265. Vector3.prototype.normalize = function () {
  3266. var len = this.length();
  3267. if (len === 0 || len === 1.0)
  3268. return this;
  3269. var num = 1.0 / len;
  3270. this.x *= num;
  3271. this.y *= num;
  3272. this.z *= num;
  3273. return this;
  3274. };
  3275. /**
  3276. * Normalize the current Vector3 to a new vector
  3277. * @returns the new Vector3
  3278. */
  3279. Vector3.prototype.normalizeToNew = function () {
  3280. var normalized = new Vector3(0, 0, 0);
  3281. this.normalizeToRef(normalized);
  3282. return normalized;
  3283. };
  3284. /**
  3285. * Normalize the current Vector3 to the reference
  3286. * @param reference define the Vector3 to update
  3287. * @returns the updated Vector3
  3288. */
  3289. Vector3.prototype.normalizeToRef = function (reference) {
  3290. var len = this.length();
  3291. if (len === 0 || len === 1.0) {
  3292. reference.set(this.x, this.y, this.z);
  3293. return reference;
  3294. }
  3295. var scale = 1.0 / len;
  3296. this.scaleToRef(scale, reference);
  3297. return reference;
  3298. };
  3299. /**
  3300. * Creates a new Vector3 copied from the current Vector3
  3301. * @returns the new Vector3
  3302. */
  3303. Vector3.prototype.clone = function () {
  3304. return new Vector3(this.x, this.y, this.z);
  3305. };
  3306. /**
  3307. * Copies the given vector coordinates to the current Vector3 ones
  3308. * @param source defines the source Vector3
  3309. * @returns the current updated Vector3
  3310. */
  3311. Vector3.prototype.copyFrom = function (source) {
  3312. this.x = source.x;
  3313. this.y = source.y;
  3314. this.z = source.z;
  3315. return this;
  3316. };
  3317. /**
  3318. * Copies the given floats to the current Vector3 coordinates
  3319. * @param x defines the x coordinate of the operand
  3320. * @param y defines the y coordinate of the operand
  3321. * @param z defines the z coordinate of the operand
  3322. * @returns the current updated Vector3
  3323. */
  3324. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3325. this.x = x;
  3326. this.y = y;
  3327. this.z = z;
  3328. return this;
  3329. };
  3330. /**
  3331. * Copies the given floats to the current Vector3 coordinates
  3332. * @param x defines the x coordinate of the operand
  3333. * @param y defines the y coordinate of the operand
  3334. * @param z defines the z coordinate of the operand
  3335. * @returns the current updated Vector3
  3336. */
  3337. Vector3.prototype.set = function (x, y, z) {
  3338. return this.copyFromFloats(x, y, z);
  3339. };
  3340. // Statics
  3341. /**
  3342. * Get the clip factor between two vectors
  3343. * @param vector0 defines the first operand
  3344. * @param vector1 defines the second operand
  3345. * @param axis defines the axis to use
  3346. * @param size defines the size along the axis
  3347. * @returns the clip factor
  3348. */
  3349. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3350. var d0 = Vector3.Dot(vector0, axis) - size;
  3351. var d1 = Vector3.Dot(vector1, axis) - size;
  3352. var s = d0 / (d0 - d1);
  3353. return s;
  3354. };
  3355. /**
  3356. * Get angle between two vectors
  3357. * @param vector0 angle between vector0 and vector1
  3358. * @param vector1 angle between vector0 and vector1
  3359. * @param normal direction of the normal
  3360. * @return the angle between vector0 and vector1
  3361. */
  3362. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3363. var v0 = vector0.clone().normalize();
  3364. var v1 = vector1.clone().normalize();
  3365. var dot = Vector3.Dot(v0, v1);
  3366. var n = Vector3.Cross(v0, v1);
  3367. if (Vector3.Dot(n, normal) > 0) {
  3368. return Math.acos(dot);
  3369. }
  3370. return -Math.acos(dot);
  3371. };
  3372. /**
  3373. * Returns a new Vector3 set from the index "offset" of the given array
  3374. * @param array defines the source array
  3375. * @param offset defines the offset in the source array
  3376. * @returns the new Vector3
  3377. */
  3378. Vector3.FromArray = function (array, offset) {
  3379. if (!offset) {
  3380. offset = 0;
  3381. }
  3382. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3383. };
  3384. /**
  3385. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3386. * This function is deprecated. Use FromArray instead
  3387. * @param array defines the source array
  3388. * @param offset defines the offset in the source array
  3389. * @returns the new Vector3
  3390. */
  3391. Vector3.FromFloatArray = function (array, offset) {
  3392. return Vector3.FromArray(array, offset);
  3393. };
  3394. /**
  3395. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3396. * @param array defines the source array
  3397. * @param offset defines the offset in the source array
  3398. * @param result defines the Vector3 where to store the result
  3399. */
  3400. Vector3.FromArrayToRef = function (array, offset, result) {
  3401. result.x = array[offset];
  3402. result.y = array[offset + 1];
  3403. result.z = array[offset + 2];
  3404. };
  3405. /**
  3406. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3407. * This function is deprecated. Use FromArrayToRef instead.
  3408. * @param array defines the source array
  3409. * @param offset defines the offset in the source array
  3410. * @param result defines the Vector3 where to store the result
  3411. */
  3412. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3413. return Vector3.FromArrayToRef(array, offset, result);
  3414. };
  3415. /**
  3416. * Sets the given vector "result" with the given floats.
  3417. * @param x defines the x coordinate of the source
  3418. * @param y defines the y coordinate of the source
  3419. * @param z defines the z coordinate of the source
  3420. * @param result defines the Vector3 where to store the result
  3421. */
  3422. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3423. result.x = x;
  3424. result.y = y;
  3425. result.z = z;
  3426. };
  3427. /**
  3428. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3429. * @returns a new empty Vector3
  3430. */
  3431. Vector3.Zero = function () {
  3432. return new Vector3(0.0, 0.0, 0.0);
  3433. };
  3434. /**
  3435. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3436. * @returns a new unit Vector3
  3437. */
  3438. Vector3.One = function () {
  3439. return new Vector3(1.0, 1.0, 1.0);
  3440. };
  3441. /**
  3442. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3443. * @returns a new up Vector3
  3444. */
  3445. Vector3.Up = function () {
  3446. return new Vector3(0.0, 1.0, 0.0);
  3447. };
  3448. /**
  3449. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3450. * @returns a new down Vector3
  3451. */
  3452. Vector3.Down = function () {
  3453. return new Vector3(0.0, -1.0, 0.0);
  3454. };
  3455. /**
  3456. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3457. * @returns a new forward Vector3
  3458. */
  3459. Vector3.Forward = function () {
  3460. return new Vector3(0.0, 0.0, 1.0);
  3461. };
  3462. /**
  3463. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3464. * @returns a new forward Vector3
  3465. */
  3466. Vector3.Backward = function () {
  3467. return new Vector3(0.0, 0.0, -1.0);
  3468. };
  3469. /**
  3470. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3471. * @returns a new right Vector3
  3472. */
  3473. Vector3.Right = function () {
  3474. return new Vector3(1.0, 0.0, 0.0);
  3475. };
  3476. /**
  3477. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3478. * @returns a new left Vector3
  3479. */
  3480. Vector3.Left = function () {
  3481. return new Vector3(-1.0, 0.0, 0.0);
  3482. };
  3483. /**
  3484. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3485. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3486. * @param vector defines the Vector3 to transform
  3487. * @param transformation defines the transformation matrix
  3488. * @returns the transformed Vector3
  3489. */
  3490. Vector3.TransformCoordinates = function (vector, transformation) {
  3491. var result = Vector3.Zero();
  3492. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3493. return result;
  3494. };
  3495. /**
  3496. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3497. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3498. * @param vector defines the Vector3 to transform
  3499. * @param transformation defines the transformation matrix
  3500. * @param result defines the Vector3 where to store the result
  3501. */
  3502. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3503. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3504. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3505. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3506. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3507. result.x = x / w;
  3508. result.y = y / w;
  3509. result.z = z / w;
  3510. };
  3511. /**
  3512. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3513. * This method computes tranformed coordinates only, not transformed direction vectors
  3514. * @param x define the x coordinate of the source vector
  3515. * @param y define the y coordinate of the source vector
  3516. * @param z define the z coordinate of the source vector
  3517. * @param transformation defines the transformation matrix
  3518. * @param result defines the Vector3 where to store the result
  3519. */
  3520. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3521. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3522. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3523. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3524. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3525. result.x = rx / rw;
  3526. result.y = ry / rw;
  3527. result.z = rz / rw;
  3528. };
  3529. /**
  3530. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3531. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3532. * @param vector defines the Vector3 to transform
  3533. * @param transformation defines the transformation matrix
  3534. * @returns the new Vector3
  3535. */
  3536. Vector3.TransformNormal = function (vector, transformation) {
  3537. var result = Vector3.Zero();
  3538. Vector3.TransformNormalToRef(vector, transformation, result);
  3539. return result;
  3540. };
  3541. /**
  3542. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3543. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3544. * @param vector defines the Vector3 to transform
  3545. * @param transformation defines the transformation matrix
  3546. * @param result defines the Vector3 where to store the result
  3547. */
  3548. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3549. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3550. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3551. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3552. result.x = x;
  3553. result.y = y;
  3554. result.z = z;
  3555. };
  3556. /**
  3557. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3558. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3559. * @param x define the x coordinate of the source vector
  3560. * @param y define the y coordinate of the source vector
  3561. * @param z define the z coordinate of the source vector
  3562. * @param transformation defines the transformation matrix
  3563. * @param result defines the Vector3 where to store the result
  3564. */
  3565. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3566. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3567. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3568. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3569. };
  3570. /**
  3571. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3572. * @param value1 defines the first control point
  3573. * @param value2 defines the second control point
  3574. * @param value3 defines the third control point
  3575. * @param value4 defines the fourth control point
  3576. * @param amount defines the amount on the spline to use
  3577. * @returns the new Vector3
  3578. */
  3579. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3580. var squared = amount * amount;
  3581. var cubed = amount * squared;
  3582. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3583. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3584. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3585. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3586. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3587. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3588. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3589. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3590. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3591. return new Vector3(x, y, z);
  3592. };
  3593. /**
  3594. * 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"
  3595. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3596. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3597. * @param value defines the current value
  3598. * @param min defines the lower range value
  3599. * @param max defines the upper range value
  3600. * @returns the new Vector3
  3601. */
  3602. Vector3.Clamp = function (value, min, max) {
  3603. var x = value.x;
  3604. x = (x > max.x) ? max.x : x;
  3605. x = (x < min.x) ? min.x : x;
  3606. var y = value.y;
  3607. y = (y > max.y) ? max.y : y;
  3608. y = (y < min.y) ? min.y : y;
  3609. var z = value.z;
  3610. z = (z > max.z) ? max.z : z;
  3611. z = (z < min.z) ? min.z : z;
  3612. return new Vector3(x, y, z);
  3613. };
  3614. /**
  3615. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3616. * @param value1 defines the first control point
  3617. * @param tangent1 defines the first tangent vector
  3618. * @param value2 defines the second control point
  3619. * @param tangent2 defines the second tangent vector
  3620. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3621. * @returns the new Vector3
  3622. */
  3623. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3624. var squared = amount * amount;
  3625. var cubed = amount * squared;
  3626. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3627. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3628. var part3 = (cubed - (2.0 * squared)) + amount;
  3629. var part4 = cubed - squared;
  3630. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3631. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3632. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3633. return new Vector3(x, y, z);
  3634. };
  3635. /**
  3636. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3637. * @param start defines the start value
  3638. * @param end defines the end value
  3639. * @param amount max defines amount between both (between 0 and 1)
  3640. * @returns the new Vector3
  3641. */
  3642. Vector3.Lerp = function (start, end, amount) {
  3643. var result = new Vector3(0, 0, 0);
  3644. Vector3.LerpToRef(start, end, amount, result);
  3645. return result;
  3646. };
  3647. /**
  3648. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3649. * @param start defines the start value
  3650. * @param end defines the end value
  3651. * @param amount max defines amount between both (between 0 and 1)
  3652. * @param result defines the Vector3 where to store the result
  3653. */
  3654. Vector3.LerpToRef = function (start, end, amount, result) {
  3655. result.x = start.x + ((end.x - start.x) * amount);
  3656. result.y = start.y + ((end.y - start.y) * amount);
  3657. result.z = start.z + ((end.z - start.z) * amount);
  3658. };
  3659. /**
  3660. * Returns the dot product (float) between the vectors "left" and "right"
  3661. * @param left defines the left operand
  3662. * @param right defines the right operand
  3663. * @returns the dot product
  3664. */
  3665. Vector3.Dot = function (left, right) {
  3666. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3667. };
  3668. /**
  3669. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3670. * The cross product is then orthogonal to both "left" and "right"
  3671. * @param left defines the left operand
  3672. * @param right defines the right operand
  3673. * @returns the cross product
  3674. */
  3675. Vector3.Cross = function (left, right) {
  3676. var result = Vector3.Zero();
  3677. Vector3.CrossToRef(left, right, result);
  3678. return result;
  3679. };
  3680. /**
  3681. * Sets the given vector "result" with the cross product of "left" and "right"
  3682. * The cross product is then orthogonal to both "left" and "right"
  3683. * @param left defines the left operand
  3684. * @param right defines the right operand
  3685. * @param result defines the Vector3 where to store the result
  3686. */
  3687. Vector3.CrossToRef = function (left, right, result) {
  3688. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3689. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3690. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3691. result.copyFrom(MathTmp.Vector3[0]);
  3692. };
  3693. /**
  3694. * Returns a new Vector3 as the normalization of the given vector
  3695. * @param vector defines the Vector3 to normalize
  3696. * @returns the new Vector3
  3697. */
  3698. Vector3.Normalize = function (vector) {
  3699. var result = Vector3.Zero();
  3700. Vector3.NormalizeToRef(vector, result);
  3701. return result;
  3702. };
  3703. /**
  3704. * Sets the given vector "result" with the normalization of the given first vector
  3705. * @param vector defines the Vector3 to normalize
  3706. * @param result defines the Vector3 where to store the result
  3707. */
  3708. Vector3.NormalizeToRef = function (vector, result) {
  3709. result.copyFrom(vector);
  3710. result.normalize();
  3711. };
  3712. /**
  3713. * Project a Vector3 onto screen space
  3714. * @param vector defines the Vector3 to project
  3715. * @param world defines the world matrix to use
  3716. * @param transform defines the transform (view x projection) matrix to use
  3717. * @param viewport defines the screen viewport to use
  3718. * @returns the new Vector3
  3719. */
  3720. Vector3.Project = function (vector, world, transform, viewport) {
  3721. var cw = viewport.width;
  3722. var ch = viewport.height;
  3723. var cx = viewport.x;
  3724. var cy = viewport.y;
  3725. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3726. 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);
  3727. var matrix = MathTmp.Matrix[0];
  3728. world.multiplyToRef(transform, matrix);
  3729. matrix.multiplyToRef(viewportMatrix, matrix);
  3730. return Vector3.TransformCoordinates(vector, matrix);
  3731. };
  3732. /**
  3733. * Unproject from screen space to object space
  3734. * @param source defines the screen space Vector3 to use
  3735. * @param viewportWidth defines the current width of the viewport
  3736. * @param viewportHeight defines the current height of the viewport
  3737. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3738. * @param transform defines the transform (view x projection) matrix to use
  3739. * @returns the new Vector3
  3740. */
  3741. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3742. var matrix = MathTmp.Matrix[0];
  3743. world.multiplyToRef(transform, matrix);
  3744. matrix.invert();
  3745. source.x = source.x / viewportWidth * 2 - 1;
  3746. source.y = -(source.y / viewportHeight * 2 - 1);
  3747. var vector = Vector3.TransformCoordinates(source, matrix);
  3748. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3749. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3750. vector = vector.scale(1.0 / num);
  3751. }
  3752. return vector;
  3753. };
  3754. /**
  3755. * Unproject from screen space to object space
  3756. * @param source defines the screen space Vector3 to use
  3757. * @param viewportWidth defines the current width of the viewport
  3758. * @param viewportHeight defines the current height of the viewport
  3759. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3760. * @param view defines the view matrix to use
  3761. * @param projection defines the projection matrix to use
  3762. * @returns the new Vector3
  3763. */
  3764. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3765. var result = Vector3.Zero();
  3766. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3767. return result;
  3768. };
  3769. /**
  3770. * Unproject from screen space to object space
  3771. * @param source defines the screen space Vector3 to use
  3772. * @param viewportWidth defines the current width of the viewport
  3773. * @param viewportHeight defines the current height of the viewport
  3774. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3775. * @param view defines the view matrix to use
  3776. * @param projection defines the projection matrix to use
  3777. * @param result defines the Vector3 where to store the result
  3778. */
  3779. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3780. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3781. };
  3782. /**
  3783. * Unproject from screen space to object space
  3784. * @param sourceX defines the screen space x coordinate to use
  3785. * @param sourceY defines the screen space y coordinate to use
  3786. * @param sourceZ defines the screen space z coordinate to use
  3787. * @param viewportWidth defines the current width of the viewport
  3788. * @param viewportHeight defines the current height of the viewport
  3789. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3790. * @param view defines the view matrix to use
  3791. * @param projection defines the projection matrix to use
  3792. * @param result defines the Vector3 where to store the result
  3793. */
  3794. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3795. var matrix = MathTmp.Matrix[0];
  3796. world.multiplyToRef(view, matrix);
  3797. matrix.multiplyToRef(projection, matrix);
  3798. matrix.invert();
  3799. var screenSource = MathTmp.Vector3[0];
  3800. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3801. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3802. screenSource.z = 2 * sourceZ - 1.0;
  3803. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3804. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3805. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3806. result.scaleInPlace(1.0 / num);
  3807. }
  3808. };
  3809. /**
  3810. * Gets the minimal coordinate values between two Vector3
  3811. * @param left defines the first operand
  3812. * @param right defines the second operand
  3813. * @returns the new Vector3
  3814. */
  3815. Vector3.Minimize = function (left, right) {
  3816. var min = left.clone();
  3817. min.minimizeInPlace(right);
  3818. return min;
  3819. };
  3820. /**
  3821. * Gets the maximal coordinate values between two Vector3
  3822. * @param left defines the first operand
  3823. * @param right defines the second operand
  3824. * @returns the new Vector3
  3825. */
  3826. Vector3.Maximize = function (left, right) {
  3827. var max = left.clone();
  3828. max.maximizeInPlace(right);
  3829. return max;
  3830. };
  3831. /**
  3832. * Returns the distance between the vectors "value1" and "value2"
  3833. * @param value1 defines the first operand
  3834. * @param value2 defines the second operand
  3835. * @returns the distance
  3836. */
  3837. Vector3.Distance = function (value1, value2) {
  3838. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3839. };
  3840. /**
  3841. * Returns the squared distance between the vectors "value1" and "value2"
  3842. * @param value1 defines the first operand
  3843. * @param value2 defines the second operand
  3844. * @returns the squared distance
  3845. */
  3846. Vector3.DistanceSquared = function (value1, value2) {
  3847. var x = value1.x - value2.x;
  3848. var y = value1.y - value2.y;
  3849. var z = value1.z - value2.z;
  3850. return (x * x) + (y * y) + (z * z);
  3851. };
  3852. /**
  3853. * Returns a new Vector3 located at the center between "value1" and "value2"
  3854. * @param value1 defines the first operand
  3855. * @param value2 defines the second operand
  3856. * @returns the new Vector3
  3857. */
  3858. Vector3.Center = function (value1, value2) {
  3859. var center = value1.add(value2);
  3860. center.scaleInPlace(0.5);
  3861. return center;
  3862. };
  3863. /**
  3864. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3865. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3866. * to something in order to rotate it from its local system to the given target system
  3867. * Note: axis1, axis2 and axis3 are normalized during this operation
  3868. * @param axis1 defines the first axis
  3869. * @param axis2 defines the second axis
  3870. * @param axis3 defines the third axis
  3871. * @returns a new Vector3
  3872. */
  3873. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3874. var rotation = Vector3.Zero();
  3875. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3876. return rotation;
  3877. };
  3878. /**
  3879. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3880. * @param axis1 defines the first axis
  3881. * @param axis2 defines the second axis
  3882. * @param axis3 defines the third axis
  3883. * @param ref defines the Vector3 where to store the result
  3884. */
  3885. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3886. var quat = MathTmp.Quaternion[0];
  3887. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3888. quat.toEulerAnglesToRef(ref);
  3889. };
  3890. return Vector3;
  3891. }());
  3892. BABYLON.Vector3 = Vector3;
  3893. /**
  3894. * Vector4 class created for EulerAngle class conversion to Quaternion
  3895. */
  3896. var Vector4 = /** @class */ (function () {
  3897. /**
  3898. * Creates a Vector4 object from the given floats.
  3899. * @param x x value of the vector
  3900. * @param y y value of the vector
  3901. * @param z z value of the vector
  3902. * @param w w value of the vector
  3903. */
  3904. function Vector4(
  3905. /** x value of the vector */
  3906. x,
  3907. /** y value of the vector */
  3908. y,
  3909. /** z value of the vector */
  3910. z,
  3911. /** w value of the vector */
  3912. w) {
  3913. this.x = x;
  3914. this.y = y;
  3915. this.z = z;
  3916. this.w = w;
  3917. }
  3918. /**
  3919. * Returns the string with the Vector4 coordinates.
  3920. * @returns a string containing all the vector values
  3921. */
  3922. Vector4.prototype.toString = function () {
  3923. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3924. };
  3925. /**
  3926. * Returns the string "Vector4".
  3927. * @returns "Vector4"
  3928. */
  3929. Vector4.prototype.getClassName = function () {
  3930. return "Vector4";
  3931. };
  3932. /**
  3933. * Returns the Vector4 hash code.
  3934. * @returns a unique hash code
  3935. */
  3936. Vector4.prototype.getHashCode = function () {
  3937. var hash = this.x || 0;
  3938. hash = (hash * 397) ^ (this.y || 0);
  3939. hash = (hash * 397) ^ (this.z || 0);
  3940. hash = (hash * 397) ^ (this.w || 0);
  3941. return hash;
  3942. };
  3943. // Operators
  3944. /**
  3945. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3946. * @returns the resulting array
  3947. */
  3948. Vector4.prototype.asArray = function () {
  3949. var result = new Array();
  3950. this.toArray(result, 0);
  3951. return result;
  3952. };
  3953. /**
  3954. * Populates the given array from the given index with the Vector4 coordinates.
  3955. * @param array array to populate
  3956. * @param index index of the array to start at (default: 0)
  3957. * @returns the Vector4.
  3958. */
  3959. Vector4.prototype.toArray = function (array, index) {
  3960. if (index === undefined) {
  3961. index = 0;
  3962. }
  3963. array[index] = this.x;
  3964. array[index + 1] = this.y;
  3965. array[index + 2] = this.z;
  3966. array[index + 3] = this.w;
  3967. return this;
  3968. };
  3969. /**
  3970. * Adds the given vector to the current Vector4.
  3971. * @param otherVector the vector to add
  3972. * @returns the updated Vector4.
  3973. */
  3974. Vector4.prototype.addInPlace = function (otherVector) {
  3975. this.x += otherVector.x;
  3976. this.y += otherVector.y;
  3977. this.z += otherVector.z;
  3978. this.w += otherVector.w;
  3979. return this;
  3980. };
  3981. /**
  3982. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3983. * @param otherVector the vector to add
  3984. * @returns the resulting vector
  3985. */
  3986. Vector4.prototype.add = function (otherVector) {
  3987. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3988. };
  3989. /**
  3990. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3991. * @param otherVector the vector to add
  3992. * @param result the vector to store the result
  3993. * @returns the current Vector4.
  3994. */
  3995. Vector4.prototype.addToRef = function (otherVector, result) {
  3996. result.x = this.x + otherVector.x;
  3997. result.y = this.y + otherVector.y;
  3998. result.z = this.z + otherVector.z;
  3999. result.w = this.w + otherVector.w;
  4000. return this;
  4001. };
  4002. /**
  4003. * Subtract in place the given vector from the current Vector4.
  4004. * @param otherVector the vector to subtract
  4005. * @returns the updated Vector4.
  4006. */
  4007. Vector4.prototype.subtractInPlace = function (otherVector) {
  4008. this.x -= otherVector.x;
  4009. this.y -= otherVector.y;
  4010. this.z -= otherVector.z;
  4011. this.w -= otherVector.w;
  4012. return this;
  4013. };
  4014. /**
  4015. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  4016. * @param otherVector the vector to add
  4017. * @returns the new vector with the result
  4018. */
  4019. Vector4.prototype.subtract = function (otherVector) {
  4020. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  4021. };
  4022. /**
  4023. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  4024. * @param otherVector the vector to subtract
  4025. * @param result the vector to store the result
  4026. * @returns the current Vector4.
  4027. */
  4028. Vector4.prototype.subtractToRef = function (otherVector, result) {
  4029. result.x = this.x - otherVector.x;
  4030. result.y = this.y - otherVector.y;
  4031. result.z = this.z - otherVector.z;
  4032. result.w = this.w - otherVector.w;
  4033. return this;
  4034. };
  4035. /**
  4036. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4037. */
  4038. /**
  4039. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4040. * @param x value to subtract
  4041. * @param y value to subtract
  4042. * @param z value to subtract
  4043. * @param w value to subtract
  4044. * @returns new vector containing the result
  4045. */
  4046. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  4047. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  4048. };
  4049. /**
  4050. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4051. * @param x value to subtract
  4052. * @param y value to subtract
  4053. * @param z value to subtract
  4054. * @param w value to subtract
  4055. * @param result the vector to store the result in
  4056. * @returns the current Vector4.
  4057. */
  4058. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  4059. result.x = this.x - x;
  4060. result.y = this.y - y;
  4061. result.z = this.z - z;
  4062. result.w = this.w - w;
  4063. return this;
  4064. };
  4065. /**
  4066. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  4067. * @returns a new vector with the negated values
  4068. */
  4069. Vector4.prototype.negate = function () {
  4070. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  4071. };
  4072. /**
  4073. * Multiplies the current Vector4 coordinates by scale (float).
  4074. * @param scale the number to scale with
  4075. * @returns the updated Vector4.
  4076. */
  4077. Vector4.prototype.scaleInPlace = function (scale) {
  4078. this.x *= scale;
  4079. this.y *= scale;
  4080. this.z *= scale;
  4081. this.w *= scale;
  4082. return this;
  4083. };
  4084. /**
  4085. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4086. * @param scale the number to scale with
  4087. * @returns a new vector with the result
  4088. */
  4089. Vector4.prototype.scale = function (scale) {
  4090. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4091. };
  4092. /**
  4093. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4094. * @param scale the number to scale with
  4095. * @param result a vector to store the result in
  4096. * @returns the current Vector4.
  4097. */
  4098. Vector4.prototype.scaleToRef = function (scale, result) {
  4099. result.x = this.x * scale;
  4100. result.y = this.y * scale;
  4101. result.z = this.z * scale;
  4102. result.w = this.w * scale;
  4103. return this;
  4104. };
  4105. /**
  4106. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4107. * @param scale defines the scale factor
  4108. * @param result defines the Vector4 object where to store the result
  4109. * @returns the unmodified current Vector4
  4110. */
  4111. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4112. result.x += this.x * scale;
  4113. result.y += this.y * scale;
  4114. result.z += this.z * scale;
  4115. result.w += this.w * scale;
  4116. return this;
  4117. };
  4118. /**
  4119. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4120. * @param otherVector the vector to compare against
  4121. * @returns true if they are equal
  4122. */
  4123. Vector4.prototype.equals = function (otherVector) {
  4124. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4125. };
  4126. /**
  4127. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4128. * @param otherVector vector to compare against
  4129. * @param epsilon (Default: very small number)
  4130. * @returns true if they are equal
  4131. */
  4132. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4133. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4134. return otherVector
  4135. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4136. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4137. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4138. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4139. };
  4140. /**
  4141. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4142. * @param x x value to compare against
  4143. * @param y y value to compare against
  4144. * @param z z value to compare against
  4145. * @param w w value to compare against
  4146. * @returns true if equal
  4147. */
  4148. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4149. return this.x === x && this.y === y && this.z === z && this.w === w;
  4150. };
  4151. /**
  4152. * Multiplies in place the current Vector4 by the given one.
  4153. * @param otherVector vector to multiple with
  4154. * @returns the updated Vector4.
  4155. */
  4156. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4157. this.x *= otherVector.x;
  4158. this.y *= otherVector.y;
  4159. this.z *= otherVector.z;
  4160. this.w *= otherVector.w;
  4161. return this;
  4162. };
  4163. /**
  4164. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4165. * @param otherVector vector to multiple with
  4166. * @returns resulting new vector
  4167. */
  4168. Vector4.prototype.multiply = function (otherVector) {
  4169. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4170. };
  4171. /**
  4172. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4173. * @param otherVector vector to multiple with
  4174. * @param result vector to store the result
  4175. * @returns the current Vector4.
  4176. */
  4177. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4178. result.x = this.x * otherVector.x;
  4179. result.y = this.y * otherVector.y;
  4180. result.z = this.z * otherVector.z;
  4181. result.w = this.w * otherVector.w;
  4182. return this;
  4183. };
  4184. /**
  4185. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4186. * @param x x value multiply with
  4187. * @param y y value multiply with
  4188. * @param z z value multiply with
  4189. * @param w w value multiply with
  4190. * @returns resulting new vector
  4191. */
  4192. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4193. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4194. };
  4195. /**
  4196. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4197. * @param otherVector vector to devide with
  4198. * @returns resulting new vector
  4199. */
  4200. Vector4.prototype.divide = function (otherVector) {
  4201. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4202. };
  4203. /**
  4204. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4205. * @param otherVector vector to devide with
  4206. * @param result vector to store the result
  4207. * @returns the current Vector4.
  4208. */
  4209. Vector4.prototype.divideToRef = function (otherVector, result) {
  4210. result.x = this.x / otherVector.x;
  4211. result.y = this.y / otherVector.y;
  4212. result.z = this.z / otherVector.z;
  4213. result.w = this.w / otherVector.w;
  4214. return this;
  4215. };
  4216. /**
  4217. * Divides the current Vector3 coordinates by the given ones.
  4218. * @param otherVector vector to devide with
  4219. * @returns the updated Vector3.
  4220. */
  4221. Vector4.prototype.divideInPlace = function (otherVector) {
  4222. return this.divideToRef(otherVector, this);
  4223. };
  4224. /**
  4225. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4226. * @param other defines the second operand
  4227. * @returns the current updated Vector4
  4228. */
  4229. Vector4.prototype.minimizeInPlace = function (other) {
  4230. if (other.x < this.x)
  4231. this.x = other.x;
  4232. if (other.y < this.y)
  4233. this.y = other.y;
  4234. if (other.z < this.z)
  4235. this.z = other.z;
  4236. if (other.w < this.w)
  4237. this.w = other.w;
  4238. return this;
  4239. };
  4240. /**
  4241. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4242. * @param other defines the second operand
  4243. * @returns the current updated Vector4
  4244. */
  4245. Vector4.prototype.maximizeInPlace = function (other) {
  4246. if (other.x > this.x)
  4247. this.x = other.x;
  4248. if (other.y > this.y)
  4249. this.y = other.y;
  4250. if (other.z > this.z)
  4251. this.z = other.z;
  4252. if (other.w > this.w)
  4253. this.w = other.w;
  4254. return this;
  4255. };
  4256. /**
  4257. * Gets a new Vector4 from current Vector4 floored values
  4258. * @returns a new Vector4
  4259. */
  4260. Vector4.prototype.floor = function () {
  4261. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4262. };
  4263. /**
  4264. * Gets a new Vector4 from current Vector3 floored values
  4265. * @returns a new Vector4
  4266. */
  4267. Vector4.prototype.fract = function () {
  4268. 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));
  4269. };
  4270. // Properties
  4271. /**
  4272. * Returns the Vector4 length (float).
  4273. * @returns the length
  4274. */
  4275. Vector4.prototype.length = function () {
  4276. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4277. };
  4278. /**
  4279. * Returns the Vector4 squared length (float).
  4280. * @returns the length squared
  4281. */
  4282. Vector4.prototype.lengthSquared = function () {
  4283. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4284. };
  4285. // Methods
  4286. /**
  4287. * Normalizes in place the Vector4.
  4288. * @returns the updated Vector4.
  4289. */
  4290. Vector4.prototype.normalize = function () {
  4291. var len = this.length();
  4292. if (len === 0)
  4293. return this;
  4294. var num = 1.0 / len;
  4295. this.x *= num;
  4296. this.y *= num;
  4297. this.z *= num;
  4298. this.w *= num;
  4299. return this;
  4300. };
  4301. /**
  4302. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4303. * @returns this converted to a new vector3
  4304. */
  4305. Vector4.prototype.toVector3 = function () {
  4306. return new Vector3(this.x, this.y, this.z);
  4307. };
  4308. /**
  4309. * Returns a new Vector4 copied from the current one.
  4310. * @returns the new cloned vector
  4311. */
  4312. Vector4.prototype.clone = function () {
  4313. return new Vector4(this.x, this.y, this.z, this.w);
  4314. };
  4315. /**
  4316. * Updates the current Vector4 with the given one coordinates.
  4317. * @param source the source vector to copy from
  4318. * @returns the updated Vector4.
  4319. */
  4320. Vector4.prototype.copyFrom = function (source) {
  4321. this.x = source.x;
  4322. this.y = source.y;
  4323. this.z = source.z;
  4324. this.w = source.w;
  4325. return this;
  4326. };
  4327. /**
  4328. * Updates the current Vector4 coordinates with the given floats.
  4329. * @param x float to copy from
  4330. * @param y float to copy from
  4331. * @param z float to copy from
  4332. * @param w float to copy from
  4333. * @returns the updated Vector4.
  4334. */
  4335. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4336. this.x = x;
  4337. this.y = y;
  4338. this.z = z;
  4339. this.w = w;
  4340. return this;
  4341. };
  4342. /**
  4343. * Updates the current Vector4 coordinates with the given floats.
  4344. * @param x float to set from
  4345. * @param y float to set from
  4346. * @param z float to set from
  4347. * @param w float to set from
  4348. * @returns the updated Vector4.
  4349. */
  4350. Vector4.prototype.set = function (x, y, z, w) {
  4351. return this.copyFromFloats(x, y, z, w);
  4352. };
  4353. // Statics
  4354. /**
  4355. * Returns a new Vector4 set from the starting index of the given array.
  4356. * @param array the array to pull values from
  4357. * @param offset the offset into the array to start at
  4358. * @returns the new vector
  4359. */
  4360. Vector4.FromArray = function (array, offset) {
  4361. if (!offset) {
  4362. offset = 0;
  4363. }
  4364. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4365. };
  4366. /**
  4367. * Updates the given vector "result" from the starting index of the given array.
  4368. * @param array the array to pull values from
  4369. * @param offset the offset into the array to start at
  4370. * @param result the vector to store the result in
  4371. */
  4372. Vector4.FromArrayToRef = function (array, offset, result) {
  4373. result.x = array[offset];
  4374. result.y = array[offset + 1];
  4375. result.z = array[offset + 2];
  4376. result.w = array[offset + 3];
  4377. };
  4378. /**
  4379. * Updates the given vector "result" from the starting index of the given Float32Array.
  4380. * @param array the array to pull values from
  4381. * @param offset the offset into the array to start at
  4382. * @param result the vector to store the result in
  4383. */
  4384. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4385. Vector4.FromArrayToRef(array, offset, result);
  4386. };
  4387. /**
  4388. * Updates the given vector "result" coordinates from the given floats.
  4389. * @param x float to set from
  4390. * @param y float to set from
  4391. * @param z float to set from
  4392. * @param w float to set from
  4393. * @param result the vector to the floats in
  4394. */
  4395. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4396. result.x = x;
  4397. result.y = y;
  4398. result.z = z;
  4399. result.w = w;
  4400. };
  4401. /**
  4402. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4403. * @returns the new vector
  4404. */
  4405. Vector4.Zero = function () {
  4406. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4407. };
  4408. /**
  4409. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4410. * @returns the new vector
  4411. */
  4412. Vector4.One = function () {
  4413. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4414. };
  4415. /**
  4416. * Returns a new normalized Vector4 from the given one.
  4417. * @param vector the vector to normalize
  4418. * @returns the vector
  4419. */
  4420. Vector4.Normalize = function (vector) {
  4421. var result = Vector4.Zero();
  4422. Vector4.NormalizeToRef(vector, result);
  4423. return result;
  4424. };
  4425. /**
  4426. * Updates the given vector "result" from the normalization of the given one.
  4427. * @param vector the vector to normalize
  4428. * @param result the vector to store the result in
  4429. */
  4430. Vector4.NormalizeToRef = function (vector, result) {
  4431. result.copyFrom(vector);
  4432. result.normalize();
  4433. };
  4434. /**
  4435. * Returns a vector with the minimum values from the left and right vectors
  4436. * @param left left vector to minimize
  4437. * @param right right vector to minimize
  4438. * @returns a new vector with the minimum of the left and right vector values
  4439. */
  4440. Vector4.Minimize = function (left, right) {
  4441. var min = left.clone();
  4442. min.minimizeInPlace(right);
  4443. return min;
  4444. };
  4445. /**
  4446. * Returns a vector with the maximum values from the left and right vectors
  4447. * @param left left vector to maximize
  4448. * @param right right vector to maximize
  4449. * @returns a new vector with the maximum of the left and right vector values
  4450. */
  4451. Vector4.Maximize = function (left, right) {
  4452. var max = left.clone();
  4453. max.maximizeInPlace(right);
  4454. return max;
  4455. };
  4456. /**
  4457. * Returns the distance (float) between the vectors "value1" and "value2".
  4458. * @param value1 value to calulate the distance between
  4459. * @param value2 value to calulate the distance between
  4460. * @return the distance between the two vectors
  4461. */
  4462. Vector4.Distance = function (value1, value2) {
  4463. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4464. };
  4465. /**
  4466. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4467. * @param value1 value to calulate the distance between
  4468. * @param value2 value to calulate the distance between
  4469. * @return the distance between the two vectors squared
  4470. */
  4471. Vector4.DistanceSquared = function (value1, value2) {
  4472. var x = value1.x - value2.x;
  4473. var y = value1.y - value2.y;
  4474. var z = value1.z - value2.z;
  4475. var w = value1.w - value2.w;
  4476. return (x * x) + (y * y) + (z * z) + (w * w);
  4477. };
  4478. /**
  4479. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4480. * @param value1 value to calulate the center between
  4481. * @param value2 value to calulate the center between
  4482. * @return the center between the two vectors
  4483. */
  4484. Vector4.Center = function (value1, value2) {
  4485. var center = value1.add(value2);
  4486. center.scaleInPlace(0.5);
  4487. return center;
  4488. };
  4489. /**
  4490. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4491. * This methods computes transformed normalized direction vectors only.
  4492. * @param vector the vector to transform
  4493. * @param transformation the transformation matrix to apply
  4494. * @returns the new vector
  4495. */
  4496. Vector4.TransformNormal = function (vector, transformation) {
  4497. var result = Vector4.Zero();
  4498. Vector4.TransformNormalToRef(vector, transformation, result);
  4499. return result;
  4500. };
  4501. /**
  4502. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4503. * This methods computes transformed normalized direction vectors only.
  4504. * @param vector the vector to transform
  4505. * @param transformation the transformation matrix to apply
  4506. * @param result the vector to store the result in
  4507. */
  4508. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4509. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4510. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4511. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4512. result.x = x;
  4513. result.y = y;
  4514. result.z = z;
  4515. result.w = vector.w;
  4516. };
  4517. /**
  4518. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4519. * This methods computes transformed normalized direction vectors only.
  4520. * @param x value to transform
  4521. * @param y value to transform
  4522. * @param z value to transform
  4523. * @param w value to transform
  4524. * @param transformation the transformation matrix to apply
  4525. * @param result the vector to store the results in
  4526. */
  4527. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4528. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4529. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4530. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4531. result.w = w;
  4532. };
  4533. return Vector4;
  4534. }());
  4535. BABYLON.Vector4 = Vector4;
  4536. /**
  4537. * Size containing widht and height
  4538. */
  4539. var Size = /** @class */ (function () {
  4540. /**
  4541. * Creates a Size object from the given width and height (floats).
  4542. * @param width width of the new size
  4543. * @param height height of the new size
  4544. */
  4545. function Size(width, height) {
  4546. this.width = width;
  4547. this.height = height;
  4548. }
  4549. /**
  4550. * Returns a string with the Size width and height
  4551. * @returns a string with the Size width and height
  4552. */
  4553. Size.prototype.toString = function () {
  4554. return "{W: " + this.width + ", H: " + this.height + "}";
  4555. };
  4556. /**
  4557. * "Size"
  4558. * @returns the string "Size"
  4559. */
  4560. Size.prototype.getClassName = function () {
  4561. return "Size";
  4562. };
  4563. /**
  4564. * Returns the Size hash code.
  4565. * @returns a hash code for a unique width and height
  4566. */
  4567. Size.prototype.getHashCode = function () {
  4568. var hash = this.width || 0;
  4569. hash = (hash * 397) ^ (this.height || 0);
  4570. return hash;
  4571. };
  4572. /**
  4573. * Updates the current size from the given one.
  4574. * @param src the given size
  4575. */
  4576. Size.prototype.copyFrom = function (src) {
  4577. this.width = src.width;
  4578. this.height = src.height;
  4579. };
  4580. /**
  4581. * Updates in place the current Size from the given floats.
  4582. * @param width width of the new size
  4583. * @param height height of the new size
  4584. * @returns the updated Size.
  4585. */
  4586. Size.prototype.copyFromFloats = function (width, height) {
  4587. this.width = width;
  4588. this.height = height;
  4589. return this;
  4590. };
  4591. /**
  4592. * Updates in place the current Size from the given floats.
  4593. * @param width width to set
  4594. * @param height height to set
  4595. * @returns the updated Size.
  4596. */
  4597. Size.prototype.set = function (width, height) {
  4598. return this.copyFromFloats(width, height);
  4599. };
  4600. /**
  4601. * Multiplies the width and height by numbers
  4602. * @param w factor to multiple the width by
  4603. * @param h factor to multiple the height by
  4604. * @returns a new Size set with the multiplication result of the current Size and the given floats.
  4605. */
  4606. Size.prototype.multiplyByFloats = function (w, h) {
  4607. return new Size(this.width * w, this.height * h);
  4608. };
  4609. /**
  4610. * Clones the size
  4611. * @returns a new Size copied from the given one.
  4612. */
  4613. Size.prototype.clone = function () {
  4614. return new Size(this.width, this.height);
  4615. };
  4616. /**
  4617. * True if the current Size and the given one width and height are strictly equal.
  4618. * @param other the other size to compare against
  4619. * @returns True if the current Size and the given one width and height are strictly equal.
  4620. */
  4621. Size.prototype.equals = function (other) {
  4622. if (!other) {
  4623. return false;
  4624. }
  4625. return (this.width === other.width) && (this.height === other.height);
  4626. };
  4627. Object.defineProperty(Size.prototype, "surface", {
  4628. /**
  4629. * The surface of the Size : width * height (float).
  4630. */
  4631. get: function () {
  4632. return this.width * this.height;
  4633. },
  4634. enumerable: true,
  4635. configurable: true
  4636. });
  4637. /**
  4638. * Create a new size of zero
  4639. * @returns a new Size set to (0.0, 0.0)
  4640. */
  4641. Size.Zero = function () {
  4642. return new Size(0.0, 0.0);
  4643. };
  4644. /**
  4645. * Sums the width and height of two sizes
  4646. * @param otherSize size to add to this size
  4647. * @returns a new Size set as the addition result of the current Size and the given one.
  4648. */
  4649. Size.prototype.add = function (otherSize) {
  4650. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4651. return r;
  4652. };
  4653. /**
  4654. * Subtracts the width and height of two
  4655. * @param otherSize size to subtract to this size
  4656. * @returns a new Size set as the subtraction result of the given one from the current Size.
  4657. */
  4658. Size.prototype.subtract = function (otherSize) {
  4659. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4660. return r;
  4661. };
  4662. /**
  4663. * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
  4664. * @param start starting size to lerp between
  4665. * @param end end size to lerp between
  4666. * @param amount amount to lerp between the start and end values
  4667. * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
  4668. */
  4669. Size.Lerp = function (start, end, amount) {
  4670. var w = start.width + ((end.width - start.width) * amount);
  4671. var h = start.height + ((end.height - start.height) * amount);
  4672. return new Size(w, h);
  4673. };
  4674. return Size;
  4675. }());
  4676. BABYLON.Size = Size;
  4677. /**
  4678. * Class used to store quaternion data
  4679. * @see https://en.wikipedia.org/wiki/Quaternion
  4680. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4681. */
  4682. var Quaternion = /** @class */ (function () {
  4683. /**
  4684. * Creates a new Quaternion from the given floats
  4685. * @param x defines the first component (0 by default)
  4686. * @param y defines the second component (0 by default)
  4687. * @param z defines the third component (0 by default)
  4688. * @param w defines the fourth component (1.0 by default)
  4689. */
  4690. function Quaternion(
  4691. /** defines the first component (0 by default) */
  4692. x,
  4693. /** defines the second component (0 by default) */
  4694. y,
  4695. /** defines the third component (0 by default) */
  4696. z,
  4697. /** defines the fourth component (1.0 by default) */
  4698. w) {
  4699. if (x === void 0) { x = 0.0; }
  4700. if (y === void 0) { y = 0.0; }
  4701. if (z === void 0) { z = 0.0; }
  4702. if (w === void 0) { w = 1.0; }
  4703. this.x = x;
  4704. this.y = y;
  4705. this.z = z;
  4706. this.w = w;
  4707. }
  4708. /**
  4709. * Gets a string representation for the current quaternion
  4710. * @returns a string with the Quaternion coordinates
  4711. */
  4712. Quaternion.prototype.toString = function () {
  4713. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4714. };
  4715. /**
  4716. * Gets the class name of the quaternion
  4717. * @returns the string "Quaternion"
  4718. */
  4719. Quaternion.prototype.getClassName = function () {
  4720. return "Quaternion";
  4721. };
  4722. /**
  4723. * Gets a hash code for this quaternion
  4724. * @returns the quaternion hash code
  4725. */
  4726. Quaternion.prototype.getHashCode = function () {
  4727. var hash = this.x || 0;
  4728. hash = (hash * 397) ^ (this.y || 0);
  4729. hash = (hash * 397) ^ (this.z || 0);
  4730. hash = (hash * 397) ^ (this.w || 0);
  4731. return hash;
  4732. };
  4733. /**
  4734. * Copy the quaternion to an array
  4735. * @returns a new array populated with 4 elements from the quaternion coordinates
  4736. */
  4737. Quaternion.prototype.asArray = function () {
  4738. return [this.x, this.y, this.z, this.w];
  4739. };
  4740. /**
  4741. * Check if two quaternions are equals
  4742. * @param otherQuaternion defines the second operand
  4743. * @return true if the current quaternion and the given one coordinates are strictly equals
  4744. */
  4745. Quaternion.prototype.equals = function (otherQuaternion) {
  4746. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4747. };
  4748. /**
  4749. * Clone the current quaternion
  4750. * @returns a new quaternion copied from the current one
  4751. */
  4752. Quaternion.prototype.clone = function () {
  4753. return new Quaternion(this.x, this.y, this.z, this.w);
  4754. };
  4755. /**
  4756. * Copy a quaternion to the current one
  4757. * @param other defines the other quaternion
  4758. * @returns the updated current quaternion
  4759. */
  4760. Quaternion.prototype.copyFrom = function (other) {
  4761. this.x = other.x;
  4762. this.y = other.y;
  4763. this.z = other.z;
  4764. this.w = other.w;
  4765. return this;
  4766. };
  4767. /**
  4768. * Updates the current quaternion with the given float coordinates
  4769. * @param x defines the x coordinate
  4770. * @param y defines the y coordinate
  4771. * @param z defines the z coordinate
  4772. * @param w defines the w coordinate
  4773. * @returns the updated current quaternion
  4774. */
  4775. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4776. this.x = x;
  4777. this.y = y;
  4778. this.z = z;
  4779. this.w = w;
  4780. return this;
  4781. };
  4782. /**
  4783. * Updates the current quaternion from the given float coordinates
  4784. * @param x defines the x coordinate
  4785. * @param y defines the y coordinate
  4786. * @param z defines the z coordinate
  4787. * @param w defines the w coordinate
  4788. * @returns the updated current quaternion
  4789. */
  4790. Quaternion.prototype.set = function (x, y, z, w) {
  4791. return this.copyFromFloats(x, y, z, w);
  4792. };
  4793. /**
  4794. * Adds two quaternions
  4795. * @param other defines the second operand
  4796. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4797. */
  4798. Quaternion.prototype.add = function (other) {
  4799. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4800. };
  4801. /**
  4802. * Add a quaternion to the current one
  4803. * @param other defines the quaternion to add
  4804. * @returns the current quaternion
  4805. */
  4806. Quaternion.prototype.addInPlace = function (other) {
  4807. this.x += other.x;
  4808. this.y += other.y;
  4809. this.z += other.z;
  4810. this.w += other.w;
  4811. return this;
  4812. };
  4813. /**
  4814. * Subtract two quaternions
  4815. * @param other defines the second operand
  4816. * @returns a new quaternion as the subtraction result of the given one from the current one
  4817. */
  4818. Quaternion.prototype.subtract = function (other) {
  4819. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4820. };
  4821. /**
  4822. * Multiplies the current quaternion by a scale factor
  4823. * @param value defines the scale factor
  4824. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4825. */
  4826. Quaternion.prototype.scale = function (value) {
  4827. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4828. };
  4829. /**
  4830. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4831. * @param scale defines the scale factor
  4832. * @param result defines the Quaternion object where to store the result
  4833. * @returns the unmodified current quaternion
  4834. */
  4835. Quaternion.prototype.scaleToRef = function (scale, result) {
  4836. result.x = this.x * scale;
  4837. result.y = this.y * scale;
  4838. result.z = this.z * scale;
  4839. result.w = this.w * scale;
  4840. return this;
  4841. };
  4842. /**
  4843. * Multiplies in place the current quaternion by a scale factor
  4844. * @param value defines the scale factor
  4845. * @returns the current modified quaternion
  4846. */
  4847. Quaternion.prototype.scaleInPlace = function (value) {
  4848. this.x *= value;
  4849. this.y *= value;
  4850. this.z *= value;
  4851. this.w *= value;
  4852. return this;
  4853. };
  4854. /**
  4855. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4856. * @param scale defines the scale factor
  4857. * @param result defines the Quaternion object where to store the result
  4858. * @returns the unmodified current quaternion
  4859. */
  4860. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4861. result.x += this.x * scale;
  4862. result.y += this.y * scale;
  4863. result.z += this.z * scale;
  4864. result.w += this.w * scale;
  4865. return this;
  4866. };
  4867. /**
  4868. * Multiplies two quaternions
  4869. * @param q1 defines the second operand
  4870. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4871. */
  4872. Quaternion.prototype.multiply = function (q1) {
  4873. var result = new Quaternion(0, 0, 0, 1.0);
  4874. this.multiplyToRef(q1, result);
  4875. return result;
  4876. };
  4877. /**
  4878. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4879. * @param q1 defines the second operand
  4880. * @param result defines the target quaternion
  4881. * @returns the current quaternion
  4882. */
  4883. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4884. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4885. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4886. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4887. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4888. result.copyFromFloats(x, y, z, w);
  4889. return this;
  4890. };
  4891. /**
  4892. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4893. * @param q1 defines the second operand
  4894. * @returns the currentupdated quaternion
  4895. */
  4896. Quaternion.prototype.multiplyInPlace = function (q1) {
  4897. this.multiplyToRef(q1, this);
  4898. return this;
  4899. };
  4900. /**
  4901. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4902. * @param ref defines the target quaternion
  4903. * @returns the current quaternion
  4904. */
  4905. Quaternion.prototype.conjugateToRef = function (ref) {
  4906. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4907. return this;
  4908. };
  4909. /**
  4910. * Conjugates in place (1-q) the current quaternion
  4911. * @returns the current updated quaternion
  4912. */
  4913. Quaternion.prototype.conjugateInPlace = function () {
  4914. this.x *= -1;
  4915. this.y *= -1;
  4916. this.z *= -1;
  4917. return this;
  4918. };
  4919. /**
  4920. * Conjugates in place (1-q) the current quaternion
  4921. * @returns a new quaternion
  4922. */
  4923. Quaternion.prototype.conjugate = function () {
  4924. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4925. return result;
  4926. };
  4927. /**
  4928. * Gets length of current quaternion
  4929. * @returns the quaternion length (float)
  4930. */
  4931. Quaternion.prototype.length = function () {
  4932. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4933. };
  4934. /**
  4935. * Normalize in place the current quaternion
  4936. * @returns the current updated quaternion
  4937. */
  4938. Quaternion.prototype.normalize = function () {
  4939. var length = 1.0 / this.length();
  4940. this.x *= length;
  4941. this.y *= length;
  4942. this.z *= length;
  4943. this.w *= length;
  4944. return this;
  4945. };
  4946. /**
  4947. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4948. * @param order is a reserved parameter and is ignore for now
  4949. * @returns a new Vector3 containing the Euler angles
  4950. */
  4951. Quaternion.prototype.toEulerAngles = function (order) {
  4952. if (order === void 0) { order = "YZX"; }
  4953. var result = Vector3.Zero();
  4954. this.toEulerAnglesToRef(result, order);
  4955. return result;
  4956. };
  4957. /**
  4958. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4959. * @param result defines the vector which will be filled with the Euler angles
  4960. * @param order is a reserved parameter and is ignore for now
  4961. * @returns the current unchanged quaternion
  4962. */
  4963. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4964. if (order === void 0) { order = "YZX"; }
  4965. var qz = this.z;
  4966. var qx = this.x;
  4967. var qy = this.y;
  4968. var qw = this.w;
  4969. var sqw = qw * qw;
  4970. var sqz = qz * qz;
  4971. var sqx = qx * qx;
  4972. var sqy = qy * qy;
  4973. var zAxisY = qy * qz - qx * qw;
  4974. var limit = .4999999;
  4975. if (zAxisY < -limit) {
  4976. result.y = 2 * Math.atan2(qy, qw);
  4977. result.x = Math.PI / 2;
  4978. result.z = 0;
  4979. }
  4980. else if (zAxisY > limit) {
  4981. result.y = 2 * Math.atan2(qy, qw);
  4982. result.x = -Math.PI / 2;
  4983. result.z = 0;
  4984. }
  4985. else {
  4986. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4987. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4988. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4989. }
  4990. return this;
  4991. };
  4992. /**
  4993. * Updates the given rotation matrix with the current quaternion values
  4994. * @param result defines the target matrix
  4995. * @returns the current unchanged quaternion
  4996. */
  4997. Quaternion.prototype.toRotationMatrix = function (result) {
  4998. var xx = this.x * this.x;
  4999. var yy = this.y * this.y;
  5000. var zz = this.z * this.z;
  5001. var xy = this.x * this.y;
  5002. var zw = this.z * this.w;
  5003. var zx = this.z * this.x;
  5004. var yw = this.y * this.w;
  5005. var yz = this.y * this.z;
  5006. var xw = this.x * this.w;
  5007. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5008. result.m[1] = 2.0 * (xy + zw);
  5009. result.m[2] = 2.0 * (zx - yw);
  5010. result.m[3] = 0;
  5011. result.m[4] = 2.0 * (xy - zw);
  5012. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5013. result.m[6] = 2.0 * (yz + xw);
  5014. result.m[7] = 0;
  5015. result.m[8] = 2.0 * (zx + yw);
  5016. result.m[9] = 2.0 * (yz - xw);
  5017. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5018. result.m[11] = 0;
  5019. result.m[12] = 0;
  5020. result.m[13] = 0;
  5021. result.m[14] = 0;
  5022. result.m[15] = 1.0;
  5023. result._markAsUpdated();
  5024. return this;
  5025. };
  5026. /**
  5027. * Updates the current quaternion from the given rotation matrix values
  5028. * @param matrix defines the source matrix
  5029. * @returns the current updated quaternion
  5030. */
  5031. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  5032. Quaternion.FromRotationMatrixToRef(matrix, this);
  5033. return this;
  5034. };
  5035. // Statics
  5036. /**
  5037. * Creates a new quaternion from a rotation matrix
  5038. * @param matrix defines the source matrix
  5039. * @returns a new quaternion created from the given rotation matrix values
  5040. */
  5041. Quaternion.FromRotationMatrix = function (matrix) {
  5042. var result = new Quaternion();
  5043. Quaternion.FromRotationMatrixToRef(matrix, result);
  5044. return result;
  5045. };
  5046. /**
  5047. * Updates the given quaternion with the given rotation matrix values
  5048. * @param matrix defines the source matrix
  5049. * @param result defines the target quaternion
  5050. */
  5051. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  5052. var data = matrix.m;
  5053. var m11 = data[0], m12 = data[4], m13 = data[8];
  5054. var m21 = data[1], m22 = data[5], m23 = data[9];
  5055. var m31 = data[2], m32 = data[6], m33 = data[10];
  5056. var trace = m11 + m22 + m33;
  5057. var s;
  5058. if (trace > 0) {
  5059. s = 0.5 / Math.sqrt(trace + 1.0);
  5060. result.w = 0.25 / s;
  5061. result.x = (m32 - m23) * s;
  5062. result.y = (m13 - m31) * s;
  5063. result.z = (m21 - m12) * s;
  5064. }
  5065. else if (m11 > m22 && m11 > m33) {
  5066. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  5067. result.w = (m32 - m23) / s;
  5068. result.x = 0.25 * s;
  5069. result.y = (m12 + m21) / s;
  5070. result.z = (m13 + m31) / s;
  5071. }
  5072. else if (m22 > m33) {
  5073. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  5074. result.w = (m13 - m31) / s;
  5075. result.x = (m12 + m21) / s;
  5076. result.y = 0.25 * s;
  5077. result.z = (m23 + m32) / s;
  5078. }
  5079. else {
  5080. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  5081. result.w = (m21 - m12) / s;
  5082. result.x = (m13 + m31) / s;
  5083. result.y = (m23 + m32) / s;
  5084. result.z = 0.25 * s;
  5085. }
  5086. };
  5087. /**
  5088. * Returns the dot product (float) between the quaternions "left" and "right"
  5089. * @param left defines the left operand
  5090. * @param right defines the right operand
  5091. * @returns the dot product
  5092. */
  5093. Quaternion.Dot = function (left, right) {
  5094. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  5095. };
  5096. /**
  5097. * Checks if the two quaternions are close to each other
  5098. * @param quat0 defines the first quaternion to check
  5099. * @param quat1 defines the second quaternion to check
  5100. * @returns true if the two quaternions are close to each other
  5101. */
  5102. Quaternion.AreClose = function (quat0, quat1) {
  5103. var dot = Quaternion.Dot(quat0, quat1);
  5104. return dot >= 0;
  5105. };
  5106. /**
  5107. * Creates an empty quaternion
  5108. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  5109. */
  5110. Quaternion.Zero = function () {
  5111. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  5112. };
  5113. /**
  5114. * Inverse a given quaternion
  5115. * @param q defines the source quaternion
  5116. * @returns a new quaternion as the inverted current quaternion
  5117. */
  5118. Quaternion.Inverse = function (q) {
  5119. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  5120. };
  5121. /**
  5122. * Creates an identity quaternion
  5123. * @returns the identity quaternion
  5124. */
  5125. Quaternion.Identity = function () {
  5126. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  5127. };
  5128. /**
  5129. * Gets a boolean indicating if the given quaternion is identity
  5130. * @param quaternion defines the quaternion to check
  5131. * @returns true if the quaternion is identity
  5132. */
  5133. Quaternion.IsIdentity = function (quaternion) {
  5134. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  5135. };
  5136. /**
  5137. * Creates a quaternion from a rotation around an axis
  5138. * @param axis defines the axis to use
  5139. * @param angle defines the angle to use
  5140. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  5141. */
  5142. Quaternion.RotationAxis = function (axis, angle) {
  5143. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  5144. };
  5145. /**
  5146. * Creates a rotation around an axis and stores it into the given quaternion
  5147. * @param axis defines the axis to use
  5148. * @param angle defines the angle to use
  5149. * @param result defines the target quaternion
  5150. * @returns the target quaternion
  5151. */
  5152. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  5153. var sin = Math.sin(angle / 2);
  5154. axis.normalize();
  5155. result.w = Math.cos(angle / 2);
  5156. result.x = axis.x * sin;
  5157. result.y = axis.y * sin;
  5158. result.z = axis.z * sin;
  5159. return result;
  5160. };
  5161. /**
  5162. * Creates a new quaternion from data stored into an array
  5163. * @param array defines the data source
  5164. * @param offset defines the offset in the source array where the data starts
  5165. * @returns a new quaternion
  5166. */
  5167. Quaternion.FromArray = function (array, offset) {
  5168. if (!offset) {
  5169. offset = 0;
  5170. }
  5171. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  5172. };
  5173. /**
  5174. * Creates a new quaternion from the given Euler float angles (y, x, z)
  5175. * @param yaw defines the rotation around Y axis
  5176. * @param pitch defines the rotation around X axis
  5177. * @param roll defines the rotation around Z axis
  5178. * @returns the new quaternion
  5179. */
  5180. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5181. var q = new Quaternion();
  5182. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  5183. return q;
  5184. };
  5185. /**
  5186. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  5187. * @param yaw defines the rotation around Y axis
  5188. * @param pitch defines the rotation around X axis
  5189. * @param roll defines the rotation around Z axis
  5190. * @param result defines the target quaternion
  5191. */
  5192. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5193. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  5194. var halfRoll = roll * 0.5;
  5195. var halfPitch = pitch * 0.5;
  5196. var halfYaw = yaw * 0.5;
  5197. var sinRoll = Math.sin(halfRoll);
  5198. var cosRoll = Math.cos(halfRoll);
  5199. var sinPitch = Math.sin(halfPitch);
  5200. var cosPitch = Math.cos(halfPitch);
  5201. var sinYaw = Math.sin(halfYaw);
  5202. var cosYaw = Math.cos(halfYaw);
  5203. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  5204. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  5205. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  5206. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  5207. };
  5208. /**
  5209. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  5210. * @param alpha defines the rotation around first axis
  5211. * @param beta defines the rotation around second axis
  5212. * @param gamma defines the rotation around third axis
  5213. * @returns the new quaternion
  5214. */
  5215. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  5216. var result = new Quaternion();
  5217. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5218. return result;
  5219. };
  5220. /**
  5221. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5222. * @param alpha defines the rotation around first axis
  5223. * @param beta defines the rotation around second axis
  5224. * @param gamma defines the rotation around third axis
  5225. * @param result defines the target quaternion
  5226. */
  5227. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5228. // Produces a quaternion from Euler angles in the z-x-z orientation
  5229. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5230. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5231. var halfBeta = beta * 0.5;
  5232. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5233. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5234. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5235. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5236. };
  5237. /**
  5238. * 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)
  5239. * @param axis1 defines the first axis
  5240. * @param axis2 defines the second axis
  5241. * @param axis3 defines the third axis
  5242. * @returns the new quaternion
  5243. */
  5244. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5245. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5246. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5247. return quat;
  5248. };
  5249. /**
  5250. * 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
  5251. * @param axis1 defines the first axis
  5252. * @param axis2 defines the second axis
  5253. * @param axis3 defines the third axis
  5254. * @param ref defines the target quaternion
  5255. */
  5256. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5257. var rotMat = MathTmp.Matrix[0];
  5258. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5259. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5260. };
  5261. /**
  5262. * Interpolates between two quaternions
  5263. * @param left defines first quaternion
  5264. * @param right defines second quaternion
  5265. * @param amount defines the gradient to use
  5266. * @returns the new interpolated quaternion
  5267. */
  5268. Quaternion.Slerp = function (left, right, amount) {
  5269. var result = Quaternion.Identity();
  5270. Quaternion.SlerpToRef(left, right, amount, result);
  5271. return result;
  5272. };
  5273. /**
  5274. * Interpolates between two quaternions and stores it into a target quaternion
  5275. * @param left defines first quaternion
  5276. * @param right defines second quaternion
  5277. * @param amount defines the gradient to use
  5278. * @param result defines the target quaternion
  5279. */
  5280. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5281. var num2;
  5282. var num3;
  5283. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5284. var flag = false;
  5285. if (num4 < 0) {
  5286. flag = true;
  5287. num4 = -num4;
  5288. }
  5289. if (num4 > 0.999999) {
  5290. num3 = 1 - amount;
  5291. num2 = flag ? -amount : amount;
  5292. }
  5293. else {
  5294. var num5 = Math.acos(num4);
  5295. var num6 = (1.0 / Math.sin(num5));
  5296. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5297. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5298. }
  5299. result.x = (num3 * left.x) + (num2 * right.x);
  5300. result.y = (num3 * left.y) + (num2 * right.y);
  5301. result.z = (num3 * left.z) + (num2 * right.z);
  5302. result.w = (num3 * left.w) + (num2 * right.w);
  5303. };
  5304. /**
  5305. * Interpolate between two quaternions using Hermite interpolation
  5306. * @param value1 defines first quaternion
  5307. * @param tangent1 defines the incoming tangent
  5308. * @param value2 defines second quaternion
  5309. * @param tangent2 defines the outgoing tangent
  5310. * @param amount defines the target quaternion
  5311. * @returns the new interpolated quaternion
  5312. */
  5313. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5314. var squared = amount * amount;
  5315. var cubed = amount * squared;
  5316. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5317. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5318. var part3 = (cubed - (2.0 * squared)) + amount;
  5319. var part4 = cubed - squared;
  5320. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5321. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5322. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5323. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5324. return new Quaternion(x, y, z, w);
  5325. };
  5326. return Quaternion;
  5327. }());
  5328. BABYLON.Quaternion = Quaternion;
  5329. /**
  5330. * Class used to store matrix data (4x4)
  5331. */
  5332. var Matrix = /** @class */ (function () {
  5333. /**
  5334. * Creates an empty matrix (filled with zeros)
  5335. */
  5336. function Matrix() {
  5337. this._isIdentity = false;
  5338. this._isIdentityDirty = true;
  5339. /**
  5340. * Gets or sets the internal data of the matrix
  5341. */
  5342. this.m = new Float32Array(16);
  5343. this._markAsUpdated();
  5344. }
  5345. /** @hidden */
  5346. Matrix.prototype._markAsUpdated = function () {
  5347. this.updateFlag = Matrix._updateFlagSeed++;
  5348. this._isIdentityDirty = true;
  5349. };
  5350. // Properties
  5351. /**
  5352. * Check if the current matrix is indentity
  5353. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5354. * @returns true is the matrix is the identity matrix
  5355. */
  5356. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5357. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5358. if (this._isIdentityDirty) {
  5359. this._isIdentityDirty = false;
  5360. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5361. this._isIdentity = false;
  5362. }
  5363. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5364. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5365. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5366. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5367. this._isIdentity = false;
  5368. }
  5369. else {
  5370. this._isIdentity = true;
  5371. }
  5372. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5373. this._isIdentity = false;
  5374. }
  5375. }
  5376. return this._isIdentity;
  5377. };
  5378. /**
  5379. * Gets the determinant of the matrix
  5380. * @returns the matrix determinant
  5381. */
  5382. Matrix.prototype.determinant = function () {
  5383. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5384. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5385. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5386. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5387. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5388. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5389. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5390. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5391. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5392. };
  5393. // Methods
  5394. /**
  5395. * Returns the matrix as a Float32Array
  5396. * @returns the matrix underlying array
  5397. */
  5398. Matrix.prototype.toArray = function () {
  5399. return this.m;
  5400. };
  5401. /**
  5402. * Returns the matrix as a Float32Array
  5403. * @returns the matrix underlying array.
  5404. */
  5405. Matrix.prototype.asArray = function () {
  5406. return this.toArray();
  5407. };
  5408. /**
  5409. * Inverts the current matrix in place
  5410. * @returns the current inverted matrix
  5411. */
  5412. Matrix.prototype.invert = function () {
  5413. this.invertToRef(this);
  5414. return this;
  5415. };
  5416. /**
  5417. * Sets all the matrix elements to zero
  5418. * @returns the current matrix
  5419. */
  5420. Matrix.prototype.reset = function () {
  5421. for (var index = 0; index < 16; index++) {
  5422. this.m[index] = 0.0;
  5423. }
  5424. this._markAsUpdated();
  5425. return this;
  5426. };
  5427. /**
  5428. * Adds the current matrix with a second one
  5429. * @param other defines the matrix to add
  5430. * @returns a new matrix as the addition of the current matrix and the given one
  5431. */
  5432. Matrix.prototype.add = function (other) {
  5433. var result = new Matrix();
  5434. this.addToRef(other, result);
  5435. return result;
  5436. };
  5437. /**
  5438. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5439. * @param other defines the matrix to add
  5440. * @param result defines the target matrix
  5441. * @returns the current matrix
  5442. */
  5443. Matrix.prototype.addToRef = function (other, result) {
  5444. for (var index = 0; index < 16; index++) {
  5445. result.m[index] = this.m[index] + other.m[index];
  5446. }
  5447. result._markAsUpdated();
  5448. return this;
  5449. };
  5450. /**
  5451. * Adds in place the given matrix to the current matrix
  5452. * @param other defines the second operand
  5453. * @returns the current updated matrix
  5454. */
  5455. Matrix.prototype.addToSelf = function (other) {
  5456. for (var index = 0; index < 16; index++) {
  5457. this.m[index] += other.m[index];
  5458. }
  5459. this._markAsUpdated();
  5460. return this;
  5461. };
  5462. /**
  5463. * Sets the given matrix to the current inverted Matrix
  5464. * @param other defines the target matrix
  5465. * @returns the unmodified current matrix
  5466. */
  5467. Matrix.prototype.invertToRef = function (other) {
  5468. var l1 = this.m[0];
  5469. var l2 = this.m[1];
  5470. var l3 = this.m[2];
  5471. var l4 = this.m[3];
  5472. var l5 = this.m[4];
  5473. var l6 = this.m[5];
  5474. var l7 = this.m[6];
  5475. var l8 = this.m[7];
  5476. var l9 = this.m[8];
  5477. var l10 = this.m[9];
  5478. var l11 = this.m[10];
  5479. var l12 = this.m[11];
  5480. var l13 = this.m[12];
  5481. var l14 = this.m[13];
  5482. var l15 = this.m[14];
  5483. var l16 = this.m[15];
  5484. var l17 = (l11 * l16) - (l12 * l15);
  5485. var l18 = (l10 * l16) - (l12 * l14);
  5486. var l19 = (l10 * l15) - (l11 * l14);
  5487. var l20 = (l9 * l16) - (l12 * l13);
  5488. var l21 = (l9 * l15) - (l11 * l13);
  5489. var l22 = (l9 * l14) - (l10 * l13);
  5490. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5491. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5492. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5493. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5494. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5495. var l28 = (l7 * l16) - (l8 * l15);
  5496. var l29 = (l6 * l16) - (l8 * l14);
  5497. var l30 = (l6 * l15) - (l7 * l14);
  5498. var l31 = (l5 * l16) - (l8 * l13);
  5499. var l32 = (l5 * l15) - (l7 * l13);
  5500. var l33 = (l5 * l14) - (l6 * l13);
  5501. var l34 = (l7 * l12) - (l8 * l11);
  5502. var l35 = (l6 * l12) - (l8 * l10);
  5503. var l36 = (l6 * l11) - (l7 * l10);
  5504. var l37 = (l5 * l12) - (l8 * l9);
  5505. var l38 = (l5 * l11) - (l7 * l9);
  5506. var l39 = (l5 * l10) - (l6 * l9);
  5507. other.m[0] = l23 * l27;
  5508. other.m[4] = l24 * l27;
  5509. other.m[8] = l25 * l27;
  5510. other.m[12] = l26 * l27;
  5511. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5512. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5513. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5514. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5515. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5516. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5517. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5518. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5519. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5520. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5521. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5522. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5523. other._markAsUpdated();
  5524. return this;
  5525. };
  5526. /**
  5527. * Inserts the translation vector (using 3 floats) in the current matrix
  5528. * @param x defines the 1st component of the translation
  5529. * @param y defines the 2nd component of the translation
  5530. * @param z defines the 3rd component of the translation
  5531. * @returns the current updated matrix
  5532. */
  5533. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5534. this.m[12] = x;
  5535. this.m[13] = y;
  5536. this.m[14] = z;
  5537. this._markAsUpdated();
  5538. return this;
  5539. };
  5540. /**
  5541. * Inserts the translation vector in the current matrix
  5542. * @param vector3 defines the translation to insert
  5543. * @returns the current updated matrix
  5544. */
  5545. Matrix.prototype.setTranslation = function (vector3) {
  5546. this.m[12] = vector3.x;
  5547. this.m[13] = vector3.y;
  5548. this.m[14] = vector3.z;
  5549. this._markAsUpdated();
  5550. return this;
  5551. };
  5552. /**
  5553. * Gets the translation value of the current matrix
  5554. * @returns a new Vector3 as the extracted translation from the matrix
  5555. */
  5556. Matrix.prototype.getTranslation = function () {
  5557. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5558. };
  5559. /**
  5560. * Fill a Vector3 with the extracted translation from the matrix
  5561. * @param result defines the Vector3 where to store the translation
  5562. * @returns the current matrix
  5563. */
  5564. Matrix.prototype.getTranslationToRef = function (result) {
  5565. result.x = this.m[12];
  5566. result.y = this.m[13];
  5567. result.z = this.m[14];
  5568. return this;
  5569. };
  5570. /**
  5571. * Remove rotation and scaling part from the matrix
  5572. * @returns the updated matrix
  5573. */
  5574. Matrix.prototype.removeRotationAndScaling = function () {
  5575. this.setRowFromFloats(0, 1, 0, 0, 0);
  5576. this.setRowFromFloats(1, 0, 1, 0, 0);
  5577. this.setRowFromFloats(2, 0, 0, 1, 0);
  5578. return this;
  5579. };
  5580. /**
  5581. * Multiply two matrices
  5582. * @param other defines the second operand
  5583. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5584. */
  5585. Matrix.prototype.multiply = function (other) {
  5586. var result = new Matrix();
  5587. this.multiplyToRef(other, result);
  5588. return result;
  5589. };
  5590. /**
  5591. * Copy the current matrix from the given one
  5592. * @param other defines the source matrix
  5593. * @returns the current updated matrix
  5594. */
  5595. Matrix.prototype.copyFrom = function (other) {
  5596. for (var index = 0; index < 16; index++) {
  5597. this.m[index] = other.m[index];
  5598. }
  5599. this._markAsUpdated();
  5600. return this;
  5601. };
  5602. /**
  5603. * Populates the given array from the starting index with the current matrix values
  5604. * @param array defines the target array
  5605. * @param offset defines the offset in the target array where to start storing values
  5606. * @returns the current matrix
  5607. */
  5608. Matrix.prototype.copyToArray = function (array, offset) {
  5609. if (offset === void 0) { offset = 0; }
  5610. for (var index = 0; index < 16; index++) {
  5611. array[offset + index] = this.m[index];
  5612. }
  5613. return this;
  5614. };
  5615. /**
  5616. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5617. * @param other defines the second operand
  5618. * @param result defines the matrix where to store the multiplication
  5619. * @returns the current matrix
  5620. */
  5621. Matrix.prototype.multiplyToRef = function (other, result) {
  5622. this.multiplyToArray(other, result.m, 0);
  5623. result._markAsUpdated();
  5624. return this;
  5625. };
  5626. /**
  5627. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5628. * @param other defines the second operand
  5629. * @param result defines the array where to store the multiplication
  5630. * @param offset defines the offset in the target array where to start storing values
  5631. * @returns the current matrix
  5632. */
  5633. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5634. var tm0 = this.m[0];
  5635. var tm1 = this.m[1];
  5636. var tm2 = this.m[2];
  5637. var tm3 = this.m[3];
  5638. var tm4 = this.m[4];
  5639. var tm5 = this.m[5];
  5640. var tm6 = this.m[6];
  5641. var tm7 = this.m[7];
  5642. var tm8 = this.m[8];
  5643. var tm9 = this.m[9];
  5644. var tm10 = this.m[10];
  5645. var tm11 = this.m[11];
  5646. var tm12 = this.m[12];
  5647. var tm13 = this.m[13];
  5648. var tm14 = this.m[14];
  5649. var tm15 = this.m[15];
  5650. var om0 = other.m[0];
  5651. var om1 = other.m[1];
  5652. var om2 = other.m[2];
  5653. var om3 = other.m[3];
  5654. var om4 = other.m[4];
  5655. var om5 = other.m[5];
  5656. var om6 = other.m[6];
  5657. var om7 = other.m[7];
  5658. var om8 = other.m[8];
  5659. var om9 = other.m[9];
  5660. var om10 = other.m[10];
  5661. var om11 = other.m[11];
  5662. var om12 = other.m[12];
  5663. var om13 = other.m[13];
  5664. var om14 = other.m[14];
  5665. var om15 = other.m[15];
  5666. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5667. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5668. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5669. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5670. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5671. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5672. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5673. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5674. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5675. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5676. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5677. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5678. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5679. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5680. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5681. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5682. return this;
  5683. };
  5684. /**
  5685. * Check equality between this matrix and a second one
  5686. * @param value defines the second matrix to compare
  5687. * @returns true is the current matrix and the given one values are strictly equal
  5688. */
  5689. Matrix.prototype.equals = function (value) {
  5690. return value &&
  5691. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5692. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5693. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5694. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5695. };
  5696. /**
  5697. * Clone the current matrix
  5698. * @returns a new matrix from the current matrix
  5699. */
  5700. Matrix.prototype.clone = function () {
  5701. 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]);
  5702. };
  5703. /**
  5704. * Returns the name of the current matrix class
  5705. * @returns the string "Matrix"
  5706. */
  5707. Matrix.prototype.getClassName = function () {
  5708. return "Matrix";
  5709. };
  5710. /**
  5711. * Gets the hash code of the current matrix
  5712. * @returns the hash code
  5713. */
  5714. Matrix.prototype.getHashCode = function () {
  5715. var hash = this.m[0] || 0;
  5716. for (var i = 1; i < 16; i++) {
  5717. hash = (hash * 397) ^ (this.m[i] || 0);
  5718. }
  5719. return hash;
  5720. };
  5721. /**
  5722. * Decomposes the current Matrix into a translation, rotation and scaling components
  5723. * @param scale defines the scale vector3 given as a reference to update
  5724. * @param rotation defines the rotation quaternion given as a reference to update
  5725. * @param translation defines the translation vector3 given as a reference to update
  5726. * @returns true if operation was successful
  5727. */
  5728. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5729. if (translation) {
  5730. translation.x = this.m[12];
  5731. translation.y = this.m[13];
  5732. translation.z = this.m[14];
  5733. }
  5734. scale = scale || MathTmp.Vector3[0];
  5735. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5736. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5737. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5738. if (this.determinant() <= 0) {
  5739. scale.y *= -1;
  5740. }
  5741. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5742. if (rotation) {
  5743. rotation.x = 0;
  5744. rotation.y = 0;
  5745. rotation.z = 0;
  5746. rotation.w = 1;
  5747. }
  5748. return false;
  5749. }
  5750. if (rotation) {
  5751. 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]);
  5752. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5753. }
  5754. return true;
  5755. };
  5756. /**
  5757. * Gets specific row of the matrix
  5758. * @param index defines the number of the row to get
  5759. * @returns the index-th row of the current matrix as a new Vector4
  5760. */
  5761. Matrix.prototype.getRow = function (index) {
  5762. if (index < 0 || index > 3) {
  5763. return null;
  5764. }
  5765. var i = index * 4;
  5766. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5767. };
  5768. /**
  5769. * Sets the index-th row of the current matrix to the vector4 values
  5770. * @param index defines the number of the row to set
  5771. * @param row defines the target vector4
  5772. * @returns the updated current matrix
  5773. */
  5774. Matrix.prototype.setRow = function (index, row) {
  5775. if (index < 0 || index > 3) {
  5776. return this;
  5777. }
  5778. var i = index * 4;
  5779. this.m[i + 0] = row.x;
  5780. this.m[i + 1] = row.y;
  5781. this.m[i + 2] = row.z;
  5782. this.m[i + 3] = row.w;
  5783. this._markAsUpdated();
  5784. return this;
  5785. };
  5786. /**
  5787. * Compute the transpose of the matrix
  5788. * @returns the new transposed matrix
  5789. */
  5790. Matrix.prototype.transpose = function () {
  5791. return Matrix.Transpose(this);
  5792. };
  5793. /**
  5794. * Compute the transpose of the matrix and store it in a given matrix
  5795. * @param result defines the target matrix
  5796. * @returns the current matrix
  5797. */
  5798. Matrix.prototype.transposeToRef = function (result) {
  5799. Matrix.TransposeToRef(this, result);
  5800. return this;
  5801. };
  5802. /**
  5803. * Sets the index-th row of the current matrix with the given 4 x float values
  5804. * @param index defines the row index
  5805. * @param x defines the x component to set
  5806. * @param y defines the y component to set
  5807. * @param z defines the z component to set
  5808. * @param w defines the w component to set
  5809. * @returns the updated current matrix
  5810. */
  5811. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5812. if (index < 0 || index > 3) {
  5813. return this;
  5814. }
  5815. var i = index * 4;
  5816. this.m[i + 0] = x;
  5817. this.m[i + 1] = y;
  5818. this.m[i + 2] = z;
  5819. this.m[i + 3] = w;
  5820. this._markAsUpdated();
  5821. return this;
  5822. };
  5823. /**
  5824. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5825. * @param scale defines the scale factor
  5826. * @returns a new matrix
  5827. */
  5828. Matrix.prototype.scale = function (scale) {
  5829. var result = new Matrix();
  5830. this.scaleToRef(scale, result);
  5831. return result;
  5832. };
  5833. /**
  5834. * Scale the current matrix values by a factor to a given result matrix
  5835. * @param scale defines the scale factor
  5836. * @param result defines the matrix to store the result
  5837. * @returns the current matrix
  5838. */
  5839. Matrix.prototype.scaleToRef = function (scale, result) {
  5840. for (var index = 0; index < 16; index++) {
  5841. result.m[index] = this.m[index] * scale;
  5842. }
  5843. result._markAsUpdated();
  5844. return this;
  5845. };
  5846. /**
  5847. * Scale the current matrix values by a factor and add the result to a given matrix
  5848. * @param scale defines the scale factor
  5849. * @param result defines the Matrix to store the result
  5850. * @returns the current matrix
  5851. */
  5852. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5853. for (var index = 0; index < 16; index++) {
  5854. result.m[index] += this.m[index] * scale;
  5855. }
  5856. result._markAsUpdated();
  5857. return this;
  5858. };
  5859. /**
  5860. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5861. * @param ref matrix to store the result
  5862. */
  5863. Matrix.prototype.toNormalMatrix = function (ref) {
  5864. this.invertToRef(ref);
  5865. ref.transpose();
  5866. var m = ref.m;
  5867. 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);
  5868. };
  5869. /**
  5870. * Gets only rotation part of the current matrix
  5871. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5872. */
  5873. Matrix.prototype.getRotationMatrix = function () {
  5874. var result = Matrix.Identity();
  5875. this.getRotationMatrixToRef(result);
  5876. return result;
  5877. };
  5878. /**
  5879. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5880. * @param result defines the target matrix to store data to
  5881. * @returns the current matrix
  5882. */
  5883. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5884. var m = this.m;
  5885. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5886. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5887. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5888. if (this.determinant() <= 0) {
  5889. sy *= -1;
  5890. }
  5891. if (sx === 0 || sy === 0 || sz === 0) {
  5892. Matrix.IdentityToRef(result);
  5893. }
  5894. else {
  5895. 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);
  5896. }
  5897. return this;
  5898. };
  5899. // Statics
  5900. /**
  5901. * Creates a matrix from an array
  5902. * @param array defines the source array
  5903. * @param offset defines an offset in the source array
  5904. * @returns a new Matrix set from the starting index of the given array
  5905. */
  5906. Matrix.FromArray = function (array, offset) {
  5907. var result = new Matrix();
  5908. if (!offset) {
  5909. offset = 0;
  5910. }
  5911. Matrix.FromArrayToRef(array, offset, result);
  5912. return result;
  5913. };
  5914. /**
  5915. * Copy the content of an array into a given matrix
  5916. * @param array defines the source array
  5917. * @param offset defines an offset in the source array
  5918. * @param result defines the target matrix
  5919. */
  5920. Matrix.FromArrayToRef = function (array, offset, result) {
  5921. for (var index = 0; index < 16; index++) {
  5922. result.m[index] = array[index + offset];
  5923. }
  5924. result._markAsUpdated();
  5925. };
  5926. /**
  5927. * Stores an array into a matrix after having multiplied each component by a given factor
  5928. * @param array defines the source array
  5929. * @param offset defines the offset in the source array
  5930. * @param scale defines the scaling factor
  5931. * @param result defines the target matrix
  5932. */
  5933. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5934. for (var index = 0; index < 16; index++) {
  5935. result.m[index] = array[index + offset] * scale;
  5936. }
  5937. result._markAsUpdated();
  5938. };
  5939. /**
  5940. * Stores a list of values (16) inside a given matrix
  5941. * @param initialM11 defines 1st value of 1st row
  5942. * @param initialM12 defines 2nd value of 1st row
  5943. * @param initialM13 defines 3rd value of 1st row
  5944. * @param initialM14 defines 4th value of 1st row
  5945. * @param initialM21 defines 1st value of 2nd row
  5946. * @param initialM22 defines 2nd value of 2nd row
  5947. * @param initialM23 defines 3rd value of 2nd row
  5948. * @param initialM24 defines 4th value of 2nd row
  5949. * @param initialM31 defines 1st value of 3rd row
  5950. * @param initialM32 defines 2nd value of 3rd row
  5951. * @param initialM33 defines 3rd value of 3rd row
  5952. * @param initialM34 defines 4th value of 3rd row
  5953. * @param initialM41 defines 1st value of 4th row
  5954. * @param initialM42 defines 2nd value of 4th row
  5955. * @param initialM43 defines 3rd value of 4th row
  5956. * @param initialM44 defines 4th value of 4th row
  5957. * @param result defines the target matrix
  5958. */
  5959. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5960. result.m[0] = initialM11;
  5961. result.m[1] = initialM12;
  5962. result.m[2] = initialM13;
  5963. result.m[3] = initialM14;
  5964. result.m[4] = initialM21;
  5965. result.m[5] = initialM22;
  5966. result.m[6] = initialM23;
  5967. result.m[7] = initialM24;
  5968. result.m[8] = initialM31;
  5969. result.m[9] = initialM32;
  5970. result.m[10] = initialM33;
  5971. result.m[11] = initialM34;
  5972. result.m[12] = initialM41;
  5973. result.m[13] = initialM42;
  5974. result.m[14] = initialM43;
  5975. result.m[15] = initialM44;
  5976. result._markAsUpdated();
  5977. };
  5978. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5979. /**
  5980. * Gets an identity matrix that must not be updated
  5981. */
  5982. get: function () {
  5983. return Matrix._identityReadOnly;
  5984. },
  5985. enumerable: true,
  5986. configurable: true
  5987. });
  5988. /**
  5989. * Creates new matrix from a list of values (16)
  5990. * @param initialM11 defines 1st value of 1st row
  5991. * @param initialM12 defines 2nd value of 1st row
  5992. * @param initialM13 defines 3rd value of 1st row
  5993. * @param initialM14 defines 4th value of 1st row
  5994. * @param initialM21 defines 1st value of 2nd row
  5995. * @param initialM22 defines 2nd value of 2nd row
  5996. * @param initialM23 defines 3rd value of 2nd row
  5997. * @param initialM24 defines 4th value of 2nd row
  5998. * @param initialM31 defines 1st value of 3rd row
  5999. * @param initialM32 defines 2nd value of 3rd row
  6000. * @param initialM33 defines 3rd value of 3rd row
  6001. * @param initialM34 defines 4th value of 3rd row
  6002. * @param initialM41 defines 1st value of 4th row
  6003. * @param initialM42 defines 2nd value of 4th row
  6004. * @param initialM43 defines 3rd value of 4th row
  6005. * @param initialM44 defines 4th value of 4th row
  6006. * @returns the new matrix
  6007. */
  6008. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  6009. var result = new Matrix();
  6010. result.m[0] = initialM11;
  6011. result.m[1] = initialM12;
  6012. result.m[2] = initialM13;
  6013. result.m[3] = initialM14;
  6014. result.m[4] = initialM21;
  6015. result.m[5] = initialM22;
  6016. result.m[6] = initialM23;
  6017. result.m[7] = initialM24;
  6018. result.m[8] = initialM31;
  6019. result.m[9] = initialM32;
  6020. result.m[10] = initialM33;
  6021. result.m[11] = initialM34;
  6022. result.m[12] = initialM41;
  6023. result.m[13] = initialM42;
  6024. result.m[14] = initialM43;
  6025. result.m[15] = initialM44;
  6026. return result;
  6027. };
  6028. /**
  6029. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6030. * @param scale defines the scale vector3
  6031. * @param rotation defines the rotation quaternion
  6032. * @param translation defines the translation vector3
  6033. * @returns a new matrix
  6034. */
  6035. Matrix.Compose = function (scale, rotation, translation) {
  6036. var result = Matrix.Identity();
  6037. Matrix.ComposeToRef(scale, rotation, translation, result);
  6038. return result;
  6039. };
  6040. /**
  6041. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6042. * @param scale defines the scale vector3
  6043. * @param rotation defines the rotation quaternion
  6044. * @param translation defines the translation vector3
  6045. * @param result defines the target matrix
  6046. */
  6047. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  6048. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  6049. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  6050. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  6051. result.setTranslation(translation);
  6052. };
  6053. /**
  6054. * Creates a new identity matrix
  6055. * @returns a new identity matrix
  6056. */
  6057. Matrix.Identity = function () {
  6058. 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);
  6059. };
  6060. /**
  6061. * Creates a new identity matrix and stores the result in a given matrix
  6062. * @param result defines the target matrix
  6063. */
  6064. Matrix.IdentityToRef = function (result) {
  6065. 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);
  6066. };
  6067. /**
  6068. * Creates a new zero matrix
  6069. * @returns a new zero matrix
  6070. */
  6071. Matrix.Zero = function () {
  6072. 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);
  6073. };
  6074. /**
  6075. * Creates a new rotation matrix for "angle" radians around the X axis
  6076. * @param angle defines the angle (in radians) to use
  6077. * @return the new matrix
  6078. */
  6079. Matrix.RotationX = function (angle) {
  6080. var result = new Matrix();
  6081. Matrix.RotationXToRef(angle, result);
  6082. return result;
  6083. };
  6084. /**
  6085. * Creates a new matrix as the invert of a given matrix
  6086. * @param source defines the source matrix
  6087. * @returns the new matrix
  6088. */
  6089. Matrix.Invert = function (source) {
  6090. var result = new Matrix();
  6091. source.invertToRef(result);
  6092. return result;
  6093. };
  6094. /**
  6095. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  6096. * @param angle defines the angle (in radians) to use
  6097. * @param result defines the target matrix
  6098. */
  6099. Matrix.RotationXToRef = function (angle, result) {
  6100. var s = Math.sin(angle);
  6101. var c = Math.cos(angle);
  6102. result.m[0] = 1.0;
  6103. result.m[15] = 1.0;
  6104. result.m[5] = c;
  6105. result.m[10] = c;
  6106. result.m[9] = -s;
  6107. result.m[6] = s;
  6108. result.m[1] = 0.0;
  6109. result.m[2] = 0.0;
  6110. result.m[3] = 0.0;
  6111. result.m[4] = 0.0;
  6112. result.m[7] = 0.0;
  6113. result.m[8] = 0.0;
  6114. result.m[11] = 0.0;
  6115. result.m[12] = 0.0;
  6116. result.m[13] = 0.0;
  6117. result.m[14] = 0.0;
  6118. result._markAsUpdated();
  6119. };
  6120. /**
  6121. * Creates a new rotation matrix for "angle" radians around the Y axis
  6122. * @param angle defines the angle (in radians) to use
  6123. * @return the new matrix
  6124. */
  6125. Matrix.RotationY = function (angle) {
  6126. var result = new Matrix();
  6127. Matrix.RotationYToRef(angle, result);
  6128. return result;
  6129. };
  6130. /**
  6131. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  6132. * @param angle defines the angle (in radians) to use
  6133. * @param result defines the target matrix
  6134. */
  6135. Matrix.RotationYToRef = function (angle, result) {
  6136. var s = Math.sin(angle);
  6137. var c = Math.cos(angle);
  6138. result.m[5] = 1.0;
  6139. result.m[15] = 1.0;
  6140. result.m[0] = c;
  6141. result.m[2] = -s;
  6142. result.m[8] = s;
  6143. result.m[10] = c;
  6144. result.m[1] = 0.0;
  6145. result.m[3] = 0.0;
  6146. result.m[4] = 0.0;
  6147. result.m[6] = 0.0;
  6148. result.m[7] = 0.0;
  6149. result.m[9] = 0.0;
  6150. result.m[11] = 0.0;
  6151. result.m[12] = 0.0;
  6152. result.m[13] = 0.0;
  6153. result.m[14] = 0.0;
  6154. result._markAsUpdated();
  6155. };
  6156. /**
  6157. * Creates a new rotation matrix for "angle" radians around the Z axis
  6158. * @param angle defines the angle (in radians) to use
  6159. * @return the new matrix
  6160. */
  6161. Matrix.RotationZ = function (angle) {
  6162. var result = new Matrix();
  6163. Matrix.RotationZToRef(angle, result);
  6164. return result;
  6165. };
  6166. /**
  6167. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  6168. * @param angle defines the angle (in radians) to use
  6169. * @param result defines the target matrix
  6170. */
  6171. Matrix.RotationZToRef = function (angle, result) {
  6172. var s = Math.sin(angle);
  6173. var c = Math.cos(angle);
  6174. result.m[10] = 1.0;
  6175. result.m[15] = 1.0;
  6176. result.m[0] = c;
  6177. result.m[1] = s;
  6178. result.m[4] = -s;
  6179. result.m[5] = c;
  6180. result.m[2] = 0.0;
  6181. result.m[3] = 0.0;
  6182. result.m[6] = 0.0;
  6183. result.m[7] = 0.0;
  6184. result.m[8] = 0.0;
  6185. result.m[9] = 0.0;
  6186. result.m[11] = 0.0;
  6187. result.m[12] = 0.0;
  6188. result.m[13] = 0.0;
  6189. result.m[14] = 0.0;
  6190. result._markAsUpdated();
  6191. };
  6192. /**
  6193. * Creates a new rotation matrix for "angle" radians around the given axis
  6194. * @param axis defines the axis to use
  6195. * @param angle defines the angle (in radians) to use
  6196. * @return the new matrix
  6197. */
  6198. Matrix.RotationAxis = function (axis, angle) {
  6199. var result = Matrix.Zero();
  6200. Matrix.RotationAxisToRef(axis, angle, result);
  6201. return result;
  6202. };
  6203. /**
  6204. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  6205. * @param axis defines the axis to use
  6206. * @param angle defines the angle (in radians) to use
  6207. * @param result defines the target matrix
  6208. */
  6209. Matrix.RotationAxisToRef = function (axis, angle, result) {
  6210. var s = Math.sin(-angle);
  6211. var c = Math.cos(-angle);
  6212. var c1 = 1 - c;
  6213. axis.normalize();
  6214. result.m[0] = (axis.x * axis.x) * c1 + c;
  6215. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  6216. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  6217. result.m[3] = 0.0;
  6218. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6219. result.m[5] = (axis.y * axis.y) * c1 + c;
  6220. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6221. result.m[7] = 0.0;
  6222. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6223. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6224. result.m[10] = (axis.z * axis.z) * c1 + c;
  6225. result.m[11] = 0.0;
  6226. result.m[15] = 1.0;
  6227. result._markAsUpdated();
  6228. };
  6229. /**
  6230. * Creates a rotation matrix
  6231. * @param yaw defines the yaw angle in radians (Y axis)
  6232. * @param pitch defines the pitch angle in radians (X axis)
  6233. * @param roll defines the roll angle in radians (X axis)
  6234. * @returns the new rotation matrix
  6235. */
  6236. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6237. var result = new Matrix();
  6238. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6239. return result;
  6240. };
  6241. /**
  6242. * Creates a rotation matrix and stores it in a given matrix
  6243. * @param yaw defines the yaw angle in radians (Y axis)
  6244. * @param pitch defines the pitch angle in radians (X axis)
  6245. * @param roll defines the roll angle in radians (X axis)
  6246. * @param result defines the target matrix
  6247. */
  6248. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6249. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6250. this._tempQuaternion.toRotationMatrix(result);
  6251. };
  6252. /**
  6253. * Creates a scaling matrix
  6254. * @param x defines the scale factor on X axis
  6255. * @param y defines the scale factor on Y axis
  6256. * @param z defines the scale factor on Z axis
  6257. * @returns the new matrix
  6258. */
  6259. Matrix.Scaling = function (x, y, z) {
  6260. var result = Matrix.Zero();
  6261. Matrix.ScalingToRef(x, y, z, result);
  6262. return result;
  6263. };
  6264. /**
  6265. * Creates a scaling matrix and stores it in a given matrix
  6266. * @param x defines the scale factor on X axis
  6267. * @param y defines the scale factor on Y axis
  6268. * @param z defines the scale factor on Z axis
  6269. * @param result defines the target matrix
  6270. */
  6271. Matrix.ScalingToRef = function (x, y, z, result) {
  6272. result.m[0] = x;
  6273. result.m[1] = 0.0;
  6274. result.m[2] = 0.0;
  6275. result.m[3] = 0.0;
  6276. result.m[4] = 0.0;
  6277. result.m[5] = y;
  6278. result.m[6] = 0.0;
  6279. result.m[7] = 0.0;
  6280. result.m[8] = 0.0;
  6281. result.m[9] = 0.0;
  6282. result.m[10] = z;
  6283. result.m[11] = 0.0;
  6284. result.m[12] = 0.0;
  6285. result.m[13] = 0.0;
  6286. result.m[14] = 0.0;
  6287. result.m[15] = 1.0;
  6288. result._markAsUpdated();
  6289. };
  6290. /**
  6291. * Creates a translation matrix
  6292. * @param x defines the translation on X axis
  6293. * @param y defines the translation on Y axis
  6294. * @param z defines the translationon Z axis
  6295. * @returns the new matrix
  6296. */
  6297. Matrix.Translation = function (x, y, z) {
  6298. var result = Matrix.Identity();
  6299. Matrix.TranslationToRef(x, y, z, result);
  6300. return result;
  6301. };
  6302. /**
  6303. * Creates a translation matrix and stores it in a given matrix
  6304. * @param x defines the translation on X axis
  6305. * @param y defines the translation on Y axis
  6306. * @param z defines the translationon Z axis
  6307. * @param result defines the target matrix
  6308. */
  6309. Matrix.TranslationToRef = function (x, y, z, result) {
  6310. 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);
  6311. };
  6312. /**
  6313. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6314. * @param startValue defines the start value
  6315. * @param endValue defines the end value
  6316. * @param gradient defines the gradient factor
  6317. * @returns the new matrix
  6318. */
  6319. Matrix.Lerp = function (startValue, endValue, gradient) {
  6320. var result = Matrix.Zero();
  6321. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6322. return result;
  6323. };
  6324. /**
  6325. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6326. * @param startValue defines the start value
  6327. * @param endValue defines the end value
  6328. * @param gradient defines the gradient factor
  6329. * @param result defines the Matrix object where to store data
  6330. */
  6331. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6332. for (var index = 0; index < 16; index++) {
  6333. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6334. }
  6335. result._markAsUpdated();
  6336. };
  6337. /**
  6338. * Builds a new matrix whose values are computed by:
  6339. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6340. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6341. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6342. * @param startValue defines the first matrix
  6343. * @param endValue defines the second matrix
  6344. * @param gradient defines the gradient between the two matrices
  6345. * @returns the new matrix
  6346. */
  6347. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6348. var result = Matrix.Zero();
  6349. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6350. return result;
  6351. };
  6352. /**
  6353. * Update a matrix to values which are computed by:
  6354. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6355. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6356. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6357. * @param startValue defines the first matrix
  6358. * @param endValue defines the second matrix
  6359. * @param gradient defines the gradient between the two matrices
  6360. * @param result defines the target matrix
  6361. */
  6362. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6363. var startScale = MathTmp.Vector3[0];
  6364. var startRotation = MathTmp.Quaternion[0];
  6365. var startTranslation = MathTmp.Vector3[1];
  6366. startValue.decompose(startScale, startRotation, startTranslation);
  6367. var endScale = MathTmp.Vector3[2];
  6368. var endRotation = MathTmp.Quaternion[1];
  6369. var endTranslation = MathTmp.Vector3[3];
  6370. endValue.decompose(endScale, endRotation, endTranslation);
  6371. var resultScale = MathTmp.Vector3[4];
  6372. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6373. var resultRotation = MathTmp.Quaternion[2];
  6374. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6375. var resultTranslation = MathTmp.Vector3[5];
  6376. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6377. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6378. };
  6379. /**
  6380. * 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"
  6381. * This function works in left handed mode
  6382. * @param eye defines the final position of the entity
  6383. * @param target defines where the entity should look at
  6384. * @param up defines the up vector for the entity
  6385. * @returns the new matrix
  6386. */
  6387. Matrix.LookAtLH = function (eye, target, up) {
  6388. var result = Matrix.Zero();
  6389. Matrix.LookAtLHToRef(eye, target, up, result);
  6390. return result;
  6391. };
  6392. /**
  6393. * 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".
  6394. * This function works in left handed mode
  6395. * @param eye defines the final position of the entity
  6396. * @param target defines where the entity should look at
  6397. * @param up defines the up vector for the entity
  6398. * @param result defines the target matrix
  6399. */
  6400. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6401. // Z axis
  6402. target.subtractToRef(eye, this._zAxis);
  6403. this._zAxis.normalize();
  6404. // X axis
  6405. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6406. if (this._xAxis.lengthSquared() === 0) {
  6407. this._xAxis.x = 1.0;
  6408. }
  6409. else {
  6410. this._xAxis.normalize();
  6411. }
  6412. // Y axis
  6413. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6414. this._yAxis.normalize();
  6415. // Eye angles
  6416. var ex = -Vector3.Dot(this._xAxis, eye);
  6417. var ey = -Vector3.Dot(this._yAxis, eye);
  6418. var ez = -Vector3.Dot(this._zAxis, eye);
  6419. 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);
  6420. };
  6421. /**
  6422. * 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"
  6423. * This function works in right handed mode
  6424. * @param eye defines the final position of the entity
  6425. * @param target defines where the entity should look at
  6426. * @param up defines the up vector for the entity
  6427. * @returns the new matrix
  6428. */
  6429. Matrix.LookAtRH = function (eye, target, up) {
  6430. var result = Matrix.Zero();
  6431. Matrix.LookAtRHToRef(eye, target, up, result);
  6432. return result;
  6433. };
  6434. /**
  6435. * 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".
  6436. * This function works in right handed mode
  6437. * @param eye defines the final position of the entity
  6438. * @param target defines where the entity should look at
  6439. * @param up defines the up vector for the entity
  6440. * @param result defines the target matrix
  6441. */
  6442. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6443. // Z axis
  6444. eye.subtractToRef(target, this._zAxis);
  6445. this._zAxis.normalize();
  6446. // X axis
  6447. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6448. if (this._xAxis.lengthSquared() === 0) {
  6449. this._xAxis.x = 1.0;
  6450. }
  6451. else {
  6452. this._xAxis.normalize();
  6453. }
  6454. // Y axis
  6455. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6456. this._yAxis.normalize();
  6457. // Eye angles
  6458. var ex = -Vector3.Dot(this._xAxis, eye);
  6459. var ey = -Vector3.Dot(this._yAxis, eye);
  6460. var ez = -Vector3.Dot(this._zAxis, eye);
  6461. 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);
  6462. };
  6463. /**
  6464. * Create a left-handed orthographic projection matrix
  6465. * @param width defines the viewport width
  6466. * @param height defines the viewport height
  6467. * @param znear defines the near clip plane
  6468. * @param zfar defines the far clip plane
  6469. * @returns a new matrix as a left-handed orthographic projection matrix
  6470. */
  6471. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6472. var matrix = Matrix.Zero();
  6473. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6474. return matrix;
  6475. };
  6476. /**
  6477. * Store a left-handed orthographic projection to a given matrix
  6478. * @param width defines the viewport width
  6479. * @param height defines the viewport height
  6480. * @param znear defines the near clip plane
  6481. * @param zfar defines the far clip plane
  6482. * @param result defines the target matrix
  6483. */
  6484. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6485. var n = znear;
  6486. var f = zfar;
  6487. var a = 2.0 / width;
  6488. var b = 2.0 / height;
  6489. var c = 2.0 / (f - n);
  6490. var d = -(f + n) / (f - n);
  6491. 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);
  6492. };
  6493. /**
  6494. * Create a left-handed orthographic projection matrix
  6495. * @param left defines the viewport left coordinate
  6496. * @param right defines the viewport right coordinate
  6497. * @param bottom defines the viewport bottom coordinate
  6498. * @param top defines the viewport top coordinate
  6499. * @param znear defines the near clip plane
  6500. * @param zfar defines the far clip plane
  6501. * @returns a new matrix as a left-handed orthographic projection matrix
  6502. */
  6503. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6504. var matrix = Matrix.Zero();
  6505. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6506. return matrix;
  6507. };
  6508. /**
  6509. * Stores a left-handed orthographic projection into a given matrix
  6510. * @param left defines the viewport left coordinate
  6511. * @param right defines the viewport right coordinate
  6512. * @param bottom defines the viewport bottom coordinate
  6513. * @param top defines the viewport top coordinate
  6514. * @param znear defines the near clip plane
  6515. * @param zfar defines the far clip plane
  6516. * @param result defines the target matrix
  6517. */
  6518. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6519. var n = znear;
  6520. var f = zfar;
  6521. var a = 2.0 / (right - left);
  6522. var b = 2.0 / (top - bottom);
  6523. var c = 2.0 / (f - n);
  6524. var d = -(f + n) / (f - n);
  6525. var i0 = (left + right) / (left - right);
  6526. var i1 = (top + bottom) / (bottom - top);
  6527. 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);
  6528. };
  6529. /**
  6530. * Creates a right-handed orthographic projection matrix
  6531. * @param left defines the viewport left coordinate
  6532. * @param right defines the viewport right coordinate
  6533. * @param bottom defines the viewport bottom coordinate
  6534. * @param top defines the viewport top coordinate
  6535. * @param znear defines the near clip plane
  6536. * @param zfar defines the far clip plane
  6537. * @returns a new matrix as a right-handed orthographic projection matrix
  6538. */
  6539. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6540. var matrix = Matrix.Zero();
  6541. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6542. return matrix;
  6543. };
  6544. /**
  6545. * Stores a right-handed orthographic projection into a given matrix
  6546. * @param left defines the viewport left coordinate
  6547. * @param right defines the viewport right coordinate
  6548. * @param bottom defines the viewport bottom coordinate
  6549. * @param top defines the viewport top coordinate
  6550. * @param znear defines the near clip plane
  6551. * @param zfar defines the far clip plane
  6552. * @param result defines the target matrix
  6553. */
  6554. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6555. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6556. result.m[10] *= -1.0;
  6557. };
  6558. /**
  6559. * Creates a left-handed perspective projection matrix
  6560. * @param width defines the viewport width
  6561. * @param height defines the viewport height
  6562. * @param znear defines the near clip plane
  6563. * @param zfar defines the far clip plane
  6564. * @returns a new matrix as a left-handed perspective projection matrix
  6565. */
  6566. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6567. var matrix = Matrix.Zero();
  6568. var n = znear;
  6569. var f = zfar;
  6570. var a = 2.0 * n / width;
  6571. var b = 2.0 * n / height;
  6572. var c = (f + n) / (f - n);
  6573. var d = -2.0 * f * n / (f - n);
  6574. 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);
  6575. return matrix;
  6576. };
  6577. /**
  6578. * Creates a left-handed perspective projection matrix
  6579. * @param fov defines the horizontal field of view
  6580. * @param aspect defines the aspect ratio
  6581. * @param znear defines the near clip plane
  6582. * @param zfar defines the far clip plane
  6583. * @returns a new matrix as a left-handed perspective projection matrix
  6584. */
  6585. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6586. var matrix = Matrix.Zero();
  6587. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6588. return matrix;
  6589. };
  6590. /**
  6591. * Stores a left-handed perspective projection into a given matrix
  6592. * @param fov defines the horizontal field of view
  6593. * @param aspect defines the aspect ratio
  6594. * @param znear defines the near clip plane
  6595. * @param zfar defines the far clip plane
  6596. * @param result defines the target matrix
  6597. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6598. */
  6599. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6600. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6601. var n = znear;
  6602. var f = zfar;
  6603. var t = 1.0 / (Math.tan(fov * 0.5));
  6604. var a = isVerticalFovFixed ? (t / aspect) : t;
  6605. var b = isVerticalFovFixed ? t : (t * aspect);
  6606. var c = (f + n) / (f - n);
  6607. var d = -2.0 * f * n / (f - n);
  6608. 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);
  6609. };
  6610. /**
  6611. * Creates a right-handed perspective projection matrix
  6612. * @param fov defines the horizontal field of view
  6613. * @param aspect defines the aspect ratio
  6614. * @param znear defines the near clip plane
  6615. * @param zfar defines the far clip plane
  6616. * @returns a new matrix as a right-handed perspective projection matrix
  6617. */
  6618. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6619. var matrix = Matrix.Zero();
  6620. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6621. return matrix;
  6622. };
  6623. /**
  6624. * Stores a right-handed perspective projection into a given matrix
  6625. * @param fov defines the horizontal field of view
  6626. * @param aspect defines the aspect ratio
  6627. * @param znear defines the near clip plane
  6628. * @param zfar defines the far clip plane
  6629. * @param result defines the target matrix
  6630. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6631. */
  6632. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6633. //alternatively this could be expressed as:
  6634. // m = PerspectiveFovLHToRef
  6635. // m[10] *= -1.0;
  6636. // m[11] *= -1.0;
  6637. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6638. var n = znear;
  6639. var f = zfar;
  6640. var t = 1.0 / (Math.tan(fov * 0.5));
  6641. var a = isVerticalFovFixed ? (t / aspect) : t;
  6642. var b = isVerticalFovFixed ? t : (t * aspect);
  6643. var c = -(f + n) / (f - n);
  6644. var d = -2 * f * n / (f - n);
  6645. 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);
  6646. };
  6647. /**
  6648. * Stores a perspective projection for WebVR info a given matrix
  6649. * @param fov defines the field of view
  6650. * @param znear defines the near clip plane
  6651. * @param zfar defines the far clip plane
  6652. * @param result defines the target matrix
  6653. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6654. */
  6655. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6656. if (rightHanded === void 0) { rightHanded = false; }
  6657. var rightHandedFactor = rightHanded ? -1 : 1;
  6658. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6659. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6660. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6661. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6662. var xScale = 2.0 / (leftTan + rightTan);
  6663. var yScale = 2.0 / (upTan + downTan);
  6664. result.m[0] = xScale;
  6665. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6666. result.m[5] = yScale;
  6667. result.m[6] = result.m[7] = 0.0;
  6668. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6669. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6670. result.m[10] = -zfar / (znear - zfar);
  6671. result.m[11] = 1.0 * rightHandedFactor;
  6672. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6673. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6674. result._markAsUpdated();
  6675. };
  6676. /**
  6677. * Computes a complete transformation matrix
  6678. * @param viewport defines the viewport to use
  6679. * @param world defines the world matrix
  6680. * @param view defines the view matrix
  6681. * @param projection defines the projection matrix
  6682. * @param zmin defines the near clip plane
  6683. * @param zmax defines the far clip plane
  6684. * @returns the transformation matrix
  6685. */
  6686. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6687. var cw = viewport.width;
  6688. var ch = viewport.height;
  6689. var cx = viewport.x;
  6690. var cy = viewport.y;
  6691. 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);
  6692. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6693. };
  6694. /**
  6695. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6696. * @param matrix defines the matrix to use
  6697. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6698. */
  6699. Matrix.GetAsMatrix2x2 = function (matrix) {
  6700. return new Float32Array([
  6701. matrix.m[0], matrix.m[1],
  6702. matrix.m[4], matrix.m[5]
  6703. ]);
  6704. };
  6705. /**
  6706. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6707. * @param matrix defines the matrix to use
  6708. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6709. */
  6710. Matrix.GetAsMatrix3x3 = function (matrix) {
  6711. return new Float32Array([
  6712. matrix.m[0], matrix.m[1], matrix.m[2],
  6713. matrix.m[4], matrix.m[5], matrix.m[6],
  6714. matrix.m[8], matrix.m[9], matrix.m[10]
  6715. ]);
  6716. };
  6717. /**
  6718. * Compute the transpose of a given matrix
  6719. * @param matrix defines the matrix to transpose
  6720. * @returns the new matrix
  6721. */
  6722. Matrix.Transpose = function (matrix) {
  6723. var result = new Matrix();
  6724. Matrix.TransposeToRef(matrix, result);
  6725. return result;
  6726. };
  6727. /**
  6728. * Compute the transpose of a matrix and store it in a target matrix
  6729. * @param matrix defines the matrix to transpose
  6730. * @param result defines the target matrix
  6731. */
  6732. Matrix.TransposeToRef = function (matrix, result) {
  6733. result.m[0] = matrix.m[0];
  6734. result.m[1] = matrix.m[4];
  6735. result.m[2] = matrix.m[8];
  6736. result.m[3] = matrix.m[12];
  6737. result.m[4] = matrix.m[1];
  6738. result.m[5] = matrix.m[5];
  6739. result.m[6] = matrix.m[9];
  6740. result.m[7] = matrix.m[13];
  6741. result.m[8] = matrix.m[2];
  6742. result.m[9] = matrix.m[6];
  6743. result.m[10] = matrix.m[10];
  6744. result.m[11] = matrix.m[14];
  6745. result.m[12] = matrix.m[3];
  6746. result.m[13] = matrix.m[7];
  6747. result.m[14] = matrix.m[11];
  6748. result.m[15] = matrix.m[15];
  6749. };
  6750. /**
  6751. * Computes a reflection matrix from a plane
  6752. * @param plane defines the reflection plane
  6753. * @returns a new matrix
  6754. */
  6755. Matrix.Reflection = function (plane) {
  6756. var matrix = new Matrix();
  6757. Matrix.ReflectionToRef(plane, matrix);
  6758. return matrix;
  6759. };
  6760. /**
  6761. * Computes a reflection matrix from a plane
  6762. * @param plane defines the reflection plane
  6763. * @param result defines the target matrix
  6764. */
  6765. Matrix.ReflectionToRef = function (plane, result) {
  6766. plane.normalize();
  6767. var x = plane.normal.x;
  6768. var y = plane.normal.y;
  6769. var z = plane.normal.z;
  6770. var temp = -2 * x;
  6771. var temp2 = -2 * y;
  6772. var temp3 = -2 * z;
  6773. result.m[0] = (temp * x) + 1;
  6774. result.m[1] = temp2 * x;
  6775. result.m[2] = temp3 * x;
  6776. result.m[3] = 0.0;
  6777. result.m[4] = temp * y;
  6778. result.m[5] = (temp2 * y) + 1;
  6779. result.m[6] = temp3 * y;
  6780. result.m[7] = 0.0;
  6781. result.m[8] = temp * z;
  6782. result.m[9] = temp2 * z;
  6783. result.m[10] = (temp3 * z) + 1;
  6784. result.m[11] = 0.0;
  6785. result.m[12] = temp * plane.d;
  6786. result.m[13] = temp2 * plane.d;
  6787. result.m[14] = temp3 * plane.d;
  6788. result.m[15] = 1.0;
  6789. result._markAsUpdated();
  6790. };
  6791. /**
  6792. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6793. * @param xaxis defines the value of the 1st axis
  6794. * @param yaxis defines the value of the 2nd axis
  6795. * @param zaxis defines the value of the 3rd axis
  6796. * @param result defines the target matrix
  6797. */
  6798. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6799. result.m[0] = xaxis.x;
  6800. result.m[1] = xaxis.y;
  6801. result.m[2] = xaxis.z;
  6802. result.m[3] = 0.0;
  6803. result.m[4] = yaxis.x;
  6804. result.m[5] = yaxis.y;
  6805. result.m[6] = yaxis.z;
  6806. result.m[7] = 0.0;
  6807. result.m[8] = zaxis.x;
  6808. result.m[9] = zaxis.y;
  6809. result.m[10] = zaxis.z;
  6810. result.m[11] = 0.0;
  6811. result.m[12] = 0.0;
  6812. result.m[13] = 0.0;
  6813. result.m[14] = 0.0;
  6814. result.m[15] = 1.0;
  6815. result._markAsUpdated();
  6816. };
  6817. /**
  6818. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6819. * @param quat defines the quaternion to use
  6820. * @param result defines the target matrix
  6821. */
  6822. Matrix.FromQuaternionToRef = function (quat, result) {
  6823. var xx = quat.x * quat.x;
  6824. var yy = quat.y * quat.y;
  6825. var zz = quat.z * quat.z;
  6826. var xy = quat.x * quat.y;
  6827. var zw = quat.z * quat.w;
  6828. var zx = quat.z * quat.x;
  6829. var yw = quat.y * quat.w;
  6830. var yz = quat.y * quat.z;
  6831. var xw = quat.x * quat.w;
  6832. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6833. result.m[1] = 2.0 * (xy + zw);
  6834. result.m[2] = 2.0 * (zx - yw);
  6835. result.m[3] = 0.0;
  6836. result.m[4] = 2.0 * (xy - zw);
  6837. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6838. result.m[6] = 2.0 * (yz + xw);
  6839. result.m[7] = 0.0;
  6840. result.m[8] = 2.0 * (zx + yw);
  6841. result.m[9] = 2.0 * (yz - xw);
  6842. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6843. result.m[11] = 0.0;
  6844. result.m[12] = 0.0;
  6845. result.m[13] = 0.0;
  6846. result.m[14] = 0.0;
  6847. result.m[15] = 1.0;
  6848. result._markAsUpdated();
  6849. };
  6850. Matrix._tempQuaternion = new Quaternion();
  6851. Matrix._xAxis = Vector3.Zero();
  6852. Matrix._yAxis = Vector3.Zero();
  6853. Matrix._zAxis = Vector3.Zero();
  6854. Matrix._updateFlagSeed = 0;
  6855. Matrix._identityReadOnly = Matrix.Identity();
  6856. return Matrix;
  6857. }());
  6858. BABYLON.Matrix = Matrix;
  6859. /**
  6860. * Represens a plane by the equation ax + by + cz + d = 0
  6861. */
  6862. var Plane = /** @class */ (function () {
  6863. /**
  6864. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6865. * @param a a component of the plane
  6866. * @param b b component of the plane
  6867. * @param c c component of the plane
  6868. * @param d d component of the plane
  6869. */
  6870. function Plane(a, b, c, d) {
  6871. this.normal = new Vector3(a, b, c);
  6872. this.d = d;
  6873. }
  6874. /**
  6875. * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6876. */
  6877. Plane.prototype.asArray = function () {
  6878. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6879. };
  6880. // Methods
  6881. /**
  6882. * @returns a new plane copied from the current Plane.
  6883. */
  6884. Plane.prototype.clone = function () {
  6885. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6886. };
  6887. /**
  6888. * @returns the string "Plane".
  6889. */
  6890. Plane.prototype.getClassName = function () {
  6891. return "Plane";
  6892. };
  6893. /**
  6894. * @returns the Plane hash code.
  6895. */
  6896. Plane.prototype.getHashCode = function () {
  6897. var hash = this.normal.getHashCode();
  6898. hash = (hash * 397) ^ (this.d || 0);
  6899. return hash;
  6900. };
  6901. /**
  6902. * Normalize the current Plane in place.
  6903. * @returns the updated Plane.
  6904. */
  6905. Plane.prototype.normalize = function () {
  6906. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6907. var magnitude = 0.0;
  6908. if (norm !== 0) {
  6909. magnitude = 1.0 / norm;
  6910. }
  6911. this.normal.x *= magnitude;
  6912. this.normal.y *= magnitude;
  6913. this.normal.z *= magnitude;
  6914. this.d *= magnitude;
  6915. return this;
  6916. };
  6917. /**
  6918. * Applies a transformation the plane and returns the result
  6919. * @param transformation the transformation matrix to be applied to the plane
  6920. * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6921. */
  6922. Plane.prototype.transform = function (transformation) {
  6923. var transposedMatrix = Matrix.Transpose(transformation);
  6924. var x = this.normal.x;
  6925. var y = this.normal.y;
  6926. var z = this.normal.z;
  6927. var d = this.d;
  6928. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6929. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6930. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6931. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6932. return new Plane(normalX, normalY, normalZ, finalD);
  6933. };
  6934. /**
  6935. * Calcualtte the dot product between the point and the plane normal
  6936. * @param point point to calculate the dot product with
  6937. * @returns the dot product (float) of the point coordinates and the plane normal.
  6938. */
  6939. Plane.prototype.dotCoordinate = function (point) {
  6940. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6941. };
  6942. /**
  6943. * Updates the current Plane from the plane defined by the three given points.
  6944. * @param point1 one of the points used to contruct the plane
  6945. * @param point2 one of the points used to contruct the plane
  6946. * @param point3 one of the points used to contruct the plane
  6947. * @returns the updated Plane.
  6948. */
  6949. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6950. var x1 = point2.x - point1.x;
  6951. var y1 = point2.y - point1.y;
  6952. var z1 = point2.z - point1.z;
  6953. var x2 = point3.x - point1.x;
  6954. var y2 = point3.y - point1.y;
  6955. var z2 = point3.z - point1.z;
  6956. var yz = (y1 * z2) - (z1 * y2);
  6957. var xz = (z1 * x2) - (x1 * z2);
  6958. var xy = (x1 * y2) - (y1 * x2);
  6959. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6960. var invPyth;
  6961. if (pyth !== 0) {
  6962. invPyth = 1.0 / pyth;
  6963. }
  6964. else {
  6965. invPyth = 0.0;
  6966. }
  6967. this.normal.x = yz * invPyth;
  6968. this.normal.y = xz * invPyth;
  6969. this.normal.z = xy * invPyth;
  6970. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6971. return this;
  6972. };
  6973. /**
  6974. * Checks if the plane is facing a given direction
  6975. * @param direction the direction to check if the plane is facing
  6976. * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
  6977. * @returns True is the vector "direction" is the same side than the plane normal.
  6978. */
  6979. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6980. var dot = Vector3.Dot(this.normal, direction);
  6981. return (dot <= epsilon);
  6982. };
  6983. /**
  6984. * Calculates the distance to a point
  6985. * @param point point to calculate distance to
  6986. * @returns the signed distance (float) from the given point to the Plane.
  6987. */
  6988. Plane.prototype.signedDistanceTo = function (point) {
  6989. return Vector3.Dot(point, this.normal) + this.d;
  6990. };
  6991. // Statics
  6992. /**
  6993. * Creates a plane from an array
  6994. * @param array the array to create a plane from
  6995. * @returns a new Plane from the given array.
  6996. */
  6997. Plane.FromArray = function (array) {
  6998. return new Plane(array[0], array[1], array[2], array[3]);
  6999. };
  7000. /**
  7001. * Creates a plane from three points
  7002. * @param point1 point used to create the plane
  7003. * @param point2 point used to create the plane
  7004. * @param point3 point used to create the plane
  7005. * @returns a new Plane defined by the three given points.
  7006. */
  7007. Plane.FromPoints = function (point1, point2, point3) {
  7008. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7009. result.copyFromPoints(point1, point2, point3);
  7010. return result;
  7011. };
  7012. /**
  7013. * Creates a plane from an origin point and a normal
  7014. * @param origin origin of the plane to be constructed
  7015. * @param normal normal of the plane to be constructed
  7016. * @returns a new Plane the normal vector to this plane at the given origin point.
  7017. * Note : the vector "normal" is updated because normalized.
  7018. */
  7019. Plane.FromPositionAndNormal = function (origin, normal) {
  7020. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7021. normal.normalize();
  7022. result.normal = normal;
  7023. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7024. return result;
  7025. };
  7026. /**
  7027. * Calculates the distance from a plane and a point
  7028. * @param origin origin of the plane to be constructed
  7029. * @param normal normal of the plane to be constructed
  7030. * @param point point to calculate distance to
  7031. * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  7032. */
  7033. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  7034. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7035. return Vector3.Dot(point, normal) + d;
  7036. };
  7037. return Plane;
  7038. }());
  7039. BABYLON.Plane = Plane;
  7040. /**
  7041. * Class used to represent a viewport on screen
  7042. */
  7043. var Viewport = /** @class */ (function () {
  7044. /**
  7045. * Creates a Viewport object located at (x, y) and sized (width, height)
  7046. * @param x defines viewport left coordinate
  7047. * @param y defines viewport top coordinate
  7048. * @param width defines the viewport width
  7049. * @param height defines the viewport height
  7050. */
  7051. function Viewport(
  7052. /** viewport left coordinate */
  7053. x,
  7054. /** viewport top coordinate */
  7055. y,
  7056. /**viewport width */
  7057. width,
  7058. /** viewport height */
  7059. height) {
  7060. this.x = x;
  7061. this.y = y;
  7062. this.width = width;
  7063. this.height = height;
  7064. }
  7065. /**
  7066. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  7067. * @param renderWidthOrEngine defines either an engine or the rendering width
  7068. * @param renderHeight defines the rendering height
  7069. * @returns a new Viewport
  7070. */
  7071. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  7072. if (renderWidthOrEngine.getRenderWidth) {
  7073. var engine = renderWidthOrEngine;
  7074. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  7075. }
  7076. var renderWidth = renderWidthOrEngine;
  7077. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  7078. };
  7079. /**
  7080. * Returns a new Viewport copied from the current one
  7081. * @returns a new Viewport
  7082. */
  7083. Viewport.prototype.clone = function () {
  7084. return new Viewport(this.x, this.y, this.width, this.height);
  7085. };
  7086. return Viewport;
  7087. }());
  7088. BABYLON.Viewport = Viewport;
  7089. /**
  7090. * Reprasents a camera frustum
  7091. */
  7092. var Frustum = /** @class */ (function () {
  7093. function Frustum() {
  7094. }
  7095. /**
  7096. * Gets the planes representing the frustum
  7097. * @param transform matrix to be applied to the returned planes
  7098. * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
  7099. */
  7100. Frustum.GetPlanes = function (transform) {
  7101. var frustumPlanes = [];
  7102. for (var index = 0; index < 6; index++) {
  7103. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  7104. }
  7105. Frustum.GetPlanesToRef(transform, frustumPlanes);
  7106. return frustumPlanes;
  7107. };
  7108. /**
  7109. * Gets the near frustum plane transformed by the transform matrix
  7110. * @param transform transformation matrix to be applied to the resulting frustum plane
  7111. * @param frustumPlane the resuling frustum plane
  7112. */
  7113. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  7114. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  7115. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  7116. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  7117. frustumPlane.d = transform.m[15] + transform.m[14];
  7118. frustumPlane.normalize();
  7119. };
  7120. /**
  7121. * Gets the far frustum plane transformed by the transform matrix
  7122. * @param transform transformation matrix to be applied to the resulting frustum plane
  7123. * @param frustumPlane the resuling frustum plane
  7124. */
  7125. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  7126. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  7127. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  7128. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  7129. frustumPlane.d = transform.m[15] - transform.m[14];
  7130. frustumPlane.normalize();
  7131. };
  7132. /**
  7133. * Gets the left frustum plane transformed by the transform matrix
  7134. * @param transform transformation matrix to be applied to the resulting frustum plane
  7135. * @param frustumPlane the resuling frustum plane
  7136. */
  7137. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  7138. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  7139. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  7140. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  7141. frustumPlane.d = transform.m[15] + transform.m[12];
  7142. frustumPlane.normalize();
  7143. };
  7144. /**
  7145. * Gets the right frustum plane transformed by the transform matrix
  7146. * @param transform transformation matrix to be applied to the resulting frustum plane
  7147. * @param frustumPlane the resuling frustum plane
  7148. */
  7149. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  7150. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  7151. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  7152. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  7153. frustumPlane.d = transform.m[15] - transform.m[12];
  7154. frustumPlane.normalize();
  7155. };
  7156. /**
  7157. * Gets the top frustum plane transformed by the transform matrix
  7158. * @param transform transformation matrix to be applied to the resulting frustum plane
  7159. * @param frustumPlane the resuling frustum plane
  7160. */
  7161. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  7162. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  7163. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  7164. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  7165. frustumPlane.d = transform.m[15] - transform.m[13];
  7166. frustumPlane.normalize();
  7167. };
  7168. /**
  7169. * Gets the bottom frustum plane transformed by the transform matrix
  7170. * @param transform transformation matrix to be applied to the resulting frustum plane
  7171. * @param frustumPlane the resuling frustum plane
  7172. */
  7173. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  7174. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  7175. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  7176. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  7177. frustumPlane.d = transform.m[15] + transform.m[13];
  7178. frustumPlane.normalize();
  7179. };
  7180. /**
  7181. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  7182. * @param transform transformation matrix to be applied to the resulting frustum planes
  7183. * @param frustumPlanes the resuling frustum planes
  7184. */
  7185. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  7186. // Near
  7187. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  7188. // Far
  7189. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  7190. // Left
  7191. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  7192. // Right
  7193. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  7194. // Top
  7195. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  7196. // Bottom
  7197. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  7198. };
  7199. return Frustum;
  7200. }());
  7201. BABYLON.Frustum = Frustum;
  7202. /** Defines supported spaces */
  7203. var Space;
  7204. (function (Space) {
  7205. /** Local (object) space */
  7206. Space[Space["LOCAL"] = 0] = "LOCAL";
  7207. /** World space */
  7208. Space[Space["WORLD"] = 1] = "WORLD";
  7209. /** Bone space */
  7210. Space[Space["BONE"] = 2] = "BONE";
  7211. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  7212. /** Defines the 3 main axes */
  7213. var Axis = /** @class */ (function () {
  7214. function Axis() {
  7215. }
  7216. /** X axis */
  7217. Axis.X = new Vector3(1.0, 0.0, 0.0);
  7218. /** Y axis */
  7219. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  7220. /** Z axis */
  7221. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  7222. return Axis;
  7223. }());
  7224. BABYLON.Axis = Axis;
  7225. ;
  7226. /** Class used to represent a Bezier curve */
  7227. var BezierCurve = /** @class */ (function () {
  7228. function BezierCurve() {
  7229. }
  7230. /**
  7231. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  7232. * @param t defines the time
  7233. * @param x1 defines the left coordinate on X axis
  7234. * @param y1 defines the left coordinate on Y axis
  7235. * @param x2 defines the right coordinate on X axis
  7236. * @param y2 defines the right coordinate on Y axis
  7237. * @returns the interpolated value
  7238. */
  7239. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  7240. // Extract X (which is equal to time here)
  7241. var f0 = 1 - 3 * x2 + 3 * x1;
  7242. var f1 = 3 * x2 - 6 * x1;
  7243. var f2 = 3 * x1;
  7244. var refinedT = t;
  7245. for (var i = 0; i < 5; i++) {
  7246. var refinedT2 = refinedT * refinedT;
  7247. var refinedT3 = refinedT2 * refinedT;
  7248. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  7249. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  7250. refinedT -= (x - t) * slope;
  7251. refinedT = Math.min(1, Math.max(0, refinedT));
  7252. }
  7253. // Resolve cubic bezier for the given x
  7254. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  7255. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  7256. Math.pow(refinedT, 3);
  7257. };
  7258. return BezierCurve;
  7259. }());
  7260. BABYLON.BezierCurve = BezierCurve;
  7261. /**
  7262. * Defines potential orientation for back face culling
  7263. */
  7264. var Orientation;
  7265. (function (Orientation) {
  7266. /**
  7267. * Clockwise
  7268. */
  7269. Orientation[Orientation["CW"] = 0] = "CW";
  7270. /** Counter clockwise */
  7271. Orientation[Orientation["CCW"] = 1] = "CCW";
  7272. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  7273. /**
  7274. * Defines angle representation
  7275. */
  7276. var Angle = /** @class */ (function () {
  7277. /**
  7278. * Creates an Angle object of "radians" radians (float).
  7279. */
  7280. function Angle(radians) {
  7281. this._radians = radians;
  7282. if (this._radians < 0.0)
  7283. this._radians += (2.0 * Math.PI);
  7284. }
  7285. /**
  7286. * Get value in degrees
  7287. * @returns the Angle value in degrees (float)
  7288. */
  7289. Angle.prototype.degrees = function () {
  7290. return this._radians * 180.0 / Math.PI;
  7291. };
  7292. /**
  7293. * Get value in radians
  7294. * @returns the Angle value in radians (float)
  7295. */
  7296. Angle.prototype.radians = function () {
  7297. return this._radians;
  7298. };
  7299. /**
  7300. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  7301. * @param a defines first vector
  7302. * @param b defines second vector
  7303. * @returns a new Angle
  7304. */
  7305. Angle.BetweenTwoPoints = function (a, b) {
  7306. var delta = b.subtract(a);
  7307. var theta = Math.atan2(delta.y, delta.x);
  7308. return new Angle(theta);
  7309. };
  7310. /**
  7311. * Gets a new Angle object from the given float in radians
  7312. * @param radians defines the angle value in radians
  7313. * @returns a new Angle
  7314. */
  7315. Angle.FromRadians = function (radians) {
  7316. return new Angle(radians);
  7317. };
  7318. /**
  7319. * Gets a new Angle object from the given float in degrees
  7320. * @param degrees defines the angle value in degrees
  7321. * @returns a new Angle
  7322. */
  7323. Angle.FromDegrees = function (degrees) {
  7324. return new Angle(degrees * Math.PI / 180.0);
  7325. };
  7326. return Angle;
  7327. }());
  7328. BABYLON.Angle = Angle;
  7329. /**
  7330. * This represents an arc in a 2d space.
  7331. */
  7332. var Arc2 = /** @class */ (function () {
  7333. /**
  7334. * Creates an Arc object from the three given points : start, middle and end.
  7335. * @param startPoint Defines the start point of the arc
  7336. * @param midPoint Defines the midlle point of the arc
  7337. * @param endPoint Defines the end point of the arc
  7338. */
  7339. function Arc2(
  7340. /** Defines the start point of the arc */
  7341. startPoint,
  7342. /** Defines the mid point of the arc */
  7343. midPoint,
  7344. /** Defines the end point of the arc */
  7345. endPoint) {
  7346. this.startPoint = startPoint;
  7347. this.midPoint = midPoint;
  7348. this.endPoint = endPoint;
  7349. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7350. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7351. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7352. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7353. 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);
  7354. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7355. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7356. var a1 = this.startAngle.degrees();
  7357. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7358. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7359. // angles correction
  7360. if (a2 - a1 > +180.0)
  7361. a2 -= 360.0;
  7362. if (a2 - a1 < -180.0)
  7363. a2 += 360.0;
  7364. if (a3 - a2 > +180.0)
  7365. a3 -= 360.0;
  7366. if (a3 - a2 < -180.0)
  7367. a3 += 360.0;
  7368. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7369. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7370. }
  7371. return Arc2;
  7372. }());
  7373. BABYLON.Arc2 = Arc2;
  7374. /**
  7375. * Represents a 2D path made up of multiple 2D points
  7376. */
  7377. var Path2 = /** @class */ (function () {
  7378. /**
  7379. * Creates a Path2 object from the starting 2D coordinates x and y.
  7380. * @param x the starting points x value
  7381. * @param y the starting points y value
  7382. */
  7383. function Path2(x, y) {
  7384. this._points = new Array();
  7385. this._length = 0.0;
  7386. /**
  7387. * If the path start and end point are the same
  7388. */
  7389. this.closed = false;
  7390. this._points.push(new Vector2(x, y));
  7391. }
  7392. /**
  7393. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7394. * @param x the added points x value
  7395. * @param y the added points y value
  7396. * @returns the updated Path2.
  7397. */
  7398. Path2.prototype.addLineTo = function (x, y) {
  7399. if (this.closed) {
  7400. return this;
  7401. }
  7402. var newPoint = new Vector2(x, y);
  7403. var previousPoint = this._points[this._points.length - 1];
  7404. this._points.push(newPoint);
  7405. this._length += newPoint.subtract(previousPoint).length();
  7406. return this;
  7407. };
  7408. /**
  7409. * 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.
  7410. * @param midX middle point x value
  7411. * @param midY middle point y value
  7412. * @param endX end point x value
  7413. * @param endY end point y value
  7414. * @param numberOfSegments (default: 36)
  7415. * @returns the updated Path2.
  7416. */
  7417. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7418. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7419. if (this.closed) {
  7420. return this;
  7421. }
  7422. var startPoint = this._points[this._points.length - 1];
  7423. var midPoint = new Vector2(midX, midY);
  7424. var endPoint = new Vector2(endX, endY);
  7425. var arc = new Arc2(startPoint, midPoint, endPoint);
  7426. var increment = arc.angle.radians() / numberOfSegments;
  7427. if (arc.orientation === Orientation.CW)
  7428. increment *= -1;
  7429. var currentAngle = arc.startAngle.radians() + increment;
  7430. for (var i = 0; i < numberOfSegments; i++) {
  7431. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7432. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7433. this.addLineTo(x, y);
  7434. currentAngle += increment;
  7435. }
  7436. return this;
  7437. };
  7438. /**
  7439. * Closes the Path2.
  7440. * @returns the Path2.
  7441. */
  7442. Path2.prototype.close = function () {
  7443. this.closed = true;
  7444. return this;
  7445. };
  7446. /**
  7447. * Gets the sum of the distance between each sequential point in the path
  7448. * @returns the Path2 total length (float).
  7449. */
  7450. Path2.prototype.length = function () {
  7451. var result = this._length;
  7452. if (!this.closed) {
  7453. var lastPoint = this._points[this._points.length - 1];
  7454. var firstPoint = this._points[0];
  7455. result += (firstPoint.subtract(lastPoint).length());
  7456. }
  7457. return result;
  7458. };
  7459. /**
  7460. * Gets the points which construct the path
  7461. * @returns the Path2 internal array of points.
  7462. */
  7463. Path2.prototype.getPoints = function () {
  7464. return this._points;
  7465. };
  7466. /**
  7467. * Retreives the point at the distance aways from the starting point
  7468. * @param normalizedLengthPosition the length along the path to retreive the point from
  7469. * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7470. */
  7471. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7472. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7473. return Vector2.Zero();
  7474. }
  7475. var lengthPosition = normalizedLengthPosition * this.length();
  7476. var previousOffset = 0;
  7477. for (var i = 0; i < this._points.length; i++) {
  7478. var j = (i + 1) % this._points.length;
  7479. var a = this._points[i];
  7480. var b = this._points[j];
  7481. var bToA = b.subtract(a);
  7482. var nextOffset = (bToA.length() + previousOffset);
  7483. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7484. var dir = bToA.normalize();
  7485. var localOffset = lengthPosition - previousOffset;
  7486. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7487. }
  7488. previousOffset = nextOffset;
  7489. }
  7490. return Vector2.Zero();
  7491. };
  7492. /**
  7493. * Creates a new path starting from an x and y position
  7494. * @param x starting x value
  7495. * @param y starting y value
  7496. * @returns a new Path2 starting at the coordinates (x, y).
  7497. */
  7498. Path2.StartingAt = function (x, y) {
  7499. return new Path2(x, y);
  7500. };
  7501. return Path2;
  7502. }());
  7503. BABYLON.Path2 = Path2;
  7504. /**
  7505. * Represents a 3D path made up of multiple 3D points
  7506. */
  7507. var Path3D = /** @class */ (function () {
  7508. /**
  7509. * new Path3D(path, normal, raw)
  7510. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7511. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7512. * @param path an array of Vector3, the curve axis of the Path3D
  7513. * @param normal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7514. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7515. */
  7516. function Path3D(
  7517. /**
  7518. * an array of Vector3, the curve axis of the Path3D
  7519. */
  7520. path, firstNormal, raw) {
  7521. if (firstNormal === void 0) { firstNormal = null; }
  7522. this.path = path;
  7523. this._curve = new Array();
  7524. this._distances = new Array();
  7525. this._tangents = new Array();
  7526. this._normals = new Array();
  7527. this._binormals = new Array();
  7528. for (var p = 0; p < path.length; p++) {
  7529. this._curve[p] = path[p].clone(); // hard copy
  7530. }
  7531. this._raw = raw || false;
  7532. this._compute(firstNormal);
  7533. }
  7534. /**
  7535. * Returns the Path3D array of successive Vector3 designing its curve.
  7536. * @returns the Path3D array of successive Vector3 designing its curve.
  7537. */
  7538. Path3D.prototype.getCurve = function () {
  7539. return this._curve;
  7540. };
  7541. /**
  7542. * Returns an array populated with tangent vectors on each Path3D curve point.
  7543. * @returns an array populated with tangent vectors on each Path3D curve point.
  7544. */
  7545. Path3D.prototype.getTangents = function () {
  7546. return this._tangents;
  7547. };
  7548. /**
  7549. * Returns an array populated with normal vectors on each Path3D curve point.
  7550. * @returns an array populated with normal vectors on each Path3D curve point.
  7551. */
  7552. Path3D.prototype.getNormals = function () {
  7553. return this._normals;
  7554. };
  7555. /**
  7556. * Returns an array populated with binormal vectors on each Path3D curve point.
  7557. * @returns an array populated with binormal vectors on each Path3D curve point.
  7558. */
  7559. Path3D.prototype.getBinormals = function () {
  7560. return this._binormals;
  7561. };
  7562. /**
  7563. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7564. * @returns an array populated with distances (float) of the i-th point from the first curve point.
  7565. */
  7566. Path3D.prototype.getDistances = function () {
  7567. return this._distances;
  7568. };
  7569. /**
  7570. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7571. * @param path path which all values are copied into the curves points
  7572. * @param firstNormal which should be projected onto the curve
  7573. * @returns the same object updated.
  7574. */
  7575. Path3D.prototype.update = function (path, firstNormal) {
  7576. if (firstNormal === void 0) { firstNormal = null; }
  7577. for (var p = 0; p < path.length; p++) {
  7578. this._curve[p].x = path[p].x;
  7579. this._curve[p].y = path[p].y;
  7580. this._curve[p].z = path[p].z;
  7581. }
  7582. this._compute(firstNormal);
  7583. return this;
  7584. };
  7585. // private function compute() : computes tangents, normals and binormals
  7586. Path3D.prototype._compute = function (firstNormal) {
  7587. var l = this._curve.length;
  7588. // first and last tangents
  7589. this._tangents[0] = this._getFirstNonNullVector(0);
  7590. if (!this._raw) {
  7591. this._tangents[0].normalize();
  7592. }
  7593. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7594. if (!this._raw) {
  7595. this._tangents[l - 1].normalize();
  7596. }
  7597. // normals and binormals at first point : arbitrary vector with _normalVector()
  7598. var tg0 = this._tangents[0];
  7599. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7600. this._normals[0] = pp0;
  7601. if (!this._raw) {
  7602. this._normals[0].normalize();
  7603. }
  7604. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7605. if (!this._raw) {
  7606. this._binormals[0].normalize();
  7607. }
  7608. this._distances[0] = 0.0;
  7609. // normals and binormals : next points
  7610. var prev; // previous vector (segment)
  7611. var cur; // current vector (segment)
  7612. var curTang; // current tangent
  7613. // previous normal
  7614. var prevBinor; // previous binormal
  7615. for (var i = 1; i < l; i++) {
  7616. // tangents
  7617. prev = this._getLastNonNullVector(i);
  7618. if (i < l - 1) {
  7619. cur = this._getFirstNonNullVector(i);
  7620. this._tangents[i] = prev.add(cur);
  7621. this._tangents[i].normalize();
  7622. }
  7623. this._distances[i] = this._distances[i - 1] + prev.length();
  7624. // normals and binormals
  7625. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7626. curTang = this._tangents[i];
  7627. prevBinor = this._binormals[i - 1];
  7628. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7629. if (!this._raw) {
  7630. this._normals[i].normalize();
  7631. }
  7632. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7633. if (!this._raw) {
  7634. this._binormals[i].normalize();
  7635. }
  7636. }
  7637. };
  7638. // private function getFirstNonNullVector(index)
  7639. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7640. Path3D.prototype._getFirstNonNullVector = function (index) {
  7641. var i = 1;
  7642. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7643. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7644. i++;
  7645. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7646. }
  7647. return nNVector;
  7648. };
  7649. // private function getLastNonNullVector(index)
  7650. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7651. Path3D.prototype._getLastNonNullVector = function (index) {
  7652. var i = 1;
  7653. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7654. while (nLVector.length() === 0 && index > i + 1) {
  7655. i++;
  7656. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7657. }
  7658. return nLVector;
  7659. };
  7660. // private function normalVector(v0, vt, va) :
  7661. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7662. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7663. Path3D.prototype._normalVector = function (v0, vt, va) {
  7664. var normal0;
  7665. var tgl = vt.length();
  7666. if (tgl === 0.0) {
  7667. tgl = 1.0;
  7668. }
  7669. if (va === undefined || va === null) {
  7670. var point;
  7671. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7672. point = new Vector3(0.0, -1.0, 0.0);
  7673. }
  7674. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7675. point = new Vector3(1.0, 0.0, 0.0);
  7676. }
  7677. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7678. point = new Vector3(0.0, 0.0, 1.0);
  7679. }
  7680. else {
  7681. point = Vector3.Zero();
  7682. }
  7683. normal0 = Vector3.Cross(vt, point);
  7684. }
  7685. else {
  7686. normal0 = Vector3.Cross(vt, va);
  7687. Vector3.CrossToRef(normal0, vt, normal0);
  7688. }
  7689. normal0.normalize();
  7690. return normal0;
  7691. };
  7692. return Path3D;
  7693. }());
  7694. BABYLON.Path3D = Path3D;
  7695. /**
  7696. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7697. * A Curve3 is designed from a series of successive Vector3.
  7698. * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
  7699. */
  7700. var Curve3 = /** @class */ (function () {
  7701. /**
  7702. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7703. * A Curve3 is designed from a series of successive Vector3.
  7704. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7705. * @param points points which make up the curve
  7706. */
  7707. function Curve3(points) {
  7708. this._length = 0.0;
  7709. this._points = points;
  7710. this._length = this._computeLength(points);
  7711. }
  7712. /**
  7713. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7714. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7715. * @param v1 (Vector3) the control point
  7716. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7717. * @param nbPoints (integer) the wanted number of points in the curve
  7718. * @returns the created Curve3
  7719. */
  7720. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7721. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7722. var bez = new Array();
  7723. var equation = function (t, val0, val1, val2) {
  7724. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7725. return res;
  7726. };
  7727. for (var i = 0; i <= nbPoints; i++) {
  7728. 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)));
  7729. }
  7730. return new Curve3(bez);
  7731. };
  7732. /**
  7733. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7734. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7735. * @param v1 (Vector3) the first control point
  7736. * @param v2 (Vector3) the second control point
  7737. * @param v3 (Vector3) the end point of the Cubic Bezier
  7738. * @param nbPoints (integer) the wanted number of points in the curve
  7739. * @returns the created Curve3
  7740. */
  7741. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7742. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7743. var bez = new Array();
  7744. var equation = function (t, val0, val1, val2, val3) {
  7745. 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;
  7746. return res;
  7747. };
  7748. for (var i = 0; i <= nbPoints; i++) {
  7749. 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)));
  7750. }
  7751. return new Curve3(bez);
  7752. };
  7753. /**
  7754. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7755. * @param p1 (Vector3) the origin point of the Hermite Spline
  7756. * @param t1 (Vector3) the tangent vector at the origin point
  7757. * @param p2 (Vector3) the end point of the Hermite Spline
  7758. * @param t2 (Vector3) the tangent vector at the end point
  7759. * @param nbPoints (integer) the wanted number of points in the curve
  7760. * @returns the created Curve3
  7761. */
  7762. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7763. var hermite = new Array();
  7764. var step = 1.0 / nbPoints;
  7765. for (var i = 0; i <= nbPoints; i++) {
  7766. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7767. }
  7768. return new Curve3(hermite);
  7769. };
  7770. /**
  7771. * Returns a Curve3 object along a CatmullRom Spline curve :
  7772. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7773. * @param nbPoints (integer) the wanted number of points between each curve control points
  7774. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7775. * @returns the created Curve3
  7776. */
  7777. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7778. var catmullRom = new Array();
  7779. var step = 1.0 / nbPoints;
  7780. var amount = 0.0;
  7781. if (closed) {
  7782. var pointsCount = points.length;
  7783. for (var i = 0; i < pointsCount; i++) {
  7784. amount = 0;
  7785. for (var c = 0; c < nbPoints; c++) {
  7786. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7787. amount += step;
  7788. }
  7789. }
  7790. catmullRom.push(catmullRom[0]);
  7791. }
  7792. else {
  7793. var totalPoints = new Array();
  7794. totalPoints.push(points[0].clone());
  7795. Array.prototype.push.apply(totalPoints, points);
  7796. totalPoints.push(points[points.length - 1].clone());
  7797. for (var i = 0; i < totalPoints.length - 3; i++) {
  7798. amount = 0;
  7799. for (var c = 0; c < nbPoints; c++) {
  7800. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7801. amount += step;
  7802. }
  7803. }
  7804. i--;
  7805. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7806. }
  7807. return new Curve3(catmullRom);
  7808. };
  7809. /**
  7810. * @returns the Curve3 stored array of successive Vector3
  7811. */
  7812. Curve3.prototype.getPoints = function () {
  7813. return this._points;
  7814. };
  7815. /**
  7816. * @returns the computed length (float) of the curve.
  7817. */
  7818. Curve3.prototype.length = function () {
  7819. return this._length;
  7820. };
  7821. /**
  7822. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7823. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7824. * curveA and curveB keep unchanged.
  7825. * @param curve the curve to continue from this curve
  7826. * @returns the newly constructed curve
  7827. */
  7828. Curve3.prototype.continue = function (curve) {
  7829. var lastPoint = this._points[this._points.length - 1];
  7830. var continuedPoints = this._points.slice();
  7831. var curvePoints = curve.getPoints();
  7832. for (var i = 1; i < curvePoints.length; i++) {
  7833. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7834. }
  7835. var continuedCurve = new Curve3(continuedPoints);
  7836. return continuedCurve;
  7837. };
  7838. Curve3.prototype._computeLength = function (path) {
  7839. var l = 0;
  7840. for (var i = 1; i < path.length; i++) {
  7841. l += (path[i].subtract(path[i - 1])).length();
  7842. }
  7843. return l;
  7844. };
  7845. return Curve3;
  7846. }());
  7847. BABYLON.Curve3 = Curve3;
  7848. // Vertex formats
  7849. /**
  7850. * Contains position and normal vectors for a vertex
  7851. */
  7852. var PositionNormalVertex = /** @class */ (function () {
  7853. /**
  7854. * Creates a PositionNormalVertex
  7855. * @param position the position of the vertex (defaut: 0,0,0)
  7856. * @param normal the normal of the vertex (defaut: 0,1,0)
  7857. */
  7858. function PositionNormalVertex(
  7859. /** the position of the vertex (defaut: 0,0,0) */
  7860. position,
  7861. /** the normal of the vertex (defaut: 0,1,0) */
  7862. normal) {
  7863. if (position === void 0) { position = Vector3.Zero(); }
  7864. if (normal === void 0) { normal = Vector3.Up(); }
  7865. this.position = position;
  7866. this.normal = normal;
  7867. }
  7868. /**
  7869. * Clones the PositionNormalVertex
  7870. * @returns the cloned PositionNormalVertex
  7871. */
  7872. PositionNormalVertex.prototype.clone = function () {
  7873. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7874. };
  7875. return PositionNormalVertex;
  7876. }());
  7877. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7878. /**
  7879. * Contains position, normal and uv vectors for a vertex
  7880. */
  7881. var PositionNormalTextureVertex = /** @class */ (function () {
  7882. /**
  7883. * Creates a PositionNormalTextureVertex
  7884. * @param position the position of the vertex (defaut: 0,0,0)
  7885. * @param normal the normal of the vertex (defaut: 0,1,0)
  7886. * @param uv the uv of the vertex (default: 0,0)
  7887. */
  7888. function PositionNormalTextureVertex(
  7889. /** the position of the vertex (defaut: 0,0,0) */
  7890. position,
  7891. /** the normal of the vertex (defaut: 0,1,0) */
  7892. normal,
  7893. /** the uv of the vertex (default: 0,0) */
  7894. uv) {
  7895. if (position === void 0) { position = Vector3.Zero(); }
  7896. if (normal === void 0) { normal = Vector3.Up(); }
  7897. if (uv === void 0) { uv = Vector2.Zero(); }
  7898. this.position = position;
  7899. this.normal = normal;
  7900. this.uv = uv;
  7901. }
  7902. /**
  7903. * Clones the PositionNormalTextureVertex
  7904. * @returns the cloned PositionNormalTextureVertex
  7905. */
  7906. PositionNormalTextureVertex.prototype.clone = function () {
  7907. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7908. };
  7909. return PositionNormalTextureVertex;
  7910. }());
  7911. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7912. // Temporary pre-allocated objects for engine internal use
  7913. // usage in any internal function :
  7914. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7915. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7916. /**
  7917. * @hidden
  7918. */
  7919. var Tmp = /** @class */ (function () {
  7920. function Tmp() {
  7921. }
  7922. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7923. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7924. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7925. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7926. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7927. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7928. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7929. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7930. Matrix.Zero(), Matrix.Zero(),
  7931. Matrix.Zero(), Matrix.Zero(),
  7932. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7933. return Tmp;
  7934. }());
  7935. BABYLON.Tmp = Tmp;
  7936. /**
  7937. * @hidden
  7938. * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7939. */
  7940. var MathTmp = /** @class */ (function () {
  7941. function MathTmp() {
  7942. }
  7943. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7944. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7945. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7946. return MathTmp;
  7947. }());
  7948. })(BABYLON || (BABYLON = {}));
  7949. //# sourceMappingURL=babylon.math.js.map
  7950. var BABYLON;
  7951. (function (BABYLON) {
  7952. var Scalar = /** @class */ (function () {
  7953. function Scalar() {
  7954. }
  7955. /**
  7956. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7957. */
  7958. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7959. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7960. var num = a - b;
  7961. return -epsilon <= num && num <= epsilon;
  7962. };
  7963. /**
  7964. * Returns a string : the upper case translation of the number i to hexadecimal.
  7965. */
  7966. Scalar.ToHex = function (i) {
  7967. var str = i.toString(16);
  7968. if (i <= 15) {
  7969. return ("0" + str).toUpperCase();
  7970. }
  7971. return str.toUpperCase();
  7972. };
  7973. /**
  7974. * Returns -1 if value is negative and +1 is value is positive.
  7975. * Returns the value itself if it's equal to zero.
  7976. */
  7977. Scalar.Sign = function (value) {
  7978. value = +value; // convert to a number
  7979. if (value === 0 || isNaN(value))
  7980. return value;
  7981. return value > 0 ? 1 : -1;
  7982. };
  7983. /**
  7984. * Returns the value itself if it's between min and max.
  7985. * Returns min if the value is lower than min.
  7986. * Returns max if the value is greater than max.
  7987. */
  7988. Scalar.Clamp = function (value, min, max) {
  7989. if (min === void 0) { min = 0; }
  7990. if (max === void 0) { max = 1; }
  7991. return Math.min(max, Math.max(min, value));
  7992. };
  7993. /**
  7994. * Returns the log2 of value.
  7995. */
  7996. Scalar.Log2 = function (value) {
  7997. return Math.log(value) * Math.LOG2E;
  7998. };
  7999. /**
  8000. * Loops the value, so that it is never larger than length and never smaller than 0.
  8001. *
  8002. * This is similar to the modulo operator but it works with floating point numbers.
  8003. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  8004. * With t = 5 and length = 2.5, the result would be 0.0.
  8005. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  8006. */
  8007. Scalar.Repeat = function (value, length) {
  8008. return value - Math.floor(value / length) * length;
  8009. };
  8010. /**
  8011. * Normalize the value between 0.0 and 1.0 using min and max values
  8012. */
  8013. Scalar.Normalize = function (value, min, max) {
  8014. return (value - min) / (max - min);
  8015. };
  8016. /**
  8017. * Denormalize the value from 0.0 and 1.0 using min and max values
  8018. */
  8019. Scalar.Denormalize = function (normalized, min, max) {
  8020. return (normalized * (max - min) + min);
  8021. };
  8022. /**
  8023. * Calculates the shortest difference between two given angles given in degrees.
  8024. */
  8025. Scalar.DeltaAngle = function (current, target) {
  8026. var num = Scalar.Repeat(target - current, 360.0);
  8027. if (num > 180.0) {
  8028. num -= 360.0;
  8029. }
  8030. return num;
  8031. };
  8032. /**
  8033. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  8034. *
  8035. * The returned value will move back and forth between 0 and length
  8036. */
  8037. Scalar.PingPong = function (tx, length) {
  8038. var t = Scalar.Repeat(tx, length * 2.0);
  8039. return length - Math.abs(t - length);
  8040. };
  8041. /**
  8042. * Interpolates between min and max with smoothing at the limits.
  8043. *
  8044. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  8045. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  8046. */
  8047. Scalar.SmoothStep = function (from, to, tx) {
  8048. var t = Scalar.Clamp(tx);
  8049. t = -2.0 * t * t * t + 3.0 * t * t;
  8050. return to * t + from * (1.0 - t);
  8051. };
  8052. /**
  8053. * Moves a value current towards target.
  8054. *
  8055. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  8056. * Negative values of maxDelta pushes the value away from target.
  8057. */
  8058. Scalar.MoveTowards = function (current, target, maxDelta) {
  8059. var result = 0;
  8060. if (Math.abs(target - current) <= maxDelta) {
  8061. result = target;
  8062. }
  8063. else {
  8064. result = current + Scalar.Sign(target - current) * maxDelta;
  8065. }
  8066. return result;
  8067. };
  8068. /**
  8069. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8070. *
  8071. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  8072. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  8073. */
  8074. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  8075. var num = Scalar.DeltaAngle(current, target);
  8076. var result = 0;
  8077. if (-maxDelta < num && num < maxDelta) {
  8078. result = target;
  8079. }
  8080. else {
  8081. target = current + num;
  8082. result = Scalar.MoveTowards(current, target, maxDelta);
  8083. }
  8084. return result;
  8085. };
  8086. /**
  8087. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  8088. */
  8089. Scalar.Lerp = function (start, end, amount) {
  8090. return start + ((end - start) * amount);
  8091. };
  8092. /**
  8093. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8094. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  8095. */
  8096. Scalar.LerpAngle = function (start, end, amount) {
  8097. var num = Scalar.Repeat(end - start, 360.0);
  8098. if (num > 180.0) {
  8099. num -= 360.0;
  8100. }
  8101. return start + num * Scalar.Clamp(amount);
  8102. };
  8103. /**
  8104. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  8105. */
  8106. Scalar.InverseLerp = function (a, b, value) {
  8107. var result = 0;
  8108. if (a != b) {
  8109. result = Scalar.Clamp((value - a) / (b - a));
  8110. }
  8111. else {
  8112. result = 0.0;
  8113. }
  8114. return result;
  8115. };
  8116. /**
  8117. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  8118. */
  8119. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  8120. var squared = amount * amount;
  8121. var cubed = amount * squared;
  8122. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  8123. var part2 = (-2.0 * cubed) + (3.0 * squared);
  8124. var part3 = (cubed - (2.0 * squared)) + amount;
  8125. var part4 = cubed - squared;
  8126. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  8127. };
  8128. /**
  8129. * Returns a random float number between and min and max values
  8130. */
  8131. Scalar.RandomRange = function (min, max) {
  8132. if (min === max)
  8133. return min;
  8134. return ((Math.random() * (max - min)) + min);
  8135. };
  8136. /**
  8137. * This function returns percentage of a number in a given range.
  8138. *
  8139. * RangeToPercent(40,20,60) will return 0.5 (50%)
  8140. * RangeToPercent(34,0,100) will return 0.34 (34%)
  8141. */
  8142. Scalar.RangeToPercent = function (number, min, max) {
  8143. return ((number - min) / (max - min));
  8144. };
  8145. /**
  8146. * This function returns number that corresponds to the percentage in a given range.
  8147. *
  8148. * PercentToRange(0.34,0,100) will return 34.
  8149. */
  8150. Scalar.PercentToRange = function (percent, min, max) {
  8151. return ((max - min) * percent + min);
  8152. };
  8153. /**
  8154. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  8155. * @param angle The angle to normalize in radian.
  8156. * @return The converted angle.
  8157. */
  8158. Scalar.NormalizeRadians = function (angle) {
  8159. // More precise but slower version kept for reference.
  8160. // angle = angle % Tools.TwoPi;
  8161. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  8162. //if (angle > Math.PI) {
  8163. // angle -= Tools.TwoPi;
  8164. //}
  8165. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  8166. return angle;
  8167. };
  8168. /**
  8169. * Two pi constants convenient for computation.
  8170. */
  8171. Scalar.TwoPi = Math.PI * 2;
  8172. return Scalar;
  8173. }());
  8174. BABYLON.Scalar = Scalar;
  8175. })(BABYLON || (BABYLON = {}));
  8176. //# sourceMappingURL=babylon.math.scalar.js.map
  8177. //# sourceMappingURL=babylon.mixins.js.map
  8178. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  8179. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  8180. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  8181. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  8182. //# sourceMappingURL=babylon.webgl2.js.map
  8183. var BABYLON;
  8184. (function (BABYLON) {
  8185. var __decoratorInitialStore = {};
  8186. var __mergedStore = {};
  8187. var _copySource = function (creationFunction, source, instanciate) {
  8188. var destination = creationFunction();
  8189. // Tags
  8190. if (BABYLON.Tags) {
  8191. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8192. }
  8193. var classStore = getMergedStore(destination);
  8194. // Properties
  8195. for (var property in classStore) {
  8196. var propertyDescriptor = classStore[property];
  8197. var sourceProperty = source[property];
  8198. var propertyType = propertyDescriptor.type;
  8199. if (sourceProperty !== undefined && sourceProperty !== null) {
  8200. switch (propertyType) {
  8201. case 0: // Value
  8202. case 6: // Mesh reference
  8203. case 11: // Camera reference
  8204. destination[property] = sourceProperty;
  8205. break;
  8206. case 1: // Texture
  8207. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  8208. break;
  8209. case 2: // Color3
  8210. case 3: // FresnelParameters
  8211. case 4: // Vector2
  8212. case 5: // Vector3
  8213. case 7: // Color Curves
  8214. case 10: // Quaternion
  8215. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  8216. break;
  8217. }
  8218. }
  8219. }
  8220. return destination;
  8221. };
  8222. function getDirectStore(target) {
  8223. var classKey = target.getClassName();
  8224. if (!__decoratorInitialStore[classKey]) {
  8225. __decoratorInitialStore[classKey] = {};
  8226. }
  8227. return __decoratorInitialStore[classKey];
  8228. }
  8229. /**
  8230. * Return the list of properties flagged as serializable
  8231. * @param target: host object
  8232. */
  8233. function getMergedStore(target) {
  8234. var classKey = target.getClassName();
  8235. if (__mergedStore[classKey]) {
  8236. return __mergedStore[classKey];
  8237. }
  8238. __mergedStore[classKey] = {};
  8239. var store = __mergedStore[classKey];
  8240. var currentTarget = target;
  8241. var currentKey = classKey;
  8242. while (currentKey) {
  8243. var initialStore = __decoratorInitialStore[currentKey];
  8244. for (var property in initialStore) {
  8245. store[property] = initialStore[property];
  8246. }
  8247. var parent_1 = void 0;
  8248. var done = false;
  8249. do {
  8250. parent_1 = Object.getPrototypeOf(currentTarget);
  8251. if (!parent_1.getClassName) {
  8252. done = true;
  8253. break;
  8254. }
  8255. if (parent_1.getClassName() !== currentKey) {
  8256. break;
  8257. }
  8258. currentTarget = parent_1;
  8259. } while (parent_1);
  8260. if (done) {
  8261. break;
  8262. }
  8263. currentKey = parent_1.getClassName();
  8264. currentTarget = parent_1;
  8265. }
  8266. return store;
  8267. }
  8268. function generateSerializableMember(type, sourceName) {
  8269. return function (target, propertyKey) {
  8270. var classStore = getDirectStore(target);
  8271. if (!classStore[propertyKey]) {
  8272. classStore[propertyKey] = { type: type, sourceName: sourceName };
  8273. }
  8274. };
  8275. }
  8276. function generateExpandMember(setCallback, targetKey) {
  8277. if (targetKey === void 0) { targetKey = null; }
  8278. return function (target, propertyKey) {
  8279. var key = targetKey || ("_" + propertyKey);
  8280. Object.defineProperty(target, propertyKey, {
  8281. get: function () {
  8282. return this[key];
  8283. },
  8284. set: function (value) {
  8285. if (this[key] === value) {
  8286. return;
  8287. }
  8288. this[key] = value;
  8289. target[setCallback].apply(this);
  8290. },
  8291. enumerable: true,
  8292. configurable: true
  8293. });
  8294. };
  8295. }
  8296. function expandToProperty(callback, targetKey) {
  8297. if (targetKey === void 0) { targetKey = null; }
  8298. return generateExpandMember(callback, targetKey);
  8299. }
  8300. BABYLON.expandToProperty = expandToProperty;
  8301. function serialize(sourceName) {
  8302. return generateSerializableMember(0, sourceName); // value member
  8303. }
  8304. BABYLON.serialize = serialize;
  8305. function serializeAsTexture(sourceName) {
  8306. return generateSerializableMember(1, sourceName); // texture member
  8307. }
  8308. BABYLON.serializeAsTexture = serializeAsTexture;
  8309. function serializeAsColor3(sourceName) {
  8310. return generateSerializableMember(2, sourceName); // color3 member
  8311. }
  8312. BABYLON.serializeAsColor3 = serializeAsColor3;
  8313. function serializeAsFresnelParameters(sourceName) {
  8314. return generateSerializableMember(3, sourceName); // fresnel parameters member
  8315. }
  8316. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  8317. function serializeAsVector2(sourceName) {
  8318. return generateSerializableMember(4, sourceName); // vector2 member
  8319. }
  8320. BABYLON.serializeAsVector2 = serializeAsVector2;
  8321. function serializeAsVector3(sourceName) {
  8322. return generateSerializableMember(5, sourceName); // vector3 member
  8323. }
  8324. BABYLON.serializeAsVector3 = serializeAsVector3;
  8325. function serializeAsMeshReference(sourceName) {
  8326. return generateSerializableMember(6, sourceName); // mesh reference member
  8327. }
  8328. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  8329. function serializeAsColorCurves(sourceName) {
  8330. return generateSerializableMember(7, sourceName); // color curves
  8331. }
  8332. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  8333. function serializeAsColor4(sourceName) {
  8334. return generateSerializableMember(8, sourceName); // color 4
  8335. }
  8336. BABYLON.serializeAsColor4 = serializeAsColor4;
  8337. function serializeAsImageProcessingConfiguration(sourceName) {
  8338. return generateSerializableMember(9, sourceName); // image processing
  8339. }
  8340. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  8341. function serializeAsQuaternion(sourceName) {
  8342. return generateSerializableMember(10, sourceName); // quaternion member
  8343. }
  8344. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  8345. /**
  8346. * Decorator used to define property that can be serialized as reference to a camera
  8347. * @param sourceName defines the name of the property to decorate
  8348. */
  8349. function serializeAsCameraReference(sourceName) {
  8350. return generateSerializableMember(11, sourceName); // camera reference member
  8351. }
  8352. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  8353. var SerializationHelper = /** @class */ (function () {
  8354. function SerializationHelper() {
  8355. }
  8356. SerializationHelper.Serialize = function (entity, serializationObject) {
  8357. if (!serializationObject) {
  8358. serializationObject = {};
  8359. }
  8360. // Tags
  8361. if (BABYLON.Tags) {
  8362. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  8363. }
  8364. var serializedProperties = getMergedStore(entity);
  8365. // Properties
  8366. for (var property in serializedProperties) {
  8367. var propertyDescriptor = serializedProperties[property];
  8368. var targetPropertyName = propertyDescriptor.sourceName || property;
  8369. var propertyType = propertyDescriptor.type;
  8370. var sourceProperty = entity[property];
  8371. if (sourceProperty !== undefined && sourceProperty !== null) {
  8372. switch (propertyType) {
  8373. case 0: // Value
  8374. serializationObject[targetPropertyName] = sourceProperty;
  8375. break;
  8376. case 1: // Texture
  8377. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8378. break;
  8379. case 2: // Color3
  8380. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8381. break;
  8382. case 3: // FresnelParameters
  8383. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8384. break;
  8385. case 4: // Vector2
  8386. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8387. break;
  8388. case 5: // Vector3
  8389. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8390. break;
  8391. case 6: // Mesh reference
  8392. serializationObject[targetPropertyName] = sourceProperty.id;
  8393. break;
  8394. case 7: // Color Curves
  8395. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8396. break;
  8397. case 8: // Color 4
  8398. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8399. break;
  8400. case 9: // Image Processing
  8401. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8402. break;
  8403. case 10: // Quaternion
  8404. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8405. break;
  8406. case 11: // Camera reference
  8407. serializationObject[targetPropertyName] = sourceProperty.id;
  8408. break;
  8409. }
  8410. }
  8411. }
  8412. return serializationObject;
  8413. };
  8414. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8415. if (rootUrl === void 0) { rootUrl = null; }
  8416. var destination = creationFunction();
  8417. if (!rootUrl) {
  8418. rootUrl = "";
  8419. }
  8420. // Tags
  8421. if (BABYLON.Tags) {
  8422. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8423. }
  8424. var classStore = getMergedStore(destination);
  8425. // Properties
  8426. for (var property in classStore) {
  8427. var propertyDescriptor = classStore[property];
  8428. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8429. var propertyType = propertyDescriptor.type;
  8430. if (sourceProperty !== undefined && sourceProperty !== null) {
  8431. var dest = destination;
  8432. switch (propertyType) {
  8433. case 0: // Value
  8434. dest[property] = sourceProperty;
  8435. break;
  8436. case 1: // Texture
  8437. if (scene) {
  8438. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8439. }
  8440. break;
  8441. case 2: // Color3
  8442. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8443. break;
  8444. case 3: // FresnelParameters
  8445. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8446. break;
  8447. case 4: // Vector2
  8448. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8449. break;
  8450. case 5: // Vector3
  8451. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8452. break;
  8453. case 6: // Mesh reference
  8454. if (scene) {
  8455. dest[property] = scene.getLastMeshByID(sourceProperty);
  8456. }
  8457. break;
  8458. case 7: // Color Curves
  8459. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8460. break;
  8461. case 8: // Color 4
  8462. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8463. break;
  8464. case 9: // Image Processing
  8465. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8466. break;
  8467. case 10: // Quaternion
  8468. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8469. break;
  8470. case 11: // Camera reference
  8471. if (scene) {
  8472. dest[property] = scene.getCameraByID(sourceProperty);
  8473. }
  8474. break;
  8475. }
  8476. }
  8477. }
  8478. return destination;
  8479. };
  8480. SerializationHelper.Clone = function (creationFunction, source) {
  8481. return _copySource(creationFunction, source, false);
  8482. };
  8483. SerializationHelper.Instanciate = function (creationFunction, source) {
  8484. return _copySource(creationFunction, source, true);
  8485. };
  8486. return SerializationHelper;
  8487. }());
  8488. BABYLON.SerializationHelper = SerializationHelper;
  8489. })(BABYLON || (BABYLON = {}));
  8490. //# sourceMappingURL=babylon.decorators.js.map
  8491. var BABYLON;
  8492. (function (BABYLON) {
  8493. /**
  8494. * Wrapper class for promise with external resolve and reject.
  8495. */
  8496. var Deferred = /** @class */ (function () {
  8497. /**
  8498. * Constructor for this deferred object.
  8499. */
  8500. function Deferred() {
  8501. var _this = this;
  8502. this.promise = new Promise(function (resolve, reject) {
  8503. _this._resolve = resolve;
  8504. _this._reject = reject;
  8505. });
  8506. }
  8507. Object.defineProperty(Deferred.prototype, "resolve", {
  8508. /**
  8509. * The resolve method of the promise associated with this deferred object.
  8510. */
  8511. get: function () {
  8512. return this._resolve;
  8513. },
  8514. enumerable: true,
  8515. configurable: true
  8516. });
  8517. Object.defineProperty(Deferred.prototype, "reject", {
  8518. /**
  8519. * The reject method of the promise associated with this deferred object.
  8520. */
  8521. get: function () {
  8522. return this._reject;
  8523. },
  8524. enumerable: true,
  8525. configurable: true
  8526. });
  8527. return Deferred;
  8528. }());
  8529. BABYLON.Deferred = Deferred;
  8530. })(BABYLON || (BABYLON = {}));
  8531. //# sourceMappingURL=babylon.deferred.js.map
  8532. var BABYLON;
  8533. (function (BABYLON) {
  8534. /**
  8535. * A class serves as a medium between the observable and its observers
  8536. */
  8537. var EventState = /** @class */ (function () {
  8538. /**
  8539. * Create a new EventState
  8540. * @param mask defines the mask associated with this state
  8541. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8542. * @param target defines the original target of the state
  8543. * @param currentTarget defines the current target of the state
  8544. */
  8545. function EventState(mask, skipNextObservers, target, currentTarget) {
  8546. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8547. this.initalize(mask, skipNextObservers, target, currentTarget);
  8548. }
  8549. /**
  8550. * Initialize the current event state
  8551. * @param mask defines the mask associated with this state
  8552. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8553. * @param target defines the original target of the state
  8554. * @param currentTarget defines the current target of the state
  8555. * @returns the current event state
  8556. */
  8557. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8558. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8559. this.mask = mask;
  8560. this.skipNextObservers = skipNextObservers;
  8561. this.target = target;
  8562. this.currentTarget = currentTarget;
  8563. return this;
  8564. };
  8565. return EventState;
  8566. }());
  8567. BABYLON.EventState = EventState;
  8568. /**
  8569. * Represent an Observer registered to a given Observable object.
  8570. */
  8571. var Observer = /** @class */ (function () {
  8572. /**
  8573. * Creates a new observer
  8574. * @param callback defines the callback to call when the observer is notified
  8575. * @param mask defines the mask of the observer (used to filter notifications)
  8576. * @param scope defines the current scope used to restore the JS context
  8577. */
  8578. function Observer(
  8579. /**
  8580. * Defines the callback to call when the observer is notified
  8581. */
  8582. callback,
  8583. /**
  8584. * Defines the mask of the observer (used to filter notifications)
  8585. */
  8586. mask,
  8587. /**
  8588. * Defines the current scope used to restore the JS context
  8589. */
  8590. scope) {
  8591. if (scope === void 0) { scope = null; }
  8592. this.callback = callback;
  8593. this.mask = mask;
  8594. this.scope = scope;
  8595. /** @hidden */
  8596. this._willBeUnregistered = false;
  8597. /**
  8598. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8599. */
  8600. this.unregisterOnNextCall = false;
  8601. }
  8602. return Observer;
  8603. }());
  8604. BABYLON.Observer = Observer;
  8605. /**
  8606. * Represent a list of observers registered to multiple Observables object.
  8607. */
  8608. var MultiObserver = /** @class */ (function () {
  8609. function MultiObserver() {
  8610. }
  8611. /**
  8612. * Release associated resources
  8613. */
  8614. MultiObserver.prototype.dispose = function () {
  8615. if (this._observers && this._observables) {
  8616. for (var index = 0; index < this._observers.length; index++) {
  8617. this._observables[index].remove(this._observers[index]);
  8618. }
  8619. }
  8620. this._observers = null;
  8621. this._observables = null;
  8622. };
  8623. /**
  8624. * Raise a callback when one of the observable will notify
  8625. * @param observables defines a list of observables to watch
  8626. * @param callback defines the callback to call on notification
  8627. * @param mask defines the mask used to filter notifications
  8628. * @param scope defines the current scope used to restore the JS context
  8629. * @returns the new MultiObserver
  8630. */
  8631. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8632. if (mask === void 0) { mask = -1; }
  8633. if (scope === void 0) { scope = null; }
  8634. var result = new MultiObserver();
  8635. result._observers = new Array();
  8636. result._observables = observables;
  8637. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8638. var observable = observables_1[_i];
  8639. var observer = observable.add(callback, mask, false, scope);
  8640. if (observer) {
  8641. result._observers.push(observer);
  8642. }
  8643. }
  8644. return result;
  8645. };
  8646. return MultiObserver;
  8647. }());
  8648. BABYLON.MultiObserver = MultiObserver;
  8649. /**
  8650. * The Observable class is a simple implementation of the Observable pattern.
  8651. *
  8652. * 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.
  8653. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8654. * 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).
  8655. * 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.
  8656. */
  8657. var Observable = /** @class */ (function () {
  8658. /**
  8659. * Creates a new observable
  8660. * @param onObserverAdded defines a callback to call when a new observer is added
  8661. */
  8662. function Observable(onObserverAdded) {
  8663. this._observers = new Array();
  8664. this._eventState = new EventState(0);
  8665. if (onObserverAdded) {
  8666. this._onObserverAdded = onObserverAdded;
  8667. }
  8668. }
  8669. /**
  8670. * Create a new Observer with the specified callback
  8671. * @param callback the callback that will be executed for that Observer
  8672. * @param mask the mask used to filter observers
  8673. * @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.
  8674. * @param scope optional scope for the callback to be called from
  8675. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8676. * @returns the new observer created for the callback
  8677. */
  8678. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8679. if (mask === void 0) { mask = -1; }
  8680. if (insertFirst === void 0) { insertFirst = false; }
  8681. if (scope === void 0) { scope = null; }
  8682. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8683. if (!callback) {
  8684. return null;
  8685. }
  8686. var observer = new Observer(callback, mask, scope);
  8687. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8688. if (insertFirst) {
  8689. this._observers.unshift(observer);
  8690. }
  8691. else {
  8692. this._observers.push(observer);
  8693. }
  8694. if (this._onObserverAdded) {
  8695. this._onObserverAdded(observer);
  8696. }
  8697. return observer;
  8698. };
  8699. /**
  8700. * Create a new Observer with the specified callback and unregisters after the next notification
  8701. * @param callback the callback that will be executed for that Observer
  8702. * @returns the new observer created for the callback
  8703. */
  8704. Observable.prototype.addOnce = function (callback) {
  8705. return this.add(callback, undefined, undefined, undefined, true);
  8706. };
  8707. /**
  8708. * Remove an Observer from the Observable object
  8709. * @param observer the instance of the Observer to remove
  8710. * @returns false if it doesn't belong to this Observable
  8711. */
  8712. Observable.prototype.remove = function (observer) {
  8713. if (!observer) {
  8714. return false;
  8715. }
  8716. var index = this._observers.indexOf(observer);
  8717. if (index !== -1) {
  8718. this._deferUnregister(observer);
  8719. return true;
  8720. }
  8721. return false;
  8722. };
  8723. /**
  8724. * Remove a callback from the Observable object
  8725. * @param callback the callback to remove
  8726. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8727. * @returns false if it doesn't belong to this Observable
  8728. */
  8729. Observable.prototype.removeCallback = function (callback, scope) {
  8730. for (var index = 0; index < this._observers.length; index++) {
  8731. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8732. this._deferUnregister(this._observers[index]);
  8733. return true;
  8734. }
  8735. }
  8736. return false;
  8737. };
  8738. Observable.prototype._deferUnregister = function (observer) {
  8739. var _this = this;
  8740. observer.unregisterOnNextCall = false;
  8741. observer._willBeUnregistered = true;
  8742. BABYLON.Tools.SetImmediate(function () {
  8743. _this._remove(observer);
  8744. });
  8745. };
  8746. // This should only be called when not iterating over _observers to avoid callback skipping.
  8747. // Removes an observer from the _observer Array.
  8748. Observable.prototype._remove = function (observer) {
  8749. if (!observer) {
  8750. return false;
  8751. }
  8752. var index = this._observers.indexOf(observer);
  8753. if (index !== -1) {
  8754. this._observers.splice(index, 1);
  8755. return true;
  8756. }
  8757. return false;
  8758. };
  8759. /**
  8760. * Notify all Observers by calling their respective callback with the given data
  8761. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8762. * @param eventData defines the data to send to all observers
  8763. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8764. * @param target defines the original target of the state
  8765. * @param currentTarget defines the current target of the state
  8766. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8767. */
  8768. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8769. if (mask === void 0) { mask = -1; }
  8770. if (!this._observers.length) {
  8771. return true;
  8772. }
  8773. var state = this._eventState;
  8774. state.mask = mask;
  8775. state.target = target;
  8776. state.currentTarget = currentTarget;
  8777. state.skipNextObservers = false;
  8778. state.lastReturnValue = eventData;
  8779. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8780. var obs = _a[_i];
  8781. if (obs._willBeUnregistered) {
  8782. continue;
  8783. }
  8784. if (obs.mask & mask) {
  8785. if (obs.scope) {
  8786. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8787. }
  8788. else {
  8789. state.lastReturnValue = obs.callback(eventData, state);
  8790. }
  8791. if (obs.unregisterOnNextCall) {
  8792. this._deferUnregister(obs);
  8793. }
  8794. }
  8795. if (state.skipNextObservers) {
  8796. return false;
  8797. }
  8798. }
  8799. return true;
  8800. };
  8801. /**
  8802. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8803. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8804. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8805. * and it is crucial that all callbacks will be executed.
  8806. * The order of the callbacks is kept, callbacks are not executed parallel.
  8807. *
  8808. * @param eventData The data to be sent to each callback
  8809. * @param mask is used to filter observers defaults to -1
  8810. * @param target defines the callback target (see EventState)
  8811. * @param currentTarget defines he current object in the bubbling phase
  8812. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8813. */
  8814. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8815. var _this = this;
  8816. if (mask === void 0) { mask = -1; }
  8817. // create an empty promise
  8818. var p = Promise.resolve(eventData);
  8819. // no observers? return this promise.
  8820. if (!this._observers.length) {
  8821. return p;
  8822. }
  8823. var state = this._eventState;
  8824. state.mask = mask;
  8825. state.target = target;
  8826. state.currentTarget = currentTarget;
  8827. state.skipNextObservers = false;
  8828. // execute one callback after another (not using Promise.all, the order is important)
  8829. this._observers.forEach(function (obs) {
  8830. if (state.skipNextObservers) {
  8831. return;
  8832. }
  8833. if (obs._willBeUnregistered) {
  8834. return;
  8835. }
  8836. if (obs.mask & mask) {
  8837. if (obs.scope) {
  8838. p = p.then(function (lastReturnedValue) {
  8839. state.lastReturnValue = lastReturnedValue;
  8840. return obs.callback.apply(obs.scope, [eventData, state]);
  8841. });
  8842. }
  8843. else {
  8844. p = p.then(function (lastReturnedValue) {
  8845. state.lastReturnValue = lastReturnedValue;
  8846. return obs.callback(eventData, state);
  8847. });
  8848. }
  8849. if (obs.unregisterOnNextCall) {
  8850. _this._deferUnregister(obs);
  8851. }
  8852. }
  8853. });
  8854. // return the eventData
  8855. return p.then(function () { return eventData; });
  8856. };
  8857. /**
  8858. * Notify a specific observer
  8859. * @param observer defines the observer to notify
  8860. * @param eventData defines the data to be sent to each callback
  8861. * @param mask is used to filter observers defaults to -1
  8862. */
  8863. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8864. if (mask === void 0) { mask = -1; }
  8865. var state = this._eventState;
  8866. state.mask = mask;
  8867. state.skipNextObservers = false;
  8868. observer.callback(eventData, state);
  8869. };
  8870. /**
  8871. * Gets a boolean indicating if the observable has at least one observer
  8872. * @returns true is the Observable has at least one Observer registered
  8873. */
  8874. Observable.prototype.hasObservers = function () {
  8875. return this._observers.length > 0;
  8876. };
  8877. /**
  8878. * Clear the list of observers
  8879. */
  8880. Observable.prototype.clear = function () {
  8881. this._observers = new Array();
  8882. this._onObserverAdded = null;
  8883. };
  8884. /**
  8885. * Clone the current observable
  8886. * @returns a new observable
  8887. */
  8888. Observable.prototype.clone = function () {
  8889. var result = new Observable();
  8890. result._observers = this._observers.slice(0);
  8891. return result;
  8892. };
  8893. /**
  8894. * Does this observable handles observer registered with a given mask
  8895. * @param mask defines the mask to be tested
  8896. * @return whether or not one observer registered with the given mask is handeled
  8897. **/
  8898. Observable.prototype.hasSpecificMask = function (mask) {
  8899. if (mask === void 0) { mask = -1; }
  8900. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8901. var obs = _a[_i];
  8902. if (obs.mask & mask || obs.mask === mask) {
  8903. return true;
  8904. }
  8905. }
  8906. return false;
  8907. };
  8908. return Observable;
  8909. }());
  8910. BABYLON.Observable = Observable;
  8911. })(BABYLON || (BABYLON = {}));
  8912. //# sourceMappingURL=babylon.observable.js.map
  8913. var BABYLON;
  8914. (function (BABYLON) {
  8915. /**
  8916. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8917. */
  8918. var SmartArray = /** @class */ (function () {
  8919. /**
  8920. * Instantiates a Smart Array.
  8921. * @param capacity defines the default capacity of the array.
  8922. */
  8923. function SmartArray(capacity) {
  8924. /**
  8925. * The active length of the array.
  8926. */
  8927. this.length = 0;
  8928. this.data = new Array(capacity);
  8929. this._id = SmartArray._GlobalId++;
  8930. }
  8931. /**
  8932. * Pushes a value at the end of the active data.
  8933. * @param value defines the object to push in the array.
  8934. */
  8935. SmartArray.prototype.push = function (value) {
  8936. this.data[this.length++] = value;
  8937. if (this.length > this.data.length) {
  8938. this.data.length *= 2;
  8939. }
  8940. };
  8941. /**
  8942. * Iterates over the active data and apply the lambda to them.
  8943. * @param func defines the action to apply on each value.
  8944. */
  8945. SmartArray.prototype.forEach = function (func) {
  8946. for (var index = 0; index < this.length; index++) {
  8947. func(this.data[index]);
  8948. }
  8949. };
  8950. /**
  8951. * Sorts the full sets of data.
  8952. * @param compareFn defines the comparison function to apply.
  8953. */
  8954. SmartArray.prototype.sort = function (compareFn) {
  8955. this.data.sort(compareFn);
  8956. };
  8957. /**
  8958. * Resets the active data to an empty array.
  8959. */
  8960. SmartArray.prototype.reset = function () {
  8961. this.length = 0;
  8962. };
  8963. /**
  8964. * Releases all the data from the array as well as the array.
  8965. */
  8966. SmartArray.prototype.dispose = function () {
  8967. this.reset();
  8968. if (this.data) {
  8969. this.data.length = 0;
  8970. this.data = [];
  8971. }
  8972. };
  8973. /**
  8974. * Concats the active data with a given array.
  8975. * @param array defines the data to concatenate with.
  8976. */
  8977. SmartArray.prototype.concat = function (array) {
  8978. if (array.length === 0) {
  8979. return;
  8980. }
  8981. if (this.length + array.length > this.data.length) {
  8982. this.data.length = (this.length + array.length) * 2;
  8983. }
  8984. for (var index = 0; index < array.length; index++) {
  8985. this.data[this.length++] = (array.data || array)[index];
  8986. }
  8987. };
  8988. /**
  8989. * Returns the position of a value in the active data.
  8990. * @param value defines the value to find the index for
  8991. * @returns the index if found in the active data otherwise -1
  8992. */
  8993. SmartArray.prototype.indexOf = function (value) {
  8994. var position = this.data.indexOf(value);
  8995. if (position >= this.length) {
  8996. return -1;
  8997. }
  8998. return position;
  8999. };
  9000. /**
  9001. * Returns whether an element is part of the active data.
  9002. * @param value defines the value to look for
  9003. * @returns true if found in the active data otherwise false
  9004. */
  9005. SmartArray.prototype.contains = function (value) {
  9006. return this.indexOf(value) !== -1;
  9007. };
  9008. // Statics
  9009. SmartArray._GlobalId = 0;
  9010. return SmartArray;
  9011. }());
  9012. BABYLON.SmartArray = SmartArray;
  9013. /**
  9014. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  9015. * The data in this array can only be present once
  9016. */
  9017. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  9018. __extends(SmartArrayNoDuplicate, _super);
  9019. function SmartArrayNoDuplicate() {
  9020. var _this = _super !== null && _super.apply(this, arguments) || this;
  9021. _this._duplicateId = 0;
  9022. return _this;
  9023. }
  9024. /**
  9025. * Pushes a value at the end of the active data.
  9026. * THIS DOES NOT PREVENT DUPPLICATE DATA
  9027. * @param value defines the object to push in the array.
  9028. */
  9029. SmartArrayNoDuplicate.prototype.push = function (value) {
  9030. _super.prototype.push.call(this, value);
  9031. if (!value.__smartArrayFlags) {
  9032. value.__smartArrayFlags = {};
  9033. }
  9034. value.__smartArrayFlags[this._id] = this._duplicateId;
  9035. };
  9036. /**
  9037. * Pushes a value at the end of the active data.
  9038. * If the data is already present, it won t be added again
  9039. * @param value defines the object to push in the array.
  9040. * @returns true if added false if it was already present
  9041. */
  9042. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  9043. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  9044. return false;
  9045. }
  9046. this.push(value);
  9047. return true;
  9048. };
  9049. /**
  9050. * Resets the active data to an empty array.
  9051. */
  9052. SmartArrayNoDuplicate.prototype.reset = function () {
  9053. _super.prototype.reset.call(this);
  9054. this._duplicateId++;
  9055. };
  9056. /**
  9057. * Concats the active data with a given array.
  9058. * This ensures no dupplicate will be present in the result.
  9059. * @param array defines the data to concatenate with.
  9060. */
  9061. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  9062. if (array.length === 0) {
  9063. return;
  9064. }
  9065. if (this.length + array.length > this.data.length) {
  9066. this.data.length = (this.length + array.length) * 2;
  9067. }
  9068. for (var index = 0; index < array.length; index++) {
  9069. var item = (array.data || array)[index];
  9070. this.pushNoDuplicate(item);
  9071. }
  9072. };
  9073. return SmartArrayNoDuplicate;
  9074. }(SmartArray));
  9075. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  9076. })(BABYLON || (BABYLON = {}));
  9077. //# sourceMappingURL=babylon.smartArray.js.map
  9078. var BABYLON;
  9079. (function (BABYLON) {
  9080. /** Class used to store color4 gradient */
  9081. var ColorGradient = /** @class */ (function () {
  9082. function ColorGradient() {
  9083. }
  9084. /**
  9085. * Will get a color picked randomly between color1 and color2.
  9086. * If color2 is undefined then color1 will be used
  9087. * @param result defines the target Color4 to store the result in
  9088. */
  9089. ColorGradient.prototype.getColorToRef = function (result) {
  9090. if (!this.color2) {
  9091. result.copyFrom(this.color1);
  9092. return;
  9093. }
  9094. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  9095. };
  9096. return ColorGradient;
  9097. }());
  9098. BABYLON.ColorGradient = ColorGradient;
  9099. /** Class used to store color 3 gradient */
  9100. var Color3Gradient = /** @class */ (function () {
  9101. function Color3Gradient() {
  9102. }
  9103. return Color3Gradient;
  9104. }());
  9105. BABYLON.Color3Gradient = Color3Gradient;
  9106. /** Class used to store factor gradient */
  9107. var FactorGradient = /** @class */ (function () {
  9108. function FactorGradient() {
  9109. }
  9110. /**
  9111. * Will get a number picked randomly between factor1 and factor2.
  9112. * If factor2 is undefined then factor1 will be used
  9113. * @returns the picked number
  9114. */
  9115. FactorGradient.prototype.getFactor = function () {
  9116. if (this.factor2 === undefined) {
  9117. return this.factor1;
  9118. }
  9119. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  9120. };
  9121. return FactorGradient;
  9122. }());
  9123. BABYLON.FactorGradient = FactorGradient;
  9124. /**
  9125. * Application error to support additional information when loading a file
  9126. */
  9127. var LoadFileError = /** @class */ (function (_super) {
  9128. __extends(LoadFileError, _super);
  9129. /**
  9130. * Creates a new LoadFileError
  9131. * @param message defines the message of the error
  9132. * @param request defines the optional XHR request
  9133. */
  9134. function LoadFileError(message, request) {
  9135. var _this = _super.call(this, message) || this;
  9136. _this.request = request;
  9137. _this.name = "LoadFileError";
  9138. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  9139. return _this;
  9140. }
  9141. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  9142. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  9143. // Polyfill for Object.setPrototypeOf if necessary.
  9144. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  9145. return LoadFileError;
  9146. }(Error));
  9147. BABYLON.LoadFileError = LoadFileError;
  9148. /**
  9149. * Class used to define a retry strategy when error happens while loading assets
  9150. */
  9151. var RetryStrategy = /** @class */ (function () {
  9152. function RetryStrategy() {
  9153. }
  9154. /**
  9155. * Function used to defines an exponential back off strategy
  9156. * @param maxRetries defines the maximum number of retries (3 by default)
  9157. * @param baseInterval defines the interval between retries
  9158. * @returns the strategy function to use
  9159. */
  9160. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  9161. if (maxRetries === void 0) { maxRetries = 3; }
  9162. if (baseInterval === void 0) { baseInterval = 500; }
  9163. return function (url, request, retryIndex) {
  9164. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  9165. return -1;
  9166. }
  9167. return Math.pow(2, retryIndex) * baseInterval;
  9168. };
  9169. };
  9170. return RetryStrategy;
  9171. }());
  9172. BABYLON.RetryStrategy = RetryStrategy;
  9173. // Screenshots
  9174. var screenshotCanvas;
  9175. var cloneValue = function (source, destinationObject) {
  9176. if (!source)
  9177. return null;
  9178. if (source instanceof BABYLON.Mesh) {
  9179. return null;
  9180. }
  9181. if (source instanceof BABYLON.SubMesh) {
  9182. return source.clone(destinationObject);
  9183. }
  9184. else if (source.clone) {
  9185. return source.clone();
  9186. }
  9187. return null;
  9188. };
  9189. /**
  9190. * Class containing a set of static utilities functions
  9191. */
  9192. var Tools = /** @class */ (function () {
  9193. function Tools() {
  9194. }
  9195. /**
  9196. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  9197. * @param u defines the coordinate on X axis
  9198. * @param v defines the coordinate on Y axis
  9199. * @param width defines the width of the source data
  9200. * @param height defines the height of the source data
  9201. * @param pixels defines the source byte array
  9202. * @param color defines the output color
  9203. */
  9204. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  9205. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  9206. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  9207. var position = (wrappedU + wrappedV * width) * 4;
  9208. color.r = pixels[position] / 255;
  9209. color.g = pixels[position + 1] / 255;
  9210. color.b = pixels[position + 2] / 255;
  9211. color.a = pixels[position + 3] / 255;
  9212. };
  9213. /**
  9214. * Interpolates between a and b via alpha
  9215. * @param a The lower value (returned when alpha = 0)
  9216. * @param b The upper value (returned when alpha = 1)
  9217. * @param alpha The interpolation-factor
  9218. * @return The mixed value
  9219. */
  9220. Tools.Mix = function (a, b, alpha) {
  9221. return a * (1 - alpha) + b * alpha;
  9222. };
  9223. /**
  9224. * Tries to instantiate a new object from a given class name
  9225. * @param className defines the class name to instantiate
  9226. * @returns the new object or null if the system was not able to do the instantiation
  9227. */
  9228. Tools.Instantiate = function (className) {
  9229. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  9230. return Tools.RegisteredExternalClasses[className];
  9231. }
  9232. var arr = className.split(".");
  9233. var fn = (window || this);
  9234. for (var i = 0, len = arr.length; i < len; i++) {
  9235. fn = fn[arr[i]];
  9236. }
  9237. if (typeof fn !== "function") {
  9238. return null;
  9239. }
  9240. return fn;
  9241. };
  9242. /**
  9243. * Provides a slice function that will work even on IE
  9244. * @param data defines the array to slice
  9245. * @param start defines the start of the data (optional)
  9246. * @param end defines the end of the data (optional)
  9247. * @returns the new sliced array
  9248. */
  9249. Tools.Slice = function (data, start, end) {
  9250. if (data.slice) {
  9251. return data.slice(start, end);
  9252. }
  9253. return Array.prototype.slice.call(data, start, end);
  9254. };
  9255. /**
  9256. * Polyfill for setImmediate
  9257. * @param action defines the action to execute after the current execution block
  9258. */
  9259. Tools.SetImmediate = function (action) {
  9260. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  9261. window.setImmediate(action);
  9262. }
  9263. else {
  9264. setTimeout(action, 1);
  9265. }
  9266. };
  9267. /**
  9268. * Function indicating if a number is an exponent of 2
  9269. * @param value defines the value to test
  9270. * @returns true if the value is an exponent of 2
  9271. */
  9272. Tools.IsExponentOfTwo = function (value) {
  9273. var count = 1;
  9274. do {
  9275. count *= 2;
  9276. } while (count < value);
  9277. return count === value;
  9278. };
  9279. /**
  9280. * Returns the nearest 32-bit single precision float representation of a Number
  9281. * @param value A Number. If the parameter is of a different type, it will get converted
  9282. * to a number or to NaN if it cannot be converted
  9283. * @returns number
  9284. */
  9285. Tools.FloatRound = function (value) {
  9286. if (Math.fround) {
  9287. return Math.fround(value);
  9288. }
  9289. return (Tools._tmpFloatArray[0] = value);
  9290. };
  9291. /**
  9292. * Find the next highest power of two.
  9293. * @param x Number to start search from.
  9294. * @return Next highest power of two.
  9295. */
  9296. Tools.CeilingPOT = function (x) {
  9297. x--;
  9298. x |= x >> 1;
  9299. x |= x >> 2;
  9300. x |= x >> 4;
  9301. x |= x >> 8;
  9302. x |= x >> 16;
  9303. x++;
  9304. return x;
  9305. };
  9306. /**
  9307. * Find the next lowest power of two.
  9308. * @param x Number to start search from.
  9309. * @return Next lowest power of two.
  9310. */
  9311. Tools.FloorPOT = function (x) {
  9312. x = x | (x >> 1);
  9313. x = x | (x >> 2);
  9314. x = x | (x >> 4);
  9315. x = x | (x >> 8);
  9316. x = x | (x >> 16);
  9317. return x - (x >> 1);
  9318. };
  9319. /**
  9320. * Find the nearest power of two.
  9321. * @param x Number to start search from.
  9322. * @return Next nearest power of two.
  9323. */
  9324. Tools.NearestPOT = function (x) {
  9325. var c = Tools.CeilingPOT(x);
  9326. var f = Tools.FloorPOT(x);
  9327. return (c - x) > (x - f) ? f : c;
  9328. };
  9329. /**
  9330. * Get the closest exponent of two
  9331. * @param value defines the value to approximate
  9332. * @param max defines the maximum value to return
  9333. * @param mode defines how to define the closest value
  9334. * @returns closest exponent of two of the given value
  9335. */
  9336. Tools.GetExponentOfTwo = function (value, max, mode) {
  9337. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  9338. var pot;
  9339. switch (mode) {
  9340. case BABYLON.Engine.SCALEMODE_FLOOR:
  9341. pot = Tools.FloorPOT(value);
  9342. break;
  9343. case BABYLON.Engine.SCALEMODE_NEAREST:
  9344. pot = Tools.NearestPOT(value);
  9345. break;
  9346. case BABYLON.Engine.SCALEMODE_CEILING:
  9347. default:
  9348. pot = Tools.CeilingPOT(value);
  9349. break;
  9350. }
  9351. return Math.min(pot, max);
  9352. };
  9353. /**
  9354. * Extracts the filename from a path
  9355. * @param path defines the path to use
  9356. * @returns the filename
  9357. */
  9358. Tools.GetFilename = function (path) {
  9359. var index = path.lastIndexOf("/");
  9360. if (index < 0)
  9361. return path;
  9362. return path.substring(index + 1);
  9363. };
  9364. /**
  9365. * Extracts the "folder" part of a path (everything before the filename).
  9366. * @param uri The URI to extract the info from
  9367. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  9368. * @returns The "folder" part of the path
  9369. */
  9370. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  9371. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  9372. var index = uri.lastIndexOf("/");
  9373. if (index < 0) {
  9374. if (returnUnchangedIfNoSlash) {
  9375. return uri;
  9376. }
  9377. return "";
  9378. }
  9379. return uri.substring(0, index + 1);
  9380. };
  9381. /**
  9382. * Extracts text content from a DOM element hierarchy
  9383. * @param element defines the root element
  9384. * @returns a string
  9385. */
  9386. Tools.GetDOMTextContent = function (element) {
  9387. var result = "";
  9388. var child = element.firstChild;
  9389. while (child) {
  9390. if (child.nodeType === 3) {
  9391. result += child.textContent;
  9392. }
  9393. child = child.nextSibling;
  9394. }
  9395. return result;
  9396. };
  9397. /**
  9398. * Convert an angle in radians to degrees
  9399. * @param angle defines the angle to convert
  9400. * @returns the angle in degrees
  9401. */
  9402. Tools.ToDegrees = function (angle) {
  9403. return angle * 180 / Math.PI;
  9404. };
  9405. /**
  9406. * Convert an angle in degrees to radians
  9407. * @param angle defines the angle to convert
  9408. * @returns the angle in radians
  9409. */
  9410. Tools.ToRadians = function (angle) {
  9411. return angle * Math.PI / 180;
  9412. };
  9413. /**
  9414. * Encode a buffer to a base64 string
  9415. * @param buffer defines the buffer to encode
  9416. * @returns the encoded string
  9417. */
  9418. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  9419. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  9420. var output = "";
  9421. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  9422. var i = 0;
  9423. var bytes = new Uint8Array(buffer);
  9424. while (i < bytes.length) {
  9425. chr1 = bytes[i++];
  9426. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  9427. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  9428. enc1 = chr1 >> 2;
  9429. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  9430. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  9431. enc4 = chr3 & 63;
  9432. if (isNaN(chr2)) {
  9433. enc3 = enc4 = 64;
  9434. }
  9435. else if (isNaN(chr3)) {
  9436. enc4 = 64;
  9437. }
  9438. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  9439. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  9440. }
  9441. return "data:image/png;base64," + output;
  9442. };
  9443. /**
  9444. * Extracts minimum and maximum values from a list of indexed positions
  9445. * @param positions defines the positions to use
  9446. * @param indices defines the indices to the positions
  9447. * @param indexStart defines the start index
  9448. * @param indexCount defines the end index
  9449. * @param bias defines bias value to add to the result
  9450. * @return minimum and maximum values
  9451. */
  9452. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  9453. if (bias === void 0) { bias = null; }
  9454. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9455. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9456. for (var index = indexStart; index < indexStart + indexCount; index++) {
  9457. var offset = indices[index] * 3;
  9458. var x = positions[offset];
  9459. var y = positions[offset + 1];
  9460. var z = positions[offset + 2];
  9461. minimum.minimizeInPlaceFromFloats(x, y, z);
  9462. maximum.maximizeInPlaceFromFloats(x, y, z);
  9463. }
  9464. if (bias) {
  9465. minimum.x -= minimum.x * bias.x + bias.y;
  9466. minimum.y -= minimum.y * bias.x + bias.y;
  9467. minimum.z -= minimum.z * bias.x + bias.y;
  9468. maximum.x += maximum.x * bias.x + bias.y;
  9469. maximum.y += maximum.y * bias.x + bias.y;
  9470. maximum.z += maximum.z * bias.x + bias.y;
  9471. }
  9472. return {
  9473. minimum: minimum,
  9474. maximum: maximum
  9475. };
  9476. };
  9477. /**
  9478. * Extracts minimum and maximum values from a list of positions
  9479. * @param positions defines the positions to use
  9480. * @param start defines the start index in the positions array
  9481. * @param count defines the number of positions to handle
  9482. * @param bias defines bias value to add to the result
  9483. * @param stride defines the stride size to use (distance between two positions in the positions array)
  9484. * @return minimum and maximum values
  9485. */
  9486. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  9487. if (bias === void 0) { bias = null; }
  9488. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9489. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9490. if (!stride) {
  9491. stride = 3;
  9492. }
  9493. for (var index = start, offset = start * stride; index < start + count; index++, offset += stride) {
  9494. var x = positions[offset];
  9495. var y = positions[offset + 1];
  9496. var z = positions[offset + 2];
  9497. minimum.minimizeInPlaceFromFloats(x, y, z);
  9498. maximum.maximizeInPlaceFromFloats(x, y, z);
  9499. }
  9500. if (bias) {
  9501. minimum.x -= minimum.x * bias.x + bias.y;
  9502. minimum.y -= minimum.y * bias.x + bias.y;
  9503. minimum.z -= minimum.z * bias.x + bias.y;
  9504. maximum.x += maximum.x * bias.x + bias.y;
  9505. maximum.y += maximum.y * bias.x + bias.y;
  9506. maximum.z += maximum.z * bias.x + bias.y;
  9507. }
  9508. return {
  9509. minimum: minimum,
  9510. maximum: maximum
  9511. };
  9512. };
  9513. /**
  9514. * Returns an array if obj is not an array
  9515. * @param obj defines the object to evaluate as an array
  9516. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  9517. * @returns either obj directly if obj is an array or a new array containing obj
  9518. */
  9519. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9520. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9521. return null;
  9522. return Array.isArray(obj) ? obj : [obj];
  9523. };
  9524. /**
  9525. * Gets the pointer prefix to use
  9526. * @returns "pointer" if touch is enabled. Else returns "mouse"
  9527. */
  9528. Tools.GetPointerPrefix = function () {
  9529. var eventPrefix = "pointer";
  9530. // Check if pointer events are supported
  9531. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9532. eventPrefix = "mouse";
  9533. }
  9534. return eventPrefix;
  9535. };
  9536. /**
  9537. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  9538. * @param func - the function to be called
  9539. * @param requester - the object that will request the next frame. Falls back to window.
  9540. * @returns frame number
  9541. */
  9542. Tools.QueueNewFrame = function (func, requester) {
  9543. if (!Tools.IsWindowObjectExist()) {
  9544. return setTimeout(func, 16);
  9545. }
  9546. if (!requester) {
  9547. requester = window;
  9548. }
  9549. if (requester.requestAnimationFrame) {
  9550. return requester.requestAnimationFrame(func);
  9551. }
  9552. else if (requester.msRequestAnimationFrame) {
  9553. return requester.msRequestAnimationFrame(func);
  9554. }
  9555. else if (requester.webkitRequestAnimationFrame) {
  9556. return requester.webkitRequestAnimationFrame(func);
  9557. }
  9558. else if (requester.mozRequestAnimationFrame) {
  9559. return requester.mozRequestAnimationFrame(func);
  9560. }
  9561. else if (requester.oRequestAnimationFrame) {
  9562. return requester.oRequestAnimationFrame(func);
  9563. }
  9564. else {
  9565. return window.setTimeout(func, 16);
  9566. }
  9567. };
  9568. /**
  9569. * Ask the browser to promote the current element to fullscreen rendering mode
  9570. * @param element defines the DOM element to promote
  9571. */
  9572. Tools.RequestFullscreen = function (element) {
  9573. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9574. if (!requestFunction)
  9575. return;
  9576. requestFunction.call(element);
  9577. };
  9578. /**
  9579. * Asks the browser to exit fullscreen mode
  9580. */
  9581. Tools.ExitFullscreen = function () {
  9582. if (document.exitFullscreen) {
  9583. document.exitFullscreen();
  9584. }
  9585. else if (document.mozCancelFullScreen) {
  9586. document.mozCancelFullScreen();
  9587. }
  9588. else if (document.webkitCancelFullScreen) {
  9589. document.webkitCancelFullScreen();
  9590. }
  9591. else if (document.msCancelFullScreen) {
  9592. document.msCancelFullScreen();
  9593. }
  9594. };
  9595. /**
  9596. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  9597. * @param url define the url we are trying
  9598. * @param element define the dom element where to configure the cors policy
  9599. */
  9600. Tools.SetCorsBehavior = function (url, element) {
  9601. if (url && url.indexOf("data:") === 0) {
  9602. return;
  9603. }
  9604. if (Tools.CorsBehavior) {
  9605. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9606. element.crossOrigin = Tools.CorsBehavior;
  9607. }
  9608. else {
  9609. var result = Tools.CorsBehavior(url);
  9610. if (result) {
  9611. element.crossOrigin = result;
  9612. }
  9613. }
  9614. }
  9615. };
  9616. // External files
  9617. /**
  9618. * Removes unwanted characters from an url
  9619. * @param url defines the url to clean
  9620. * @returns the cleaned url
  9621. */
  9622. Tools.CleanUrl = function (url) {
  9623. url = url.replace(/#/mg, "%23");
  9624. return url;
  9625. };
  9626. /**
  9627. * Loads an image as an HTMLImageElement.
  9628. * @param input url string, ArrayBuffer, or Blob to load
  9629. * @param onLoad callback called when the image successfully loads
  9630. * @param onError callback called when the image fails to load
  9631. * @param database database for caching
  9632. * @returns the HTMLImageElement of the loaded image
  9633. */
  9634. Tools.LoadImage = function (input, onLoad, onError, database) {
  9635. var url;
  9636. var usingObjectURL = false;
  9637. if (input instanceof ArrayBuffer) {
  9638. url = URL.createObjectURL(new Blob([input]));
  9639. usingObjectURL = true;
  9640. }
  9641. else if (input instanceof Blob) {
  9642. url = URL.createObjectURL(input);
  9643. usingObjectURL = true;
  9644. }
  9645. else {
  9646. url = Tools.CleanUrl(input);
  9647. url = Tools.PreprocessUrl(input);
  9648. }
  9649. var img = new Image();
  9650. Tools.SetCorsBehavior(url, img);
  9651. var loadHandler = function () {
  9652. if (usingObjectURL && img.src) {
  9653. URL.revokeObjectURL(img.src);
  9654. }
  9655. img.removeEventListener("load", loadHandler);
  9656. img.removeEventListener("error", errorHandler);
  9657. onLoad(img);
  9658. };
  9659. var errorHandler = function (err) {
  9660. if (usingObjectURL && img.src) {
  9661. URL.revokeObjectURL(img.src);
  9662. }
  9663. img.removeEventListener("load", loadHandler);
  9664. img.removeEventListener("error", errorHandler);
  9665. Tools.Error("Error while trying to load image: " + input);
  9666. if (onError) {
  9667. onError("Error while trying to load image: " + input, err);
  9668. }
  9669. };
  9670. img.addEventListener("load", loadHandler);
  9671. img.addEventListener("error", errorHandler);
  9672. var noIndexedDB = function () {
  9673. img.src = url;
  9674. };
  9675. var loadFromIndexedDB = function () {
  9676. if (database) {
  9677. database.loadImageFromDB(url, img);
  9678. }
  9679. };
  9680. //ANY database to do!
  9681. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9682. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9683. }
  9684. else {
  9685. if (url.indexOf("file:") !== -1) {
  9686. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9687. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9688. try {
  9689. var blobURL;
  9690. try {
  9691. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9692. }
  9693. catch (ex) {
  9694. // Chrome doesn't support oneTimeOnly parameter
  9695. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9696. }
  9697. img.src = blobURL;
  9698. usingObjectURL = true;
  9699. }
  9700. catch (e) {
  9701. img.src = "";
  9702. }
  9703. return img;
  9704. }
  9705. }
  9706. noIndexedDB();
  9707. }
  9708. return img;
  9709. };
  9710. /**
  9711. * Loads a file
  9712. * @param url url string, ArrayBuffer, or Blob to load
  9713. * @param onSuccess callback called when the file successfully loads
  9714. * @param onProgress callback called while file is loading (if the server supports this mode)
  9715. * @param database database for caching
  9716. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  9717. * @param onError callback called when the file fails to load
  9718. * @returns a file request object
  9719. */
  9720. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9721. url = Tools.CleanUrl(url);
  9722. url = Tools.PreprocessUrl(url);
  9723. // If file and file input are set
  9724. if (url.indexOf("file:") !== -1) {
  9725. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9726. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9727. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9728. }
  9729. }
  9730. var loadUrl = Tools.BaseUrl + url;
  9731. var aborted = false;
  9732. var fileRequest = {
  9733. onCompleteObservable: new BABYLON.Observable(),
  9734. abort: function () { return aborted = true; },
  9735. };
  9736. var requestFile = function () {
  9737. var request = new XMLHttpRequest();
  9738. var retryHandle = null;
  9739. fileRequest.abort = function () {
  9740. aborted = true;
  9741. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9742. request.abort();
  9743. }
  9744. if (retryHandle !== null) {
  9745. clearTimeout(retryHandle);
  9746. retryHandle = null;
  9747. }
  9748. };
  9749. var retryLoop = function (retryIndex) {
  9750. request.open('GET', loadUrl, true);
  9751. if (useArrayBuffer) {
  9752. request.responseType = "arraybuffer";
  9753. }
  9754. if (onProgress) {
  9755. request.addEventListener("progress", onProgress);
  9756. }
  9757. var onLoadEnd = function () {
  9758. request.removeEventListener("loadend", onLoadEnd);
  9759. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9760. fileRequest.onCompleteObservable.clear();
  9761. };
  9762. request.addEventListener("loadend", onLoadEnd);
  9763. var onReadyStateChange = function () {
  9764. if (aborted) {
  9765. return;
  9766. }
  9767. // In case of undefined state in some browsers.
  9768. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9769. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9770. request.removeEventListener("readystatechange", onReadyStateChange);
  9771. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9772. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9773. return;
  9774. }
  9775. var retryStrategy = Tools.DefaultRetryStrategy;
  9776. if (retryStrategy) {
  9777. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9778. if (waitTime !== -1) {
  9779. // Prevent the request from completing for retry.
  9780. request.removeEventListener("loadend", onLoadEnd);
  9781. request = new XMLHttpRequest();
  9782. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9783. return;
  9784. }
  9785. }
  9786. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9787. if (onError) {
  9788. onError(request, e);
  9789. }
  9790. else {
  9791. throw e;
  9792. }
  9793. }
  9794. };
  9795. request.addEventListener("readystatechange", onReadyStateChange);
  9796. request.send();
  9797. };
  9798. retryLoop(0);
  9799. };
  9800. // Caching all files
  9801. if (database && database.enableSceneOffline) {
  9802. var noIndexedDB_1 = function (request) {
  9803. if (request && request.status > 400) {
  9804. if (onError) {
  9805. onError(request);
  9806. }
  9807. }
  9808. else {
  9809. if (!aborted) {
  9810. requestFile();
  9811. }
  9812. }
  9813. };
  9814. var loadFromIndexedDB = function () {
  9815. // TODO: database needs to support aborting and should return a IFileRequest
  9816. if (aborted) {
  9817. return;
  9818. }
  9819. if (database) {
  9820. database.loadFileFromDB(url, function (data) {
  9821. if (!aborted) {
  9822. onSuccess(data);
  9823. }
  9824. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9825. }, onProgress ? function (event) {
  9826. if (!aborted) {
  9827. onProgress(event);
  9828. }
  9829. } : undefined, noIndexedDB_1, useArrayBuffer);
  9830. }
  9831. };
  9832. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9833. }
  9834. else {
  9835. requestFile();
  9836. }
  9837. return fileRequest;
  9838. };
  9839. /**
  9840. * Load a script (identified by an url). When the url returns, the
  9841. * content of this file is added into a new script element, attached to the DOM (body element)
  9842. * @param scriptUrl defines the url of the script to laod
  9843. * @param onSuccess defines the callback called when the script is loaded
  9844. * @param onError defines the callback to call if an error occurs
  9845. */
  9846. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9847. if (!Tools.IsWindowObjectExist()) {
  9848. return;
  9849. }
  9850. var head = document.getElementsByTagName('head')[0];
  9851. var script = document.createElement('script');
  9852. script.type = 'text/javascript';
  9853. script.src = scriptUrl;
  9854. script.onload = function () {
  9855. if (onSuccess) {
  9856. onSuccess();
  9857. }
  9858. };
  9859. script.onerror = function (e) {
  9860. if (onError) {
  9861. onError("Unable to load script '" + scriptUrl + "'", e);
  9862. }
  9863. };
  9864. head.appendChild(script);
  9865. };
  9866. /**
  9867. * Loads a file from a blob
  9868. * @param fileToLoad defines the blob to use
  9869. * @param callback defines the callback to call when data is loaded
  9870. * @param progressCallback defines the callback to call during loading process
  9871. * @returns a file request object
  9872. */
  9873. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9874. var reader = new FileReader();
  9875. var request = {
  9876. onCompleteObservable: new BABYLON.Observable(),
  9877. abort: function () { return reader.abort(); },
  9878. };
  9879. reader.onloadend = function (e) {
  9880. request.onCompleteObservable.notifyObservers(request);
  9881. };
  9882. reader.onload = function (e) {
  9883. //target doesn't have result from ts 1.3
  9884. callback(e.target['result']);
  9885. };
  9886. reader.onprogress = progressCallback;
  9887. reader.readAsDataURL(fileToLoad);
  9888. return request;
  9889. };
  9890. /**
  9891. * Loads a file
  9892. * @param fileToLoad defines the file to load
  9893. * @param callback defines the callback to call when data is loaded
  9894. * @param progressCallBack defines the callback to call during loading process
  9895. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  9896. * @returns a file request object
  9897. */
  9898. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9899. var reader = new FileReader();
  9900. var request = {
  9901. onCompleteObservable: new BABYLON.Observable(),
  9902. abort: function () { return reader.abort(); },
  9903. };
  9904. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9905. reader.onerror = function (e) {
  9906. Tools.Log("Error while reading file: " + fileToLoad.name);
  9907. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9908. };
  9909. reader.onload = function (e) {
  9910. //target doesn't have result from ts 1.3
  9911. callback(e.target['result']);
  9912. };
  9913. if (progressCallBack) {
  9914. reader.onprogress = progressCallBack;
  9915. }
  9916. if (!useArrayBuffer) {
  9917. // Asynchronous read
  9918. reader.readAsText(fileToLoad);
  9919. }
  9920. else {
  9921. reader.readAsArrayBuffer(fileToLoad);
  9922. }
  9923. return request;
  9924. };
  9925. /**
  9926. * Creates a data url from a given string content
  9927. * @param content defines the content to convert
  9928. * @returns the new data url link
  9929. */
  9930. Tools.FileAsURL = function (content) {
  9931. var fileBlob = new Blob([content]);
  9932. var url = window.URL || window.webkitURL;
  9933. var link = url.createObjectURL(fileBlob);
  9934. return link;
  9935. };
  9936. /**
  9937. * Format the given number to a specific decimal format
  9938. * @param value defines the number to format
  9939. * @param decimals defines the number of decimals to use
  9940. * @returns the formatted string
  9941. */
  9942. Tools.Format = function (value, decimals) {
  9943. if (decimals === void 0) { decimals = 2; }
  9944. return value.toFixed(decimals);
  9945. };
  9946. /**
  9947. * Checks if a given vector is inside a specific range
  9948. * @param v defines the vector to test
  9949. * @param min defines the minimum range
  9950. * @param max defines the maximum range
  9951. */
  9952. Tools.CheckExtends = function (v, min, max) {
  9953. if (v.x < min.x)
  9954. min.x = v.x;
  9955. if (v.y < min.y)
  9956. min.y = v.y;
  9957. if (v.z < min.z)
  9958. min.z = v.z;
  9959. if (v.x > max.x)
  9960. max.x = v.x;
  9961. if (v.y > max.y)
  9962. max.y = v.y;
  9963. if (v.z > max.z)
  9964. max.z = v.z;
  9965. };
  9966. /**
  9967. * Tries to copy an object by duplicating every property
  9968. * @param source defines the source object
  9969. * @param destination defines the target object
  9970. * @param doNotCopyList defines a list of properties to avoid
  9971. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  9972. */
  9973. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9974. for (var prop in source) {
  9975. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9976. continue;
  9977. }
  9978. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9979. continue;
  9980. }
  9981. var sourceValue = source[prop];
  9982. var typeOfSourceValue = typeof sourceValue;
  9983. if (typeOfSourceValue === "function") {
  9984. continue;
  9985. }
  9986. try {
  9987. if (typeOfSourceValue === "object") {
  9988. if (sourceValue instanceof Array) {
  9989. destination[prop] = [];
  9990. if (sourceValue.length > 0) {
  9991. if (typeof sourceValue[0] == "object") {
  9992. for (var index = 0; index < sourceValue.length; index++) {
  9993. var clonedValue = cloneValue(sourceValue[index], destination);
  9994. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9995. destination[prop].push(clonedValue);
  9996. }
  9997. }
  9998. }
  9999. else {
  10000. destination[prop] = sourceValue.slice(0);
  10001. }
  10002. }
  10003. }
  10004. else {
  10005. destination[prop] = cloneValue(sourceValue, destination);
  10006. }
  10007. }
  10008. else {
  10009. destination[prop] = sourceValue;
  10010. }
  10011. }
  10012. catch (e) {
  10013. // Just ignore error (it could be because of a read-only property)
  10014. }
  10015. }
  10016. };
  10017. /**
  10018. * Gets a boolean indicating if the given object has no own property
  10019. * @param obj defines the object to test
  10020. * @returns true if object has no own property
  10021. */
  10022. Tools.IsEmpty = function (obj) {
  10023. for (var i in obj) {
  10024. if (obj.hasOwnProperty(i)) {
  10025. return false;
  10026. }
  10027. }
  10028. return true;
  10029. };
  10030. /**
  10031. * Function used to register events at window level
  10032. * @param events defines the events to register
  10033. */
  10034. Tools.RegisterTopRootEvents = function (events) {
  10035. for (var index = 0; index < events.length; index++) {
  10036. var event = events[index];
  10037. window.addEventListener(event.name, event.handler, false);
  10038. try {
  10039. if (window.parent) {
  10040. window.parent.addEventListener(event.name, event.handler, false);
  10041. }
  10042. }
  10043. catch (e) {
  10044. // Silently fails...
  10045. }
  10046. }
  10047. };
  10048. /**
  10049. * Function used to unregister events from window level
  10050. * @param events defines the events to unregister
  10051. */
  10052. Tools.UnregisterTopRootEvents = function (events) {
  10053. for (var index = 0; index < events.length; index++) {
  10054. var event = events[index];
  10055. window.removeEventListener(event.name, event.handler);
  10056. try {
  10057. if (window.parent) {
  10058. window.parent.removeEventListener(event.name, event.handler);
  10059. }
  10060. }
  10061. catch (e) {
  10062. // Silently fails...
  10063. }
  10064. }
  10065. };
  10066. /**
  10067. * Dumps the current bound framebuffer
  10068. * @param width defines the rendering width
  10069. * @param height defines the rendering height
  10070. * @param engine defines the hosting engine
  10071. * @param successCallback defines the callback triggered once the data are available
  10072. * @param mimeType defines the mime type of the result
  10073. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  10074. */
  10075. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  10076. if (mimeType === void 0) { mimeType = "image/png"; }
  10077. // Read the contents of the framebuffer
  10078. var numberOfChannelsByLine = width * 4;
  10079. var halfHeight = height / 2;
  10080. //Reading datas from WebGL
  10081. var data = engine.readPixels(0, 0, width, height);
  10082. //To flip image on Y axis.
  10083. for (var i = 0; i < halfHeight; i++) {
  10084. for (var j = 0; j < numberOfChannelsByLine; j++) {
  10085. var currentCell = j + i * numberOfChannelsByLine;
  10086. var targetLine = height - i - 1;
  10087. var targetCell = j + targetLine * numberOfChannelsByLine;
  10088. var temp = data[currentCell];
  10089. data[currentCell] = data[targetCell];
  10090. data[targetCell] = temp;
  10091. }
  10092. }
  10093. // Create a 2D canvas to store the result
  10094. if (!screenshotCanvas) {
  10095. screenshotCanvas = document.createElement('canvas');
  10096. }
  10097. screenshotCanvas.width = width;
  10098. screenshotCanvas.height = height;
  10099. var context = screenshotCanvas.getContext('2d');
  10100. if (context) {
  10101. // Copy the pixels to a 2D canvas
  10102. var imageData = context.createImageData(width, height);
  10103. var castData = (imageData.data);
  10104. castData.set(data);
  10105. context.putImageData(imageData, 0, 0);
  10106. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  10107. }
  10108. };
  10109. /**
  10110. * Converts the canvas data to blob.
  10111. * This acts as a polyfill for browsers not supporting the to blob function.
  10112. * @param canvas Defines the canvas to extract the data from
  10113. * @param successCallback Defines the callback triggered once the data are available
  10114. * @param mimeType Defines the mime type of the result
  10115. */
  10116. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  10117. if (mimeType === void 0) { mimeType = "image/png"; }
  10118. // We need HTMLCanvasElement.toBlob for HD screenshots
  10119. if (!canvas.toBlob) {
  10120. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  10121. canvas.toBlob = function (callback, type, quality) {
  10122. var _this = this;
  10123. setTimeout(function () {
  10124. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  10125. for (var i = 0; i < len; i++) {
  10126. arr[i] = binStr.charCodeAt(i);
  10127. }
  10128. callback(new Blob([arr]));
  10129. });
  10130. };
  10131. }
  10132. canvas.toBlob(function (blob) {
  10133. successCallback(blob);
  10134. }, mimeType);
  10135. };
  10136. /**
  10137. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  10138. * @param successCallback defines the callback triggered once the data are available
  10139. * @param mimeType defines the mime type of the result
  10140. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  10141. */
  10142. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  10143. if (mimeType === void 0) { mimeType = "image/png"; }
  10144. if (successCallback) {
  10145. var base64Image = screenshotCanvas.toDataURL(mimeType);
  10146. successCallback(base64Image);
  10147. }
  10148. else {
  10149. this.ToBlob(screenshotCanvas, function (blob) {
  10150. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  10151. if (("download" in document.createElement("a"))) {
  10152. if (!fileName) {
  10153. var date = new Date();
  10154. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  10155. fileName = "screenshot_" + stringDate + ".png";
  10156. }
  10157. Tools.Download(blob, fileName);
  10158. }
  10159. else {
  10160. var url = URL.createObjectURL(blob);
  10161. var newWindow = window.open("");
  10162. if (!newWindow)
  10163. return;
  10164. var img = newWindow.document.createElement("img");
  10165. img.onload = function () {
  10166. // no longer need to read the blob so it's revoked
  10167. URL.revokeObjectURL(url);
  10168. };
  10169. img.src = url;
  10170. newWindow.document.body.appendChild(img);
  10171. }
  10172. }, mimeType);
  10173. }
  10174. };
  10175. /**
  10176. * Downloads a blob in the browser
  10177. * @param blob defines the blob to download
  10178. * @param fileName defines the name of the downloaded file
  10179. */
  10180. Tools.Download = function (blob, fileName) {
  10181. if (navigator && navigator.msSaveBlob) {
  10182. navigator.msSaveBlob(blob, fileName);
  10183. return;
  10184. }
  10185. var url = window.URL.createObjectURL(blob);
  10186. var a = document.createElement("a");
  10187. document.body.appendChild(a);
  10188. a.style.display = "none";
  10189. a.href = url;
  10190. a.download = fileName;
  10191. a.addEventListener("click", function () {
  10192. if (a.parentElement) {
  10193. a.parentElement.removeChild(a);
  10194. }
  10195. });
  10196. a.click();
  10197. window.URL.revokeObjectURL(url);
  10198. };
  10199. /**
  10200. * Captures a screenshot of the current rendering
  10201. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10202. * @param engine defines the rendering engine
  10203. * @param camera defines the source camera
  10204. * @param size This parameter can be set to a single number or to an object with the
  10205. * following (optional) properties: precision, width, height. If a single number is passed,
  10206. * it will be used for both width and height. If an object is passed, the screenshot size
  10207. * will be derived from the parameters. The precision property is a multiplier allowing
  10208. * rendering at a higher or lower resolution
  10209. * @param successCallback defines the callback receives a single parameter which contains the
  10210. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10211. * src parameter of an <img> to display it
  10212. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  10213. * Check your browser for supported MIME types
  10214. */
  10215. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  10216. if (mimeType === void 0) { mimeType = "image/png"; }
  10217. var width;
  10218. var height;
  10219. // If a precision value is specified
  10220. if (size.precision) {
  10221. width = Math.round(engine.getRenderWidth() * size.precision);
  10222. height = Math.round(width / engine.getAspectRatio(camera));
  10223. }
  10224. else if (size.width && size.height) {
  10225. width = size.width;
  10226. height = size.height;
  10227. }
  10228. //If passing only width, computing height to keep display canvas ratio.
  10229. else if (size.width && !size.height) {
  10230. width = size.width;
  10231. height = Math.round(width / engine.getAspectRatio(camera));
  10232. }
  10233. //If passing only height, computing width to keep display canvas ratio.
  10234. else if (size.height && !size.width) {
  10235. height = size.height;
  10236. width = Math.round(height * engine.getAspectRatio(camera));
  10237. }
  10238. //Assuming here that "size" parameter is a number
  10239. else if (!isNaN(size)) {
  10240. height = size;
  10241. width = size;
  10242. }
  10243. else {
  10244. Tools.Error("Invalid 'size' parameter !");
  10245. return;
  10246. }
  10247. if (!screenshotCanvas) {
  10248. screenshotCanvas = document.createElement('canvas');
  10249. }
  10250. screenshotCanvas.width = width;
  10251. screenshotCanvas.height = height;
  10252. var renderContext = screenshotCanvas.getContext("2d");
  10253. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  10254. var newWidth = width;
  10255. var newHeight = newWidth / ratio;
  10256. if (newHeight > height) {
  10257. newHeight = height;
  10258. newWidth = newHeight * ratio;
  10259. }
  10260. var offsetX = Math.max(0, width - newWidth) / 2;
  10261. var offsetY = Math.max(0, height - newHeight) / 2;
  10262. var renderingCanvas = engine.getRenderingCanvas();
  10263. if (renderContext && renderingCanvas) {
  10264. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  10265. }
  10266. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  10267. };
  10268. /**
  10269. * Generates an image screenshot from the specified camera.
  10270. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10271. * @param engine The engine to use for rendering
  10272. * @param camera The camera to use for rendering
  10273. * @param size This parameter can be set to a single number or to an object with the
  10274. * following (optional) properties: precision, width, height. If a single number is passed,
  10275. * it will be used for both width and height. If an object is passed, the screenshot size
  10276. * will be derived from the parameters. The precision property is a multiplier allowing
  10277. * rendering at a higher or lower resolution
  10278. * @param successCallback The callback receives a single parameter which contains the
  10279. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10280. * src parameter of an <img> to display it
  10281. * @param mimeType The MIME type of the screenshot image (default: image/png).
  10282. * Check your browser for supported MIME types
  10283. * @param samples Texture samples (default: 1)
  10284. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  10285. * @param fileName A name for for the downloaded file.
  10286. */
  10287. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  10288. if (mimeType === void 0) { mimeType = "image/png"; }
  10289. if (samples === void 0) { samples = 1; }
  10290. if (antialiasing === void 0) { antialiasing = false; }
  10291. var width;
  10292. var height;
  10293. //If a precision value is specified
  10294. if (size.precision) {
  10295. width = Math.round(engine.getRenderWidth() * size.precision);
  10296. height = Math.round(width / engine.getAspectRatio(camera));
  10297. size = { width: width, height: height };
  10298. }
  10299. else if (size.width && size.height) {
  10300. width = size.width;
  10301. height = size.height;
  10302. }
  10303. //If passing only width, computing height to keep display canvas ratio.
  10304. else if (size.width && !size.height) {
  10305. width = size.width;
  10306. height = Math.round(width / engine.getAspectRatio(camera));
  10307. size = { width: width, height: height };
  10308. }
  10309. //If passing only height, computing width to keep display canvas ratio.
  10310. else if (size.height && !size.width) {
  10311. height = size.height;
  10312. width = Math.round(height * engine.getAspectRatio(camera));
  10313. size = { width: width, height: height };
  10314. }
  10315. //Assuming here that "size" parameter is a number
  10316. else if (!isNaN(size)) {
  10317. height = size;
  10318. width = size;
  10319. }
  10320. else {
  10321. Tools.Error("Invalid 'size' parameter !");
  10322. return;
  10323. }
  10324. var scene = camera.getScene();
  10325. var previousCamera = null;
  10326. if (scene.activeCamera !== camera) {
  10327. previousCamera = scene.activeCamera;
  10328. scene.activeCamera = camera;
  10329. }
  10330. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  10331. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10332. texture.renderList = null;
  10333. texture.samples = samples;
  10334. if (antialiasing) {
  10335. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  10336. }
  10337. texture.onAfterRenderObservable.add(function () {
  10338. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  10339. });
  10340. scene.incrementRenderId();
  10341. scene.resetCachedMaterial();
  10342. texture.render(true);
  10343. texture.dispose();
  10344. if (previousCamera) {
  10345. scene.activeCamera = previousCamera;
  10346. }
  10347. camera.getProjectionMatrix(true); // Force cache refresh;
  10348. };
  10349. /**
  10350. * Validates if xhr data is correct
  10351. * @param xhr defines the request to validate
  10352. * @param dataType defines the expected data type
  10353. * @returns true if data is correct
  10354. */
  10355. Tools.ValidateXHRData = function (xhr, dataType) {
  10356. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  10357. if (dataType === void 0) { dataType = 7; }
  10358. try {
  10359. if (dataType & 1) {
  10360. if (xhr.responseText && xhr.responseText.length > 0) {
  10361. return true;
  10362. }
  10363. else if (dataType === 1) {
  10364. return false;
  10365. }
  10366. }
  10367. if (dataType & 2) {
  10368. // Check header width and height since there is no "TGA" magic number
  10369. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  10370. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  10371. return true;
  10372. }
  10373. else if (dataType === 2) {
  10374. return false;
  10375. }
  10376. }
  10377. if (dataType & 4) {
  10378. // Check for the "DDS" magic number
  10379. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  10380. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  10381. return true;
  10382. }
  10383. else {
  10384. return false;
  10385. }
  10386. }
  10387. }
  10388. catch (e) {
  10389. // Global protection
  10390. }
  10391. return false;
  10392. };
  10393. /**
  10394. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  10395. * Be aware Math.random() could cause collisions, but:
  10396. * "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"
  10397. * @returns a pseudo random id
  10398. */
  10399. Tools.RandomId = function () {
  10400. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  10401. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  10402. return v.toString(16);
  10403. });
  10404. };
  10405. /**
  10406. * Test if the given uri is a base64 string
  10407. * @param uri The uri to test
  10408. * @return True if the uri is a base64 string or false otherwise
  10409. */
  10410. Tools.IsBase64 = function (uri) {
  10411. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  10412. };
  10413. /**
  10414. * Decode the given base64 uri.
  10415. * @param uri The uri to decode
  10416. * @return The decoded base64 data.
  10417. */
  10418. Tools.DecodeBase64 = function (uri) {
  10419. var decodedString = atob(uri.split(",")[1]);
  10420. var bufferLength = decodedString.length;
  10421. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  10422. for (var i = 0; i < bufferLength; i++) {
  10423. bufferView[i] = decodedString.charCodeAt(i);
  10424. }
  10425. return bufferView.buffer;
  10426. };
  10427. Tools._AddLogEntry = function (entry) {
  10428. Tools._LogCache = entry + Tools._LogCache;
  10429. if (Tools.OnNewCacheEntry) {
  10430. Tools.OnNewCacheEntry(entry);
  10431. }
  10432. };
  10433. Tools._FormatMessage = function (message) {
  10434. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  10435. var date = new Date();
  10436. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  10437. };
  10438. Tools._LogDisabled = function (message) {
  10439. // nothing to do
  10440. };
  10441. Tools._LogEnabled = function (message) {
  10442. var formattedMessage = Tools._FormatMessage(message);
  10443. console.log("BJS - " + formattedMessage);
  10444. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  10445. Tools._AddLogEntry(entry);
  10446. };
  10447. Tools._WarnDisabled = function (message) {
  10448. // nothing to do
  10449. };
  10450. Tools._WarnEnabled = function (message) {
  10451. var formattedMessage = Tools._FormatMessage(message);
  10452. console.warn("BJS - " + formattedMessage);
  10453. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  10454. Tools._AddLogEntry(entry);
  10455. };
  10456. Tools._ErrorDisabled = function (message) {
  10457. // nothing to do
  10458. };
  10459. Tools._ErrorEnabled = function (message) {
  10460. Tools.errorsCount++;
  10461. var formattedMessage = Tools._FormatMessage(message);
  10462. console.error("BJS - " + formattedMessage);
  10463. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  10464. Tools._AddLogEntry(entry);
  10465. };
  10466. Object.defineProperty(Tools, "LogCache", {
  10467. /**
  10468. * Gets current log cache (list of logs)
  10469. */
  10470. get: function () {
  10471. return Tools._LogCache;
  10472. },
  10473. enumerable: true,
  10474. configurable: true
  10475. });
  10476. /**
  10477. * Clears the log cache
  10478. */
  10479. Tools.ClearLogCache = function () {
  10480. Tools._LogCache = "";
  10481. Tools.errorsCount = 0;
  10482. };
  10483. Object.defineProperty(Tools, "LogLevels", {
  10484. /**
  10485. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  10486. */
  10487. set: function (level) {
  10488. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  10489. Tools.Log = Tools._LogEnabled;
  10490. }
  10491. else {
  10492. Tools.Log = Tools._LogDisabled;
  10493. }
  10494. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  10495. Tools.Warn = Tools._WarnEnabled;
  10496. }
  10497. else {
  10498. Tools.Warn = Tools._WarnDisabled;
  10499. }
  10500. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  10501. Tools.Error = Tools._ErrorEnabled;
  10502. }
  10503. else {
  10504. Tools.Error = Tools._ErrorDisabled;
  10505. }
  10506. },
  10507. enumerable: true,
  10508. configurable: true
  10509. });
  10510. /**
  10511. * Checks if the loaded document was accessed via `file:`-Protocol.
  10512. * @returns boolean
  10513. */
  10514. Tools.IsFileURL = function () {
  10515. return location.protocol === "file:";
  10516. };
  10517. /**
  10518. * Checks if the window object exists
  10519. * @returns true if the window object exists
  10520. */
  10521. Tools.IsWindowObjectExist = function () {
  10522. return (typeof window) !== "undefined";
  10523. };
  10524. Object.defineProperty(Tools, "PerformanceLogLevel", {
  10525. /**
  10526. * Sets the current performance log level
  10527. */
  10528. set: function (level) {
  10529. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  10530. Tools.StartPerformanceCounter = Tools._StartUserMark;
  10531. Tools.EndPerformanceCounter = Tools._EndUserMark;
  10532. return;
  10533. }
  10534. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  10535. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  10536. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  10537. return;
  10538. }
  10539. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10540. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10541. },
  10542. enumerable: true,
  10543. configurable: true
  10544. });
  10545. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10546. };
  10547. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10548. };
  10549. Tools._StartUserMark = function (counterName, condition) {
  10550. if (condition === void 0) { condition = true; }
  10551. if (!Tools._performance) {
  10552. if (!Tools.IsWindowObjectExist()) {
  10553. return;
  10554. }
  10555. Tools._performance = window.performance;
  10556. }
  10557. if (!condition || !Tools._performance.mark) {
  10558. return;
  10559. }
  10560. Tools._performance.mark(counterName + "-Begin");
  10561. };
  10562. Tools._EndUserMark = function (counterName, condition) {
  10563. if (condition === void 0) { condition = true; }
  10564. if (!condition || !Tools._performance.mark) {
  10565. return;
  10566. }
  10567. Tools._performance.mark(counterName + "-End");
  10568. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10569. };
  10570. Tools._StartPerformanceConsole = function (counterName, condition) {
  10571. if (condition === void 0) { condition = true; }
  10572. if (!condition) {
  10573. return;
  10574. }
  10575. Tools._StartUserMark(counterName, condition);
  10576. if (console.time) {
  10577. console.time(counterName);
  10578. }
  10579. };
  10580. Tools._EndPerformanceConsole = function (counterName, condition) {
  10581. if (condition === void 0) { condition = true; }
  10582. if (!condition) {
  10583. return;
  10584. }
  10585. Tools._EndUserMark(counterName, condition);
  10586. if (console.time) {
  10587. console.timeEnd(counterName);
  10588. }
  10589. };
  10590. Object.defineProperty(Tools, "Now", {
  10591. /**
  10592. * Gets either window.performance.now() if supported or Date.now() else
  10593. */
  10594. get: function () {
  10595. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10596. return window.performance.now();
  10597. }
  10598. return Date.now();
  10599. },
  10600. enumerable: true,
  10601. configurable: true
  10602. });
  10603. /**
  10604. * This method will return the name of the class used to create the instance of the given object.
  10605. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10606. * @param object the object to get the class name from
  10607. * @param isType defines if the object is actually a type
  10608. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  10609. */
  10610. Tools.GetClassName = function (object, isType) {
  10611. if (isType === void 0) { isType = false; }
  10612. var name = null;
  10613. if (!isType && object.getClassName) {
  10614. name = object.getClassName();
  10615. }
  10616. else {
  10617. if (object instanceof Object) {
  10618. var classObj = isType ? object : Object.getPrototypeOf(object);
  10619. name = classObj.constructor["__bjsclassName__"];
  10620. }
  10621. if (!name) {
  10622. name = typeof object;
  10623. }
  10624. }
  10625. return name;
  10626. };
  10627. /**
  10628. * Gets the first element of an array satisfying a given predicate
  10629. * @param array defines the array to browse
  10630. * @param predicate defines the predicate to use
  10631. * @returns null if not found or the element
  10632. */
  10633. Tools.First = function (array, predicate) {
  10634. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10635. var el = array_1[_i];
  10636. if (predicate(el)) {
  10637. return el;
  10638. }
  10639. }
  10640. return null;
  10641. };
  10642. /**
  10643. * This method will return the name of the full name of the class, including its owning module (if any).
  10644. * 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).
  10645. * @param object the object to get the class name from
  10646. * @param isType defines if the object is actually a type
  10647. * @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.
  10648. * @ignorenaming
  10649. */
  10650. Tools.getFullClassName = function (object, isType) {
  10651. if (isType === void 0) { isType = false; }
  10652. var className = null;
  10653. var moduleName = null;
  10654. if (!isType && object.getClassName) {
  10655. className = object.getClassName();
  10656. }
  10657. else {
  10658. if (object instanceof Object) {
  10659. var classObj = isType ? object : Object.getPrototypeOf(object);
  10660. className = classObj.constructor["__bjsclassName__"];
  10661. moduleName = classObj.constructor["__bjsmoduleName__"];
  10662. }
  10663. if (!className) {
  10664. className = typeof object;
  10665. }
  10666. }
  10667. if (!className) {
  10668. return null;
  10669. }
  10670. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10671. };
  10672. /**
  10673. * Returns a promise that resolves after the given amount of time.
  10674. * @param delay Number of milliseconds to delay
  10675. * @returns Promise that resolves after the given amount of time
  10676. */
  10677. Tools.DelayAsync = function (delay) {
  10678. return new Promise(function (resolve) {
  10679. setTimeout(function () {
  10680. resolve();
  10681. }, delay);
  10682. });
  10683. };
  10684. /**
  10685. * Gets the current gradient from an array of IValueGradient
  10686. * @param ratio defines the current ratio to get
  10687. * @param gradients defines the array of IValueGradient
  10688. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10689. */
  10690. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10691. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10692. var currentGradient = gradients[gradientIndex];
  10693. var nextGradient = gradients[gradientIndex + 1];
  10694. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10695. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10696. updateFunc(currentGradient, nextGradient, scale);
  10697. return;
  10698. }
  10699. }
  10700. // Use last index if over
  10701. var lastIndex = gradients.length - 1;
  10702. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10703. };
  10704. /**
  10705. * Gets or sets the base URL to use to load assets
  10706. */
  10707. Tools.BaseUrl = "";
  10708. /**
  10709. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  10710. */
  10711. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10712. /**
  10713. * Default behaviour for cors in the application.
  10714. * It can be a string if the expected behavior is identical in the entire app.
  10715. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10716. */
  10717. Tools.CorsBehavior = "anonymous";
  10718. /**
  10719. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  10720. * @ignorenaming
  10721. */
  10722. Tools.UseFallbackTexture = true;
  10723. /**
  10724. * Use this object to register external classes like custom textures or material
  10725. * to allow the laoders to instantiate them
  10726. */
  10727. Tools.RegisteredExternalClasses = {};
  10728. /**
  10729. * Texture content used if a texture cannot loaded
  10730. * @ignorenaming
  10731. */
  10732. 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";
  10733. Tools._tmpFloatArray = new Float32Array(1);
  10734. /**
  10735. * Gets or sets a function used to pre-process url before using them to load assets
  10736. */
  10737. Tools.PreprocessUrl = function (url) {
  10738. return url;
  10739. };
  10740. // Logs
  10741. /**
  10742. * No log
  10743. */
  10744. Tools.NoneLogLevel = 0;
  10745. /**
  10746. * Only message logs
  10747. */
  10748. Tools.MessageLogLevel = 1;
  10749. /**
  10750. * Only warning logs
  10751. */
  10752. Tools.WarningLogLevel = 2;
  10753. /**
  10754. * Only error logs
  10755. */
  10756. Tools.ErrorLogLevel = 4;
  10757. /**
  10758. * All logs
  10759. */
  10760. Tools.AllLogLevel = 7;
  10761. Tools._LogCache = "";
  10762. /**
  10763. * Gets a value indicating the number of loading errors
  10764. * @ignorenaming
  10765. */
  10766. Tools.errorsCount = 0;
  10767. /**
  10768. * Log a message to the console
  10769. */
  10770. Tools.Log = Tools._LogEnabled;
  10771. /**
  10772. * Write a warning message to the console
  10773. */
  10774. Tools.Warn = Tools._WarnEnabled;
  10775. /**
  10776. * Write an error message to the console
  10777. */
  10778. Tools.Error = Tools._ErrorEnabled;
  10779. // Performances
  10780. /**
  10781. * No performance log
  10782. */
  10783. Tools.PerformanceNoneLogLevel = 0;
  10784. /**
  10785. * Use user marks to log performance
  10786. */
  10787. Tools.PerformanceUserMarkLogLevel = 1;
  10788. /**
  10789. * Log performance to the console
  10790. */
  10791. Tools.PerformanceConsoleLogLevel = 2;
  10792. /**
  10793. * Starts a performance counter
  10794. */
  10795. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10796. /**
  10797. * Ends a specific performance coutner
  10798. */
  10799. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10800. return Tools;
  10801. }());
  10802. BABYLON.Tools = Tools;
  10803. /**
  10804. * This class is used to track a performance counter which is number based.
  10805. * The user has access to many properties which give statistics of different nature.
  10806. *
  10807. * The implementer can track two kinds of Performance Counter: time and count.
  10808. * 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.
  10809. * 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.
  10810. */
  10811. var PerfCounter = /** @class */ (function () {
  10812. /**
  10813. * Creates a new counter
  10814. */
  10815. function PerfCounter() {
  10816. this._startMonitoringTime = 0;
  10817. this._min = 0;
  10818. this._max = 0;
  10819. this._average = 0;
  10820. this._lastSecAverage = 0;
  10821. this._current = 0;
  10822. this._totalValueCount = 0;
  10823. this._totalAccumulated = 0;
  10824. this._lastSecAccumulated = 0;
  10825. this._lastSecTime = 0;
  10826. this._lastSecValueCount = 0;
  10827. }
  10828. Object.defineProperty(PerfCounter.prototype, "min", {
  10829. /**
  10830. * Returns the smallest value ever
  10831. */
  10832. get: function () {
  10833. return this._min;
  10834. },
  10835. enumerable: true,
  10836. configurable: true
  10837. });
  10838. Object.defineProperty(PerfCounter.prototype, "max", {
  10839. /**
  10840. * Returns the biggest value ever
  10841. */
  10842. get: function () {
  10843. return this._max;
  10844. },
  10845. enumerable: true,
  10846. configurable: true
  10847. });
  10848. Object.defineProperty(PerfCounter.prototype, "average", {
  10849. /**
  10850. * Returns the average value since the performance counter is running
  10851. */
  10852. get: function () {
  10853. return this._average;
  10854. },
  10855. enumerable: true,
  10856. configurable: true
  10857. });
  10858. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10859. /**
  10860. * Returns the average value of the last second the counter was monitored
  10861. */
  10862. get: function () {
  10863. return this._lastSecAverage;
  10864. },
  10865. enumerable: true,
  10866. configurable: true
  10867. });
  10868. Object.defineProperty(PerfCounter.prototype, "current", {
  10869. /**
  10870. * Returns the current value
  10871. */
  10872. get: function () {
  10873. return this._current;
  10874. },
  10875. enumerable: true,
  10876. configurable: true
  10877. });
  10878. Object.defineProperty(PerfCounter.prototype, "total", {
  10879. /**
  10880. * Gets the accumulated total
  10881. */
  10882. get: function () {
  10883. return this._totalAccumulated;
  10884. },
  10885. enumerable: true,
  10886. configurable: true
  10887. });
  10888. Object.defineProperty(PerfCounter.prototype, "count", {
  10889. /**
  10890. * Gets the total value count
  10891. */
  10892. get: function () {
  10893. return this._totalValueCount;
  10894. },
  10895. enumerable: true,
  10896. configurable: true
  10897. });
  10898. /**
  10899. * Call this method to start monitoring a new frame.
  10900. * 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.
  10901. */
  10902. PerfCounter.prototype.fetchNewFrame = function () {
  10903. this._totalValueCount++;
  10904. this._current = 0;
  10905. this._lastSecValueCount++;
  10906. };
  10907. /**
  10908. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10909. * @param newCount the count value to add to the monitored count
  10910. * @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.
  10911. */
  10912. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10913. if (!PerfCounter.Enabled) {
  10914. return;
  10915. }
  10916. this._current += newCount;
  10917. if (fetchResult) {
  10918. this._fetchResult();
  10919. }
  10920. };
  10921. /**
  10922. * Start monitoring this performance counter
  10923. */
  10924. PerfCounter.prototype.beginMonitoring = function () {
  10925. if (!PerfCounter.Enabled) {
  10926. return;
  10927. }
  10928. this._startMonitoringTime = Tools.Now;
  10929. };
  10930. /**
  10931. * Compute the time lapsed since the previous beginMonitoring() call.
  10932. * @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
  10933. */
  10934. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10935. if (newFrame === void 0) { newFrame = true; }
  10936. if (!PerfCounter.Enabled) {
  10937. return;
  10938. }
  10939. if (newFrame) {
  10940. this.fetchNewFrame();
  10941. }
  10942. var currentTime = Tools.Now;
  10943. this._current = currentTime - this._startMonitoringTime;
  10944. if (newFrame) {
  10945. this._fetchResult();
  10946. }
  10947. };
  10948. PerfCounter.prototype._fetchResult = function () {
  10949. this._totalAccumulated += this._current;
  10950. this._lastSecAccumulated += this._current;
  10951. // Min/Max update
  10952. this._min = Math.min(this._min, this._current);
  10953. this._max = Math.max(this._max, this._current);
  10954. this._average = this._totalAccumulated / this._totalValueCount;
  10955. // Reset last sec?
  10956. var now = Tools.Now;
  10957. if ((now - this._lastSecTime) > 1000) {
  10958. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10959. this._lastSecTime = now;
  10960. this._lastSecAccumulated = 0;
  10961. this._lastSecValueCount = 0;
  10962. }
  10963. };
  10964. /**
  10965. * Gets or sets a global boolean to turn on and off all the counters
  10966. */
  10967. PerfCounter.Enabled = true;
  10968. return PerfCounter;
  10969. }());
  10970. BABYLON.PerfCounter = PerfCounter;
  10971. /**
  10972. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10973. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10974. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10975. * @param name The name of the class, case should be preserved
  10976. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10977. */
  10978. function className(name, module) {
  10979. return function (target) {
  10980. target["__bjsclassName__"] = name;
  10981. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10982. };
  10983. }
  10984. BABYLON.className = className;
  10985. /**
  10986. * An implementation of a loop for asynchronous functions.
  10987. */
  10988. var AsyncLoop = /** @class */ (function () {
  10989. /**
  10990. * Constructor.
  10991. * @param iterations the number of iterations.
  10992. * @param func the function to run each iteration
  10993. * @param successCallback the callback that will be called upon succesful execution
  10994. * @param offset starting offset.
  10995. */
  10996. function AsyncLoop(
  10997. /**
  10998. * Defines the number of iterations for the loop
  10999. */
  11000. iterations, func, successCallback, offset) {
  11001. if (offset === void 0) { offset = 0; }
  11002. this.iterations = iterations;
  11003. this.index = offset - 1;
  11004. this._done = false;
  11005. this._fn = func;
  11006. this._successCallback = successCallback;
  11007. }
  11008. /**
  11009. * Execute the next iteration. Must be called after the last iteration was finished.
  11010. */
  11011. AsyncLoop.prototype.executeNext = function () {
  11012. if (!this._done) {
  11013. if (this.index + 1 < this.iterations) {
  11014. ++this.index;
  11015. this._fn(this);
  11016. }
  11017. else {
  11018. this.breakLoop();
  11019. }
  11020. }
  11021. };
  11022. /**
  11023. * Break the loop and run the success callback.
  11024. */
  11025. AsyncLoop.prototype.breakLoop = function () {
  11026. this._done = true;
  11027. this._successCallback();
  11028. };
  11029. /**
  11030. * Create and run an async loop.
  11031. * @param iterations the number of iterations.
  11032. * @param fn the function to run each iteration
  11033. * @param successCallback the callback that will be called upon succesful execution
  11034. * @param offset starting offset.
  11035. * @returns the created async loop object
  11036. */
  11037. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  11038. if (offset === void 0) { offset = 0; }
  11039. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  11040. loop.executeNext();
  11041. return loop;
  11042. };
  11043. /**
  11044. * A for-loop that will run a given number of iterations synchronous and the rest async.
  11045. * @param iterations total number of iterations
  11046. * @param syncedIterations number of synchronous iterations in each async iteration.
  11047. * @param fn the function to call each iteration.
  11048. * @param callback a success call back that will be called when iterating stops.
  11049. * @param breakFunction a break condition (optional)
  11050. * @param timeout timeout settings for the setTimeout function. default - 0.
  11051. * @returns the created async loop object
  11052. */
  11053. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  11054. if (timeout === void 0) { timeout = 0; }
  11055. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  11056. if (breakFunction && breakFunction())
  11057. loop.breakLoop();
  11058. else {
  11059. setTimeout(function () {
  11060. for (var i = 0; i < syncedIterations; ++i) {
  11061. var iteration = (loop.index * syncedIterations) + i;
  11062. if (iteration >= iterations)
  11063. break;
  11064. fn(iteration);
  11065. if (breakFunction && breakFunction()) {
  11066. loop.breakLoop();
  11067. break;
  11068. }
  11069. }
  11070. loop.executeNext();
  11071. }, timeout);
  11072. }
  11073. }, callback);
  11074. };
  11075. return AsyncLoop;
  11076. }());
  11077. BABYLON.AsyncLoop = AsyncLoop;
  11078. })(BABYLON || (BABYLON = {}));
  11079. //# sourceMappingURL=babylon.tools.js.map
  11080. var BABYLON;
  11081. (function (BABYLON) {
  11082. var PromiseStates;
  11083. (function (PromiseStates) {
  11084. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  11085. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  11086. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  11087. })(PromiseStates || (PromiseStates = {}));
  11088. var FulFillmentAgregator = /** @class */ (function () {
  11089. function FulFillmentAgregator() {
  11090. this.count = 0;
  11091. this.target = 0;
  11092. this.results = [];
  11093. }
  11094. return FulFillmentAgregator;
  11095. }());
  11096. var InternalPromise = /** @class */ (function () {
  11097. function InternalPromise(resolver) {
  11098. var _this = this;
  11099. this._state = PromiseStates.Pending;
  11100. this._children = new Array();
  11101. this._rejectWasConsumed = false;
  11102. if (!resolver) {
  11103. return;
  11104. }
  11105. try {
  11106. resolver(function (value) {
  11107. _this._resolve(value);
  11108. }, function (reason) {
  11109. _this._reject(reason);
  11110. });
  11111. }
  11112. catch (e) {
  11113. this._reject(e);
  11114. }
  11115. }
  11116. Object.defineProperty(InternalPromise.prototype, "_result", {
  11117. get: function () {
  11118. return this._resultValue;
  11119. },
  11120. set: function (value) {
  11121. this._resultValue = value;
  11122. if (this._parent && this._parent._result === undefined) {
  11123. this._parent._result = value;
  11124. }
  11125. },
  11126. enumerable: true,
  11127. configurable: true
  11128. });
  11129. InternalPromise.prototype.catch = function (onRejected) {
  11130. return this.then(undefined, onRejected);
  11131. };
  11132. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  11133. var _this = this;
  11134. var newPromise = new InternalPromise();
  11135. newPromise._onFulfilled = onFulfilled;
  11136. newPromise._onRejected = onRejected;
  11137. // Composition
  11138. this._children.push(newPromise);
  11139. newPromise._parent = this;
  11140. if (this._state !== PromiseStates.Pending) {
  11141. BABYLON.Tools.SetImmediate(function () {
  11142. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  11143. var returnedValue = newPromise._resolve(_this._result);
  11144. if (returnedValue !== undefined && returnedValue !== null) {
  11145. if (returnedValue._state !== undefined) {
  11146. var returnedPromise = returnedValue;
  11147. newPromise._children.push(returnedPromise);
  11148. returnedPromise._parent = newPromise;
  11149. newPromise = returnedPromise;
  11150. }
  11151. else {
  11152. newPromise._result = returnedValue;
  11153. }
  11154. }
  11155. }
  11156. else {
  11157. newPromise._reject(_this._reason);
  11158. }
  11159. });
  11160. }
  11161. return newPromise;
  11162. };
  11163. InternalPromise.prototype._moveChildren = function (children) {
  11164. var _this = this;
  11165. var _a;
  11166. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  11167. this._children.forEach(function (child) {
  11168. child._parent = _this;
  11169. });
  11170. if (this._state === PromiseStates.Fulfilled) {
  11171. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  11172. var child = _b[_i];
  11173. child._resolve(this._result);
  11174. }
  11175. }
  11176. else if (this._state === PromiseStates.Rejected) {
  11177. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  11178. var child = _d[_c];
  11179. child._reject(this._reason);
  11180. }
  11181. }
  11182. };
  11183. InternalPromise.prototype._resolve = function (value) {
  11184. try {
  11185. this._state = PromiseStates.Fulfilled;
  11186. var returnedValue = null;
  11187. if (this._onFulfilled) {
  11188. returnedValue = this._onFulfilled(value);
  11189. }
  11190. if (returnedValue !== undefined && returnedValue !== null) {
  11191. if (returnedValue._state !== undefined) {
  11192. // Transmit children
  11193. var returnedPromise = returnedValue;
  11194. returnedPromise._parent = this;
  11195. returnedPromise._moveChildren(this._children);
  11196. value = returnedPromise._result;
  11197. }
  11198. else {
  11199. value = returnedValue;
  11200. }
  11201. }
  11202. this._result = value;
  11203. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11204. var child = _a[_i];
  11205. child._resolve(value);
  11206. }
  11207. this._children.length = 0;
  11208. delete this._onFulfilled;
  11209. delete this._onRejected;
  11210. }
  11211. catch (e) {
  11212. this._reject(e, true);
  11213. }
  11214. };
  11215. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  11216. if (onLocalThrow === void 0) { onLocalThrow = false; }
  11217. this._state = PromiseStates.Rejected;
  11218. this._reason = reason;
  11219. if (this._onRejected && !onLocalThrow) {
  11220. try {
  11221. this._onRejected(reason);
  11222. this._rejectWasConsumed = true;
  11223. }
  11224. catch (e) {
  11225. reason = e;
  11226. }
  11227. }
  11228. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11229. var child = _a[_i];
  11230. if (this._rejectWasConsumed) {
  11231. child._resolve(null);
  11232. }
  11233. else {
  11234. child._reject(reason);
  11235. }
  11236. }
  11237. this._children.length = 0;
  11238. delete this._onFulfilled;
  11239. delete this._onRejected;
  11240. };
  11241. InternalPromise.resolve = function (value) {
  11242. var newPromise = new InternalPromise();
  11243. newPromise._resolve(value);
  11244. return newPromise;
  11245. };
  11246. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  11247. promise.then(function (value) {
  11248. agregator.results[index] = value;
  11249. agregator.count++;
  11250. if (agregator.count === agregator.target) {
  11251. agregator.rootPromise._resolve(agregator.results);
  11252. }
  11253. return null;
  11254. }, function (reason) {
  11255. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  11256. agregator.rootPromise._reject(reason);
  11257. }
  11258. });
  11259. };
  11260. InternalPromise.all = function (promises) {
  11261. var newPromise = new InternalPromise();
  11262. var agregator = new FulFillmentAgregator();
  11263. agregator.target = promises.length;
  11264. agregator.rootPromise = newPromise;
  11265. if (promises.length) {
  11266. for (var index = 0; index < promises.length; index++) {
  11267. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  11268. }
  11269. }
  11270. else {
  11271. newPromise._resolve([]);
  11272. }
  11273. return newPromise;
  11274. };
  11275. InternalPromise.race = function (promises) {
  11276. var newPromise = new InternalPromise();
  11277. if (promises.length) {
  11278. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  11279. var promise = promises_1[_i];
  11280. promise.then(function (value) {
  11281. if (newPromise) {
  11282. newPromise._resolve(value);
  11283. newPromise = null;
  11284. }
  11285. return null;
  11286. }, function (reason) {
  11287. if (newPromise) {
  11288. newPromise._reject(reason);
  11289. newPromise = null;
  11290. }
  11291. });
  11292. }
  11293. }
  11294. return newPromise;
  11295. };
  11296. return InternalPromise;
  11297. }());
  11298. /**
  11299. * Helper class that provides a small promise polyfill
  11300. */
  11301. var PromisePolyfill = /** @class */ (function () {
  11302. function PromisePolyfill() {
  11303. }
  11304. /**
  11305. * Static function used to check if the polyfill is required
  11306. * If this is the case then the function will inject the polyfill to window.Promise
  11307. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  11308. */
  11309. PromisePolyfill.Apply = function (force) {
  11310. if (force === void 0) { force = false; }
  11311. if (force || typeof Promise === 'undefined') {
  11312. var root = window;
  11313. root.Promise = InternalPromise;
  11314. }
  11315. };
  11316. return PromisePolyfill;
  11317. }());
  11318. BABYLON.PromisePolyfill = PromisePolyfill;
  11319. })(BABYLON || (BABYLON = {}));
  11320. //# sourceMappingURL=babylon.promise.js.map
  11321. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  11322. var BABYLON;
  11323. (function (BABYLON) {
  11324. /**
  11325. * Helper class to push actions to a pool of workers.
  11326. */
  11327. var WorkerPool = /** @class */ (function () {
  11328. /**
  11329. * Constructor
  11330. * @param workers Array of workers to use for actions
  11331. */
  11332. function WorkerPool(workers) {
  11333. this._pendingActions = new Array();
  11334. this._workerInfos = workers.map(function (worker) { return ({
  11335. worker: worker,
  11336. active: false
  11337. }); });
  11338. }
  11339. /**
  11340. * Terminates all workers and clears any pending actions.
  11341. */
  11342. WorkerPool.prototype.dispose = function () {
  11343. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11344. var workerInfo = _a[_i];
  11345. workerInfo.worker.terminate();
  11346. }
  11347. delete this._workerInfos;
  11348. delete this._pendingActions;
  11349. };
  11350. /**
  11351. * Pushes an action to the worker pool. If all the workers are active, the action will be
  11352. * pended until a worker has completed its action.
  11353. * @param action The action to perform. Call onComplete when the action is complete.
  11354. */
  11355. WorkerPool.prototype.push = function (action) {
  11356. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11357. var workerInfo = _a[_i];
  11358. if (!workerInfo.active) {
  11359. this._execute(workerInfo, action);
  11360. return;
  11361. }
  11362. }
  11363. this._pendingActions.push(action);
  11364. };
  11365. WorkerPool.prototype._execute = function (workerInfo, action) {
  11366. var _this = this;
  11367. workerInfo.active = true;
  11368. action(workerInfo.worker, function () {
  11369. workerInfo.active = false;
  11370. var nextAction = _this._pendingActions.shift();
  11371. if (nextAction) {
  11372. _this._execute(workerInfo, nextAction);
  11373. }
  11374. });
  11375. };
  11376. return WorkerPool;
  11377. }());
  11378. BABYLON.WorkerPool = WorkerPool;
  11379. })(BABYLON || (BABYLON = {}));
  11380. //# sourceMappingURL=babylon.workerPool.js.map
  11381. var BABYLON;
  11382. (function (BABYLON) {
  11383. /**
  11384. * @hidden
  11385. **/
  11386. var _AlphaState = /** @class */ (function () {
  11387. /**
  11388. * Initializes the state.
  11389. */
  11390. function _AlphaState() {
  11391. this._isAlphaBlendDirty = false;
  11392. this._isBlendFunctionParametersDirty = false;
  11393. this._isBlendEquationParametersDirty = false;
  11394. this._isBlendConstantsDirty = false;
  11395. this._alphaBlend = false;
  11396. this._blendFunctionParameters = new Array(4);
  11397. this._blendEquationParameters = new Array(2);
  11398. this._blendConstants = new Array(4);
  11399. this.reset();
  11400. }
  11401. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  11402. get: function () {
  11403. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  11404. },
  11405. enumerable: true,
  11406. configurable: true
  11407. });
  11408. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  11409. get: function () {
  11410. return this._alphaBlend;
  11411. },
  11412. set: function (value) {
  11413. if (this._alphaBlend === value) {
  11414. return;
  11415. }
  11416. this._alphaBlend = value;
  11417. this._isAlphaBlendDirty = true;
  11418. },
  11419. enumerable: true,
  11420. configurable: true
  11421. });
  11422. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  11423. if (this._blendConstants[0] === r &&
  11424. this._blendConstants[1] === g &&
  11425. this._blendConstants[2] === b &&
  11426. this._blendConstants[3] === a) {
  11427. return;
  11428. }
  11429. this._blendConstants[0] = r;
  11430. this._blendConstants[1] = g;
  11431. this._blendConstants[2] = b;
  11432. this._blendConstants[3] = a;
  11433. this._isBlendConstantsDirty = true;
  11434. };
  11435. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  11436. if (this._blendFunctionParameters[0] === value0 &&
  11437. this._blendFunctionParameters[1] === value1 &&
  11438. this._blendFunctionParameters[2] === value2 &&
  11439. this._blendFunctionParameters[3] === value3) {
  11440. return;
  11441. }
  11442. this._blendFunctionParameters[0] = value0;
  11443. this._blendFunctionParameters[1] = value1;
  11444. this._blendFunctionParameters[2] = value2;
  11445. this._blendFunctionParameters[3] = value3;
  11446. this._isBlendFunctionParametersDirty = true;
  11447. };
  11448. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  11449. if (this._blendEquationParameters[0] === rgb &&
  11450. this._blendEquationParameters[1] === alpha) {
  11451. return;
  11452. }
  11453. this._blendEquationParameters[0] = rgb;
  11454. this._blendEquationParameters[1] = alpha;
  11455. this._isBlendEquationParametersDirty = true;
  11456. };
  11457. _AlphaState.prototype.reset = function () {
  11458. this._alphaBlend = false;
  11459. this._blendFunctionParameters[0] = null;
  11460. this._blendFunctionParameters[1] = null;
  11461. this._blendFunctionParameters[2] = null;
  11462. this._blendFunctionParameters[3] = null;
  11463. this._blendEquationParameters[0] = null;
  11464. this._blendEquationParameters[1] = null;
  11465. this._blendConstants[0] = null;
  11466. this._blendConstants[1] = null;
  11467. this._blendConstants[2] = null;
  11468. this._blendConstants[3] = null;
  11469. this._isAlphaBlendDirty = true;
  11470. this._isBlendFunctionParametersDirty = false;
  11471. this._isBlendEquationParametersDirty = false;
  11472. this._isBlendConstantsDirty = false;
  11473. };
  11474. _AlphaState.prototype.apply = function (gl) {
  11475. if (!this.isDirty) {
  11476. return;
  11477. }
  11478. // Alpha blend
  11479. if (this._isAlphaBlendDirty) {
  11480. if (this._alphaBlend) {
  11481. gl.enable(gl.BLEND);
  11482. }
  11483. else {
  11484. gl.disable(gl.BLEND);
  11485. }
  11486. this._isAlphaBlendDirty = false;
  11487. }
  11488. // Alpha function
  11489. if (this._isBlendFunctionParametersDirty) {
  11490. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11491. this._isBlendFunctionParametersDirty = false;
  11492. }
  11493. // Alpha equation
  11494. if (this._isBlendEquationParametersDirty) {
  11495. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11496. this._isBlendEquationParametersDirty = false;
  11497. }
  11498. // Constants
  11499. if (this._isBlendConstantsDirty) {
  11500. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11501. this._isBlendConstantsDirty = false;
  11502. }
  11503. };
  11504. return _AlphaState;
  11505. }());
  11506. BABYLON._AlphaState = _AlphaState;
  11507. })(BABYLON || (BABYLON = {}));
  11508. //# sourceMappingURL=babylon.alphaCullingState.js.map
  11509. var BABYLON;
  11510. (function (BABYLON) {
  11511. /**
  11512. * @hidden
  11513. **/
  11514. var _DepthCullingState = /** @class */ (function () {
  11515. /**
  11516. * Initializes the state.
  11517. */
  11518. function _DepthCullingState() {
  11519. this._isDepthTestDirty = false;
  11520. this._isDepthMaskDirty = false;
  11521. this._isDepthFuncDirty = false;
  11522. this._isCullFaceDirty = false;
  11523. this._isCullDirty = false;
  11524. this._isZOffsetDirty = false;
  11525. this._isFrontFaceDirty = false;
  11526. this.reset();
  11527. }
  11528. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11529. get: function () {
  11530. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11531. },
  11532. enumerable: true,
  11533. configurable: true
  11534. });
  11535. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11536. get: function () {
  11537. return this._zOffset;
  11538. },
  11539. set: function (value) {
  11540. if (this._zOffset === value) {
  11541. return;
  11542. }
  11543. this._zOffset = value;
  11544. this._isZOffsetDirty = true;
  11545. },
  11546. enumerable: true,
  11547. configurable: true
  11548. });
  11549. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11550. get: function () {
  11551. return this._cullFace;
  11552. },
  11553. set: function (value) {
  11554. if (this._cullFace === value) {
  11555. return;
  11556. }
  11557. this._cullFace = value;
  11558. this._isCullFaceDirty = true;
  11559. },
  11560. enumerable: true,
  11561. configurable: true
  11562. });
  11563. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11564. get: function () {
  11565. return this._cull;
  11566. },
  11567. set: function (value) {
  11568. if (this._cull === value) {
  11569. return;
  11570. }
  11571. this._cull = value;
  11572. this._isCullDirty = true;
  11573. },
  11574. enumerable: true,
  11575. configurable: true
  11576. });
  11577. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11578. get: function () {
  11579. return this._depthFunc;
  11580. },
  11581. set: function (value) {
  11582. if (this._depthFunc === value) {
  11583. return;
  11584. }
  11585. this._depthFunc = value;
  11586. this._isDepthFuncDirty = true;
  11587. },
  11588. enumerable: true,
  11589. configurable: true
  11590. });
  11591. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11592. get: function () {
  11593. return this._depthMask;
  11594. },
  11595. set: function (value) {
  11596. if (this._depthMask === value) {
  11597. return;
  11598. }
  11599. this._depthMask = value;
  11600. this._isDepthMaskDirty = true;
  11601. },
  11602. enumerable: true,
  11603. configurable: true
  11604. });
  11605. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11606. get: function () {
  11607. return this._depthTest;
  11608. },
  11609. set: function (value) {
  11610. if (this._depthTest === value) {
  11611. return;
  11612. }
  11613. this._depthTest = value;
  11614. this._isDepthTestDirty = true;
  11615. },
  11616. enumerable: true,
  11617. configurable: true
  11618. });
  11619. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11620. get: function () {
  11621. return this._frontFace;
  11622. },
  11623. set: function (value) {
  11624. if (this._frontFace === value) {
  11625. return;
  11626. }
  11627. this._frontFace = value;
  11628. this._isFrontFaceDirty = true;
  11629. },
  11630. enumerable: true,
  11631. configurable: true
  11632. });
  11633. _DepthCullingState.prototype.reset = function () {
  11634. this._depthMask = true;
  11635. this._depthTest = true;
  11636. this._depthFunc = null;
  11637. this._cullFace = null;
  11638. this._cull = null;
  11639. this._zOffset = 0;
  11640. this._frontFace = null;
  11641. this._isDepthTestDirty = true;
  11642. this._isDepthMaskDirty = true;
  11643. this._isDepthFuncDirty = false;
  11644. this._isCullFaceDirty = false;
  11645. this._isCullDirty = false;
  11646. this._isZOffsetDirty = false;
  11647. this._isFrontFaceDirty = false;
  11648. };
  11649. _DepthCullingState.prototype.apply = function (gl) {
  11650. if (!this.isDirty) {
  11651. return;
  11652. }
  11653. // Cull
  11654. if (this._isCullDirty) {
  11655. if (this.cull) {
  11656. gl.enable(gl.CULL_FACE);
  11657. }
  11658. else {
  11659. gl.disable(gl.CULL_FACE);
  11660. }
  11661. this._isCullDirty = false;
  11662. }
  11663. // Cull face
  11664. if (this._isCullFaceDirty) {
  11665. gl.cullFace(this.cullFace);
  11666. this._isCullFaceDirty = false;
  11667. }
  11668. // Depth mask
  11669. if (this._isDepthMaskDirty) {
  11670. gl.depthMask(this.depthMask);
  11671. this._isDepthMaskDirty = false;
  11672. }
  11673. // Depth test
  11674. if (this._isDepthTestDirty) {
  11675. if (this.depthTest) {
  11676. gl.enable(gl.DEPTH_TEST);
  11677. }
  11678. else {
  11679. gl.disable(gl.DEPTH_TEST);
  11680. }
  11681. this._isDepthTestDirty = false;
  11682. }
  11683. // Depth func
  11684. if (this._isDepthFuncDirty) {
  11685. gl.depthFunc(this.depthFunc);
  11686. this._isDepthFuncDirty = false;
  11687. }
  11688. // zOffset
  11689. if (this._isZOffsetDirty) {
  11690. if (this.zOffset) {
  11691. gl.enable(gl.POLYGON_OFFSET_FILL);
  11692. gl.polygonOffset(this.zOffset, 0);
  11693. }
  11694. else {
  11695. gl.disable(gl.POLYGON_OFFSET_FILL);
  11696. }
  11697. this._isZOffsetDirty = false;
  11698. }
  11699. // Front face
  11700. if (this._isFrontFaceDirty) {
  11701. gl.frontFace(this.frontFace);
  11702. this._isFrontFaceDirty = false;
  11703. }
  11704. };
  11705. return _DepthCullingState;
  11706. }());
  11707. BABYLON._DepthCullingState = _DepthCullingState;
  11708. })(BABYLON || (BABYLON = {}));
  11709. //# sourceMappingURL=babylon.depthCullingState.js.map
  11710. var BABYLON;
  11711. (function (BABYLON) {
  11712. /**
  11713. * @hidden
  11714. **/
  11715. var _StencilState = /** @class */ (function () {
  11716. function _StencilState() {
  11717. this._isStencilTestDirty = false;
  11718. this._isStencilMaskDirty = false;
  11719. this._isStencilFuncDirty = false;
  11720. this._isStencilOpDirty = false;
  11721. this.reset();
  11722. }
  11723. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11724. get: function () {
  11725. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11726. },
  11727. enumerable: true,
  11728. configurable: true
  11729. });
  11730. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11731. get: function () {
  11732. return this._stencilFunc;
  11733. },
  11734. set: function (value) {
  11735. if (this._stencilFunc === value) {
  11736. return;
  11737. }
  11738. this._stencilFunc = value;
  11739. this._isStencilFuncDirty = true;
  11740. },
  11741. enumerable: true,
  11742. configurable: true
  11743. });
  11744. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11745. get: function () {
  11746. return this._stencilFuncRef;
  11747. },
  11748. set: function (value) {
  11749. if (this._stencilFuncRef === value) {
  11750. return;
  11751. }
  11752. this._stencilFuncRef = value;
  11753. this._isStencilFuncDirty = true;
  11754. },
  11755. enumerable: true,
  11756. configurable: true
  11757. });
  11758. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11759. get: function () {
  11760. return this._stencilFuncMask;
  11761. },
  11762. set: function (value) {
  11763. if (this._stencilFuncMask === value) {
  11764. return;
  11765. }
  11766. this._stencilFuncMask = value;
  11767. this._isStencilFuncDirty = true;
  11768. },
  11769. enumerable: true,
  11770. configurable: true
  11771. });
  11772. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11773. get: function () {
  11774. return this._stencilOpStencilFail;
  11775. },
  11776. set: function (value) {
  11777. if (this._stencilOpStencilFail === value) {
  11778. return;
  11779. }
  11780. this._stencilOpStencilFail = value;
  11781. this._isStencilOpDirty = true;
  11782. },
  11783. enumerable: true,
  11784. configurable: true
  11785. });
  11786. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11787. get: function () {
  11788. return this._stencilOpDepthFail;
  11789. },
  11790. set: function (value) {
  11791. if (this._stencilOpDepthFail === value) {
  11792. return;
  11793. }
  11794. this._stencilOpDepthFail = value;
  11795. this._isStencilOpDirty = true;
  11796. },
  11797. enumerable: true,
  11798. configurable: true
  11799. });
  11800. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11801. get: function () {
  11802. return this._stencilOpStencilDepthPass;
  11803. },
  11804. set: function (value) {
  11805. if (this._stencilOpStencilDepthPass === value) {
  11806. return;
  11807. }
  11808. this._stencilOpStencilDepthPass = value;
  11809. this._isStencilOpDirty = true;
  11810. },
  11811. enumerable: true,
  11812. configurable: true
  11813. });
  11814. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11815. get: function () {
  11816. return this._stencilMask;
  11817. },
  11818. set: function (value) {
  11819. if (this._stencilMask === value) {
  11820. return;
  11821. }
  11822. this._stencilMask = value;
  11823. this._isStencilMaskDirty = true;
  11824. },
  11825. enumerable: true,
  11826. configurable: true
  11827. });
  11828. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11829. get: function () {
  11830. return this._stencilTest;
  11831. },
  11832. set: function (value) {
  11833. if (this._stencilTest === value) {
  11834. return;
  11835. }
  11836. this._stencilTest = value;
  11837. this._isStencilTestDirty = true;
  11838. },
  11839. enumerable: true,
  11840. configurable: true
  11841. });
  11842. _StencilState.prototype.reset = function () {
  11843. this._stencilTest = false;
  11844. this._stencilMask = 0xFF;
  11845. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11846. this._stencilFuncRef = 1;
  11847. this._stencilFuncMask = 0xFF;
  11848. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11849. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11850. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11851. this._isStencilTestDirty = true;
  11852. this._isStencilMaskDirty = true;
  11853. this._isStencilFuncDirty = true;
  11854. this._isStencilOpDirty = true;
  11855. };
  11856. _StencilState.prototype.apply = function (gl) {
  11857. if (!this.isDirty) {
  11858. return;
  11859. }
  11860. // Stencil test
  11861. if (this._isStencilTestDirty) {
  11862. if (this.stencilTest) {
  11863. gl.enable(gl.STENCIL_TEST);
  11864. }
  11865. else {
  11866. gl.disable(gl.STENCIL_TEST);
  11867. }
  11868. this._isStencilTestDirty = false;
  11869. }
  11870. // Stencil mask
  11871. if (this._isStencilMaskDirty) {
  11872. gl.stencilMask(this.stencilMask);
  11873. this._isStencilMaskDirty = false;
  11874. }
  11875. // Stencil func
  11876. if (this._isStencilFuncDirty) {
  11877. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11878. this._isStencilFuncDirty = false;
  11879. }
  11880. // Stencil op
  11881. if (this._isStencilOpDirty) {
  11882. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11883. this._isStencilOpDirty = false;
  11884. }
  11885. };
  11886. return _StencilState;
  11887. }());
  11888. BABYLON._StencilState = _StencilState;
  11889. })(BABYLON || (BABYLON = {}));
  11890. //# sourceMappingURL=babylon.stencilState.js.map
  11891. var __assign = (this && this.__assign) || function () {
  11892. __assign = Object.assign || function(t) {
  11893. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11894. s = arguments[i];
  11895. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11896. t[p] = s[p];
  11897. }
  11898. return t;
  11899. };
  11900. return __assign.apply(this, arguments);
  11901. };
  11902. var BABYLON;
  11903. (function (BABYLON) {
  11904. /**
  11905. * Keeps track of all the buffer info used in engine.
  11906. */
  11907. var BufferPointer = /** @class */ (function () {
  11908. function BufferPointer() {
  11909. }
  11910. return BufferPointer;
  11911. }());
  11912. /**
  11913. * Interface for attribute information associated with buffer instanciation
  11914. */
  11915. var InstancingAttributeInfo = /** @class */ (function () {
  11916. function InstancingAttributeInfo() {
  11917. }
  11918. return InstancingAttributeInfo;
  11919. }());
  11920. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11921. /**
  11922. * Define options used to create a render target texture
  11923. */
  11924. var RenderTargetCreationOptions = /** @class */ (function () {
  11925. function RenderTargetCreationOptions() {
  11926. }
  11927. return RenderTargetCreationOptions;
  11928. }());
  11929. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11930. /**
  11931. * Define options used to create a depth texture
  11932. */
  11933. var DepthTextureCreationOptions = /** @class */ (function () {
  11934. function DepthTextureCreationOptions() {
  11935. }
  11936. return DepthTextureCreationOptions;
  11937. }());
  11938. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11939. /**
  11940. * Class used to describe the capabilities of the engine relatively to the current browser
  11941. */
  11942. var EngineCapabilities = /** @class */ (function () {
  11943. function EngineCapabilities() {
  11944. }
  11945. return EngineCapabilities;
  11946. }());
  11947. BABYLON.EngineCapabilities = EngineCapabilities;
  11948. /**
  11949. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11950. */
  11951. var Engine = /** @class */ (function () {
  11952. /**
  11953. * Creates a new engine
  11954. * @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
  11955. * @param antialias defines enable antialiasing (default: false)
  11956. * @param options defines further options to be sent to the getContext() function
  11957. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11958. */
  11959. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11960. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11961. var _this = this;
  11962. // Public members
  11963. /**
  11964. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11965. */
  11966. this.forcePOTTextures = false;
  11967. /**
  11968. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11969. */
  11970. this.isFullscreen = false;
  11971. /**
  11972. * Gets a boolean indicating if the pointer is currently locked
  11973. */
  11974. this.isPointerLock = false;
  11975. /**
  11976. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11977. */
  11978. this.cullBackFaces = true;
  11979. /**
  11980. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11981. */
  11982. this.renderEvenInBackground = true;
  11983. /**
  11984. * Gets or sets a boolean indicating that cache can be kept between frames
  11985. */
  11986. this.preventCacheWipeBetweenFrames = false;
  11987. /**
  11988. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11989. **/
  11990. this.enableOfflineSupport = false;
  11991. /**
  11992. * 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)
  11993. **/
  11994. this.disableManifestCheck = false;
  11995. /**
  11996. * Gets the list of created scenes
  11997. */
  11998. this.scenes = new Array();
  11999. /**
  12000. * Gets the list of created postprocesses
  12001. */
  12002. this.postProcesses = new Array();
  12003. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  12004. this.validateShaderPrograms = false;
  12005. // Observables
  12006. /**
  12007. * Observable event triggered each time the rendering canvas is resized
  12008. */
  12009. this.onResizeObservable = new BABYLON.Observable();
  12010. /**
  12011. * Observable event triggered each time the canvas loses focus
  12012. */
  12013. this.onCanvasBlurObservable = new BABYLON.Observable();
  12014. /**
  12015. * Observable event triggered each time the canvas gains focus
  12016. */
  12017. this.onCanvasFocusObservable = new BABYLON.Observable();
  12018. /**
  12019. * Observable event triggered each time the canvas receives pointerout event
  12020. */
  12021. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  12022. /**
  12023. * Observable event triggered before each texture is initialized
  12024. */
  12025. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  12026. //WebVR
  12027. this._vrDisplay = undefined;
  12028. this._vrSupported = false;
  12029. this._vrExclusivePointerMode = false;
  12030. // Uniform buffers list
  12031. /**
  12032. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  12033. */
  12034. this.disableUniformBuffers = false;
  12035. /** @hidden */
  12036. this._uniformBuffers = new Array();
  12037. // Observables
  12038. /**
  12039. * Observable raised when the engine begins a new frame
  12040. */
  12041. this.onBeginFrameObservable = new BABYLON.Observable();
  12042. /**
  12043. * Observable raised when the engine ends the current frame
  12044. */
  12045. this.onEndFrameObservable = new BABYLON.Observable();
  12046. /**
  12047. * Observable raised when the engine is about to compile a shader
  12048. */
  12049. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  12050. /**
  12051. * Observable raised when the engine has jsut compiled a shader
  12052. */
  12053. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  12054. this._windowIsBackground = false;
  12055. this._webGLVersion = 1.0;
  12056. /** @hidden */
  12057. this._badOS = false;
  12058. /** @hidden */
  12059. this._badDesktopOS = false;
  12060. /**
  12061. * Gets or sets a value indicating if we want to disable texture binding optmization.
  12062. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  12063. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  12064. */
  12065. this.disableTextureBindingOptimization = false;
  12066. /**
  12067. * Observable signaled when VR display mode changes
  12068. */
  12069. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  12070. /**
  12071. * Observable signaled when VR request present is complete
  12072. */
  12073. this.onVRRequestPresentComplete = new BABYLON.Observable();
  12074. /**
  12075. * Observable signaled when VR request present starts
  12076. */
  12077. this.onVRRequestPresentStart = new BABYLON.Observable();
  12078. this._colorWrite = true;
  12079. /** @hidden */
  12080. this._drawCalls = new BABYLON.PerfCounter();
  12081. /** @hidden */
  12082. this._textureCollisions = new BABYLON.PerfCounter();
  12083. this._renderingQueueLaunched = false;
  12084. this._activeRenderLoops = new Array();
  12085. // Deterministic lockstepMaxSteps
  12086. this._deterministicLockstep = false;
  12087. this._lockstepMaxSteps = 4;
  12088. // Lost context
  12089. /**
  12090. * Observable signaled when a context lost event is raised
  12091. */
  12092. this.onContextLostObservable = new BABYLON.Observable();
  12093. /**
  12094. * Observable signaled when a context restored event is raised
  12095. */
  12096. this.onContextRestoredObservable = new BABYLON.Observable();
  12097. this._contextWasLost = false;
  12098. this._doNotHandleContextLost = false;
  12099. // FPS
  12100. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  12101. this._fps = 60;
  12102. this._deltaTime = 0;
  12103. /**
  12104. * Turn this value on if you want to pause FPS computation when in background
  12105. */
  12106. this.disablePerformanceMonitorInBackground = false;
  12107. // States
  12108. /** @hidden */
  12109. this._depthCullingState = new BABYLON._DepthCullingState();
  12110. /** @hidden */
  12111. this._stencilState = new BABYLON._StencilState();
  12112. /** @hidden */
  12113. this._alphaState = new BABYLON._AlphaState();
  12114. /** @hidden */
  12115. this._alphaMode = Engine.ALPHA_DISABLE;
  12116. // Cache
  12117. this._internalTexturesCache = new Array();
  12118. /** @hidden */
  12119. this._activeChannel = 0;
  12120. this._currentTextureChannel = -1;
  12121. /** @hidden */
  12122. this._boundTexturesCache = {};
  12123. this._compiledEffects = {};
  12124. this._vertexAttribArraysEnabled = [];
  12125. this._uintIndicesCurrentlySet = false;
  12126. this._currentBoundBuffer = new Array();
  12127. /** @hidden */
  12128. this._currentFramebuffer = null;
  12129. this._currentBufferPointers = new Array();
  12130. this._currentInstanceLocations = new Array();
  12131. this._currentInstanceBuffers = new Array();
  12132. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12133. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12134. this._vaoRecordInProgress = false;
  12135. this._mustWipeVertexAttributes = false;
  12136. this._nextFreeTextureSlots = new Array();
  12137. this._maxSimultaneousTextures = 0;
  12138. this._activeRequests = new Array();
  12139. // Hardware supported Compressed Textures
  12140. this._texturesSupported = new Array();
  12141. /**
  12142. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  12143. */
  12144. this.premultipliedAlpha = true;
  12145. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  12146. this._onVRFullScreenTriggered = function () {
  12147. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  12148. //get the old size before we change
  12149. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  12150. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  12151. //get the width and height, change the render size
  12152. var leftEye = _this._vrDisplay.getEyeParameters('left');
  12153. _this.setHardwareScalingLevel(1);
  12154. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  12155. }
  12156. else {
  12157. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  12158. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  12159. }
  12160. };
  12161. this._unpackFlipYCached = null;
  12162. /**
  12163. * In case you are sharing the context with other applications, it might
  12164. * be interested to not cache the unpack flip y state to ensure a consistent
  12165. * value would be set.
  12166. */
  12167. this.enableUnpackFlipYCached = true;
  12168. this._boundUniforms = {};
  12169. // Register promises
  12170. BABYLON.PromisePolyfill.Apply();
  12171. var canvas = null;
  12172. Engine.Instances.push(this);
  12173. if (!canvasOrContext) {
  12174. return;
  12175. }
  12176. options = options || {};
  12177. if (canvasOrContext.getContext) {
  12178. canvas = canvasOrContext;
  12179. this._renderingCanvas = canvas;
  12180. if (antialias != null) {
  12181. options.antialias = antialias;
  12182. }
  12183. if (options.deterministicLockstep === undefined) {
  12184. options.deterministicLockstep = false;
  12185. }
  12186. if (options.lockstepMaxSteps === undefined) {
  12187. options.lockstepMaxSteps = 4;
  12188. }
  12189. if (options.preserveDrawingBuffer === undefined) {
  12190. options.preserveDrawingBuffer = false;
  12191. }
  12192. if (options.audioEngine === undefined) {
  12193. options.audioEngine = true;
  12194. }
  12195. if (options.stencil === undefined) {
  12196. options.stencil = true;
  12197. }
  12198. if (options.premultipliedAlpha === false) {
  12199. this.premultipliedAlpha = false;
  12200. }
  12201. this._deterministicLockstep = options.deterministicLockstep;
  12202. this._lockstepMaxSteps = options.lockstepMaxSteps;
  12203. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  12204. // Exceptions
  12205. if (navigator && navigator.userAgent) {
  12206. var ua = navigator.userAgent;
  12207. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  12208. var exception = _a[_i];
  12209. var key = exception.key;
  12210. var targets = exception.targets;
  12211. if (ua.indexOf(key) > -1) {
  12212. if (exception.capture && exception.captureConstraint) {
  12213. var capture = exception.capture;
  12214. var constraint = exception.captureConstraint;
  12215. var regex = new RegExp(capture);
  12216. var matches = regex.exec(ua);
  12217. if (matches && matches.length > 0) {
  12218. var capturedValue = parseInt(matches[matches.length - 1]);
  12219. if (capturedValue >= constraint) {
  12220. continue;
  12221. }
  12222. }
  12223. }
  12224. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  12225. var target = targets_1[_b];
  12226. switch (target) {
  12227. case "uniformBuffer":
  12228. this.disableUniformBuffers = true;
  12229. break;
  12230. case "textureBindingOptimization":
  12231. this.disableTextureBindingOptimization = true;
  12232. break;
  12233. }
  12234. }
  12235. }
  12236. }
  12237. }
  12238. // GL
  12239. if (!options.disableWebGL2Support) {
  12240. try {
  12241. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  12242. if (this._gl) {
  12243. this._webGLVersion = 2.0;
  12244. }
  12245. }
  12246. catch (e) {
  12247. // Do nothing
  12248. }
  12249. }
  12250. if (!this._gl) {
  12251. if (!canvas) {
  12252. throw new Error("The provided canvas is null or undefined.");
  12253. }
  12254. try {
  12255. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  12256. }
  12257. catch (e) {
  12258. throw new Error("WebGL not supported");
  12259. }
  12260. }
  12261. if (!this._gl) {
  12262. throw new Error("WebGL not supported");
  12263. }
  12264. this._onCanvasFocus = function () {
  12265. _this.onCanvasFocusObservable.notifyObservers(_this);
  12266. };
  12267. this._onCanvasBlur = function () {
  12268. _this.onCanvasBlurObservable.notifyObservers(_this);
  12269. };
  12270. canvas.addEventListener("focus", this._onCanvasFocus);
  12271. canvas.addEventListener("blur", this._onCanvasBlur);
  12272. this._onBlur = function () {
  12273. if (_this.disablePerformanceMonitorInBackground) {
  12274. _this._performanceMonitor.disable();
  12275. }
  12276. _this._windowIsBackground = true;
  12277. };
  12278. this._onFocus = function () {
  12279. if (_this.disablePerformanceMonitorInBackground) {
  12280. _this._performanceMonitor.enable();
  12281. }
  12282. _this._windowIsBackground = false;
  12283. };
  12284. this._onCanvasPointerOut = function (ev) {
  12285. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  12286. };
  12287. window.addEventListener("blur", this._onBlur);
  12288. window.addEventListener("focus", this._onFocus);
  12289. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  12290. // Context lost
  12291. if (!this._doNotHandleContextLost) {
  12292. this._onContextLost = function (evt) {
  12293. evt.preventDefault();
  12294. _this._contextWasLost = true;
  12295. BABYLON.Tools.Warn("WebGL context lost.");
  12296. _this.onContextLostObservable.notifyObservers(_this);
  12297. };
  12298. this._onContextRestored = function (evt) {
  12299. // Adding a timeout to avoid race condition at browser level
  12300. setTimeout(function () {
  12301. // Rebuild gl context
  12302. _this._initGLContext();
  12303. // Rebuild effects
  12304. _this._rebuildEffects();
  12305. // Rebuild textures
  12306. _this._rebuildInternalTextures();
  12307. // Rebuild buffers
  12308. _this._rebuildBuffers();
  12309. // Cache
  12310. _this.wipeCaches(true);
  12311. BABYLON.Tools.Warn("WebGL context successfully restored.");
  12312. _this.onContextRestoredObservable.notifyObservers(_this);
  12313. _this._contextWasLost = false;
  12314. }, 0);
  12315. };
  12316. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  12317. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  12318. }
  12319. }
  12320. else {
  12321. this._gl = canvasOrContext;
  12322. this._renderingCanvas = this._gl.canvas;
  12323. if (this._gl.renderbufferStorageMultisample) {
  12324. this._webGLVersion = 2.0;
  12325. }
  12326. options.stencil = this._gl.getContextAttributes().stencil;
  12327. }
  12328. // Viewport
  12329. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  12330. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  12331. this.resize();
  12332. this._isStencilEnable = options.stencil ? true : false;
  12333. this._initGLContext();
  12334. if (canvas) {
  12335. // Fullscreen
  12336. this._onFullscreenChange = function () {
  12337. if (document.fullscreen !== undefined) {
  12338. _this.isFullscreen = document.fullscreen;
  12339. }
  12340. else if (document.mozFullScreen !== undefined) {
  12341. _this.isFullscreen = document.mozFullScreen;
  12342. }
  12343. else if (document.webkitIsFullScreen !== undefined) {
  12344. _this.isFullscreen = document.webkitIsFullScreen;
  12345. }
  12346. else if (document.msIsFullScreen !== undefined) {
  12347. _this.isFullscreen = document.msIsFullScreen;
  12348. }
  12349. // Pointer lock
  12350. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  12351. canvas.requestPointerLock = canvas.requestPointerLock ||
  12352. canvas.msRequestPointerLock ||
  12353. canvas.mozRequestPointerLock ||
  12354. canvas.webkitRequestPointerLock;
  12355. if (canvas.requestPointerLock) {
  12356. canvas.requestPointerLock();
  12357. }
  12358. }
  12359. };
  12360. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  12361. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  12362. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  12363. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  12364. // Pointer lock
  12365. this._onPointerLockChange = function () {
  12366. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  12367. document.webkitPointerLockElement === canvas ||
  12368. document.msPointerLockElement === canvas ||
  12369. document.pointerLockElement === canvas);
  12370. };
  12371. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  12372. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  12373. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  12374. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  12375. this._onVRDisplayPointerRestricted = function () {
  12376. if (canvas) {
  12377. canvas.requestPointerLock();
  12378. }
  12379. };
  12380. this._onVRDisplayPointerUnrestricted = function () {
  12381. document.exitPointerLock();
  12382. };
  12383. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  12384. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  12385. }
  12386. // Create Audio Engine if needed.
  12387. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  12388. Engine.audioEngine = Engine.AudioEngineFactory(this);
  12389. }
  12390. // Prepare buffer pointers
  12391. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12392. this._currentBufferPointers[i] = new BufferPointer();
  12393. }
  12394. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  12395. // Load WebVR Devices
  12396. if (options.autoEnableWebVR) {
  12397. this.initWebVR();
  12398. }
  12399. // Detect if we are running on a faulty buggy OS.
  12400. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  12401. // Detect if we are running on a faulty buggy desktop OS.
  12402. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  12403. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  12404. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  12405. }
  12406. Object.defineProperty(Engine, "LastCreatedEngine", {
  12407. /**
  12408. * Gets the latest created engine
  12409. */
  12410. get: function () {
  12411. if (Engine.Instances.length === 0) {
  12412. return null;
  12413. }
  12414. return Engine.Instances[Engine.Instances.length - 1];
  12415. },
  12416. enumerable: true,
  12417. configurable: true
  12418. });
  12419. Object.defineProperty(Engine, "LastCreatedScene", {
  12420. /**
  12421. * Gets the latest created scene
  12422. */
  12423. get: function () {
  12424. var lastCreatedEngine = Engine.LastCreatedEngine;
  12425. if (!lastCreatedEngine) {
  12426. return null;
  12427. }
  12428. if (lastCreatedEngine.scenes.length === 0) {
  12429. return null;
  12430. }
  12431. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  12432. },
  12433. enumerable: true,
  12434. configurable: true
  12435. });
  12436. /**
  12437. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  12438. * @param flag defines which part of the materials must be marked as dirty
  12439. * @param predicate defines a predicate used to filter which materials should be affected
  12440. */
  12441. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  12442. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  12443. var engine = Engine.Instances[engineIndex];
  12444. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  12445. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  12446. }
  12447. }
  12448. };
  12449. Object.defineProperty(Engine, "Version", {
  12450. /**
  12451. * Returns the current version of the framework
  12452. */
  12453. get: function () {
  12454. return "3.3.0-rc.2";
  12455. },
  12456. enumerable: true,
  12457. configurable: true
  12458. });
  12459. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12460. /**
  12461. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12462. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12463. */
  12464. get: function () {
  12465. return this._vrExclusivePointerMode;
  12466. },
  12467. enumerable: true,
  12468. configurable: true
  12469. });
  12470. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12471. /**
  12472. * Gets a boolean indicating that the engine supports uniform buffers
  12473. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12474. */
  12475. get: function () {
  12476. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12477. },
  12478. enumerable: true,
  12479. configurable: true
  12480. });
  12481. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12482. /**
  12483. * Gets a boolean indicating that only power of 2 textures are supported
  12484. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12485. */
  12486. get: function () {
  12487. return this._webGLVersion < 2 || this.forcePOTTextures;
  12488. },
  12489. enumerable: true,
  12490. configurable: true
  12491. });
  12492. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12493. /**
  12494. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12495. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12496. */
  12497. get: function () {
  12498. return this._doNotHandleContextLost;
  12499. },
  12500. set: function (value) {
  12501. this._doNotHandleContextLost = value;
  12502. },
  12503. enumerable: true,
  12504. configurable: true
  12505. });
  12506. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12507. /**
  12508. * Gets the performance monitor attached to this engine
  12509. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12510. */
  12511. get: function () {
  12512. return this._performanceMonitor;
  12513. },
  12514. enumerable: true,
  12515. configurable: true
  12516. });
  12517. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12518. /**
  12519. * Gets the list of texture formats supported
  12520. */
  12521. get: function () {
  12522. return this._texturesSupported;
  12523. },
  12524. enumerable: true,
  12525. configurable: true
  12526. });
  12527. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12528. /**
  12529. * Gets the list of texture formats in use
  12530. */
  12531. get: function () {
  12532. return this._textureFormatInUse;
  12533. },
  12534. enumerable: true,
  12535. configurable: true
  12536. });
  12537. Object.defineProperty(Engine.prototype, "currentViewport", {
  12538. /**
  12539. * Gets the current viewport
  12540. */
  12541. get: function () {
  12542. return this._cachedViewport;
  12543. },
  12544. enumerable: true,
  12545. configurable: true
  12546. });
  12547. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12548. /**
  12549. * Gets the default empty texture
  12550. */
  12551. get: function () {
  12552. if (!this._emptyTexture) {
  12553. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12554. }
  12555. return this._emptyTexture;
  12556. },
  12557. enumerable: true,
  12558. configurable: true
  12559. });
  12560. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12561. /**
  12562. * Gets the default empty 3D texture
  12563. */
  12564. get: function () {
  12565. if (!this._emptyTexture3D) {
  12566. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12567. }
  12568. return this._emptyTexture3D;
  12569. },
  12570. enumerable: true,
  12571. configurable: true
  12572. });
  12573. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12574. /**
  12575. * Gets the default empty cube texture
  12576. */
  12577. get: function () {
  12578. if (!this._emptyCubeTexture) {
  12579. var faceData = new Uint8Array(4);
  12580. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12581. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12582. }
  12583. return this._emptyCubeTexture;
  12584. },
  12585. enumerable: true,
  12586. configurable: true
  12587. });
  12588. Engine.prototype._rebuildInternalTextures = function () {
  12589. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12590. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12591. var internalTexture = currentState_1[_i];
  12592. internalTexture._rebuild();
  12593. }
  12594. };
  12595. Engine.prototype._rebuildEffects = function () {
  12596. for (var key in this._compiledEffects) {
  12597. var effect = this._compiledEffects[key];
  12598. effect._prepareEffect();
  12599. }
  12600. BABYLON.Effect.ResetCache();
  12601. };
  12602. Engine.prototype._rebuildBuffers = function () {
  12603. // Index / Vertex
  12604. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12605. var scene = _a[_i];
  12606. scene.resetCachedMaterial();
  12607. scene._rebuildGeometries();
  12608. scene._rebuildTextures();
  12609. }
  12610. // Uniforms
  12611. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12612. var uniformBuffer = _c[_b];
  12613. uniformBuffer._rebuild();
  12614. }
  12615. };
  12616. Engine.prototype._initGLContext = function () {
  12617. // Caps
  12618. this._caps = new EngineCapabilities();
  12619. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12620. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12621. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12622. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12623. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12624. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12625. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12626. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12627. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12628. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12629. // Infos
  12630. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12631. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12632. if (rendererInfo != null) {
  12633. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12634. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12635. }
  12636. if (!this._glVendor) {
  12637. this._glVendor = "Unknown vendor";
  12638. }
  12639. if (!this._glRenderer) {
  12640. this._glRenderer = "Unknown renderer";
  12641. }
  12642. // Constants
  12643. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12644. if (this._gl.RGBA16F !== 0x881A) {
  12645. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12646. }
  12647. if (this._gl.RGBA32F !== 0x8814) {
  12648. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12649. }
  12650. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12651. this._gl.DEPTH24_STENCIL8 = 35056;
  12652. }
  12653. // Extensions
  12654. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12655. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12656. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12657. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12658. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12659. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12660. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12661. 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');
  12662. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12663. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12664. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12665. this._caps.highPrecisionShaderSupported = true;
  12666. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12667. if (this._caps.timerQuery) {
  12668. if (this._webGLVersion === 1) {
  12669. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12670. }
  12671. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12672. }
  12673. // Checks if some of the format renders first to allow the use of webgl inspector.
  12674. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12675. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12676. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12677. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12678. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12679. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12680. if (this._webGLVersion > 1) {
  12681. this._gl.HALF_FLOAT_OES = 0x140B;
  12682. }
  12683. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12684. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12685. // Draw buffers
  12686. if (this._webGLVersion > 1) {
  12687. this._caps.drawBuffersExtension = true;
  12688. }
  12689. else {
  12690. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12691. if (drawBuffersExtension !== null) {
  12692. this._caps.drawBuffersExtension = true;
  12693. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12694. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12695. for (var i = 0; i < 16; i++) {
  12696. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12697. }
  12698. }
  12699. else {
  12700. this._caps.drawBuffersExtension = false;
  12701. }
  12702. }
  12703. // Depth Texture
  12704. if (this._webGLVersion > 1) {
  12705. this._caps.depthTextureExtension = true;
  12706. }
  12707. else {
  12708. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12709. if (depthTextureExtension != null) {
  12710. this._caps.depthTextureExtension = true;
  12711. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12712. }
  12713. }
  12714. // Vertex array object
  12715. if (this._webGLVersion > 1) {
  12716. this._caps.vertexArrayObject = true;
  12717. }
  12718. else {
  12719. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12720. if (vertexArrayObjectExtension != null) {
  12721. this._caps.vertexArrayObject = true;
  12722. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12723. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12724. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12725. }
  12726. else {
  12727. this._caps.vertexArrayObject = false;
  12728. }
  12729. }
  12730. // Instances count
  12731. if (this._webGLVersion > 1) {
  12732. this._caps.instancedArrays = true;
  12733. }
  12734. else {
  12735. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12736. if (instanceExtension != null) {
  12737. this._caps.instancedArrays = true;
  12738. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12739. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12740. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12741. }
  12742. else {
  12743. this._caps.instancedArrays = false;
  12744. }
  12745. }
  12746. // Intelligently add supported compressed formats in order to check for.
  12747. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12748. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12749. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12750. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12751. if (this._caps.astc)
  12752. this.texturesSupported.push('-astc.ktx');
  12753. if (this._caps.s3tc)
  12754. this.texturesSupported.push('-dxt.ktx');
  12755. if (this._caps.pvrtc)
  12756. this.texturesSupported.push('-pvrtc.ktx');
  12757. if (this._caps.etc2)
  12758. this.texturesSupported.push('-etc2.ktx');
  12759. if (this._caps.etc1)
  12760. this.texturesSupported.push('-etc1.ktx');
  12761. if (this._gl.getShaderPrecisionFormat) {
  12762. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12763. if (highp) {
  12764. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12765. }
  12766. }
  12767. // Depth buffer
  12768. this.setDepthBuffer(true);
  12769. this.setDepthFunctionToLessOrEqual();
  12770. this.setDepthWrite(true);
  12771. // Texture maps
  12772. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12773. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12774. this._nextFreeTextureSlots.push(slot);
  12775. }
  12776. };
  12777. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12778. /**
  12779. * Gets version of the current webGL context
  12780. */
  12781. get: function () {
  12782. return this._webGLVersion;
  12783. },
  12784. enumerable: true,
  12785. configurable: true
  12786. });
  12787. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12788. /**
  12789. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12790. */
  12791. get: function () {
  12792. return this._isStencilEnable;
  12793. },
  12794. enumerable: true,
  12795. configurable: true
  12796. });
  12797. Engine.prototype._prepareWorkingCanvas = function () {
  12798. if (this._workingCanvas) {
  12799. return;
  12800. }
  12801. this._workingCanvas = document.createElement("canvas");
  12802. var context = this._workingCanvas.getContext("2d");
  12803. if (context) {
  12804. this._workingContext = context;
  12805. }
  12806. };
  12807. /**
  12808. * Reset the texture cache to empty state
  12809. */
  12810. Engine.prototype.resetTextureCache = function () {
  12811. for (var key in this._boundTexturesCache) {
  12812. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12813. continue;
  12814. }
  12815. var boundTexture = this._boundTexturesCache[key];
  12816. if (boundTexture) {
  12817. this._removeDesignatedSlot(boundTexture);
  12818. }
  12819. this._boundTexturesCache[key] = null;
  12820. }
  12821. if (!this.disableTextureBindingOptimization) {
  12822. this._nextFreeTextureSlots = [];
  12823. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12824. this._nextFreeTextureSlots.push(slot);
  12825. }
  12826. }
  12827. this._currentTextureChannel = -1;
  12828. };
  12829. /**
  12830. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12831. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12832. * @returns true if engine is in deterministic lock step mode
  12833. */
  12834. Engine.prototype.isDeterministicLockStep = function () {
  12835. return this._deterministicLockstep;
  12836. };
  12837. /**
  12838. * Gets the max steps when engine is running in deterministic lock step
  12839. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12840. * @returns the max steps
  12841. */
  12842. Engine.prototype.getLockstepMaxSteps = function () {
  12843. return this._lockstepMaxSteps;
  12844. };
  12845. /**
  12846. * Gets an object containing information about the current webGL context
  12847. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12848. */
  12849. Engine.prototype.getGlInfo = function () {
  12850. return {
  12851. vendor: this._glVendor,
  12852. renderer: this._glRenderer,
  12853. version: this._glVersion
  12854. };
  12855. };
  12856. /**
  12857. * Gets current aspect ratio
  12858. * @param camera defines the camera to use to get the aspect ratio
  12859. * @param useScreen defines if screen size must be used (or the current render target if any)
  12860. * @returns a number defining the aspect ratio
  12861. */
  12862. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12863. if (useScreen === void 0) { useScreen = false; }
  12864. var viewport = camera.viewport;
  12865. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12866. };
  12867. /**
  12868. * Gets current screen aspect ratio
  12869. * @returns a number defining the aspect ratio
  12870. */
  12871. Engine.prototype.getScreenAspectRatio = function () {
  12872. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12873. };
  12874. /**
  12875. * Gets the current render width
  12876. * @param useScreen defines if screen size must be used (or the current render target if any)
  12877. * @returns a number defining the current render width
  12878. */
  12879. Engine.prototype.getRenderWidth = function (useScreen) {
  12880. if (useScreen === void 0) { useScreen = false; }
  12881. if (!useScreen && this._currentRenderTarget) {
  12882. return this._currentRenderTarget.width;
  12883. }
  12884. return this._gl.drawingBufferWidth;
  12885. };
  12886. /**
  12887. * Gets the current render height
  12888. * @param useScreen defines if screen size must be used (or the current render target if any)
  12889. * @returns a number defining the current render height
  12890. */
  12891. Engine.prototype.getRenderHeight = function (useScreen) {
  12892. if (useScreen === void 0) { useScreen = false; }
  12893. if (!useScreen && this._currentRenderTarget) {
  12894. return this._currentRenderTarget.height;
  12895. }
  12896. return this._gl.drawingBufferHeight;
  12897. };
  12898. /**
  12899. * Gets the HTML canvas attached with the current webGL context
  12900. * @returns a HTML canvas
  12901. */
  12902. Engine.prototype.getRenderingCanvas = function () {
  12903. return this._renderingCanvas;
  12904. };
  12905. /**
  12906. * Gets the client rect of the HTML canvas attached with the current webGL context
  12907. * @returns a client rectanglee
  12908. */
  12909. Engine.prototype.getRenderingCanvasClientRect = function () {
  12910. if (!this._renderingCanvas) {
  12911. return null;
  12912. }
  12913. return this._renderingCanvas.getBoundingClientRect();
  12914. };
  12915. /**
  12916. * Defines the hardware scaling level.
  12917. * By default the hardware scaling level is computed from the window device ratio.
  12918. * 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.
  12919. * @param level defines the level to use
  12920. */
  12921. Engine.prototype.setHardwareScalingLevel = function (level) {
  12922. this._hardwareScalingLevel = level;
  12923. this.resize();
  12924. };
  12925. /**
  12926. * Gets the current hardware scaling level.
  12927. * By default the hardware scaling level is computed from the window device ratio.
  12928. * 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.
  12929. * @returns a number indicating the current hardware scaling level
  12930. */
  12931. Engine.prototype.getHardwareScalingLevel = function () {
  12932. return this._hardwareScalingLevel;
  12933. };
  12934. /**
  12935. * Gets the list of loaded textures
  12936. * @returns an array containing all loaded textures
  12937. */
  12938. Engine.prototype.getLoadedTexturesCache = function () {
  12939. return this._internalTexturesCache;
  12940. };
  12941. /**
  12942. * Gets the object containing all engine capabilities
  12943. * @returns the EngineCapabilities object
  12944. */
  12945. Engine.prototype.getCaps = function () {
  12946. return this._caps;
  12947. };
  12948. Object.defineProperty(Engine.prototype, "drawCalls", {
  12949. /** @hidden */
  12950. get: function () {
  12951. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12952. return 0;
  12953. },
  12954. enumerable: true,
  12955. configurable: true
  12956. });
  12957. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12958. /** @hidden */
  12959. get: function () {
  12960. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12961. return null;
  12962. },
  12963. enumerable: true,
  12964. configurable: true
  12965. });
  12966. /**
  12967. * Gets the current depth function
  12968. * @returns a number defining the depth function
  12969. */
  12970. Engine.prototype.getDepthFunction = function () {
  12971. return this._depthCullingState.depthFunc;
  12972. };
  12973. /**
  12974. * Sets the current depth function
  12975. * @param depthFunc defines the function to use
  12976. */
  12977. Engine.prototype.setDepthFunction = function (depthFunc) {
  12978. this._depthCullingState.depthFunc = depthFunc;
  12979. };
  12980. /**
  12981. * Sets the current depth function to GREATER
  12982. */
  12983. Engine.prototype.setDepthFunctionToGreater = function () {
  12984. this._depthCullingState.depthFunc = this._gl.GREATER;
  12985. };
  12986. /**
  12987. * Sets the current depth function to GEQUAL
  12988. */
  12989. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12990. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12991. };
  12992. /**
  12993. * Sets the current depth function to LESS
  12994. */
  12995. Engine.prototype.setDepthFunctionToLess = function () {
  12996. this._depthCullingState.depthFunc = this._gl.LESS;
  12997. };
  12998. /**
  12999. * Sets the current depth function to LEQUAL
  13000. */
  13001. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  13002. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  13003. };
  13004. /**
  13005. * Gets a boolean indicating if stencil buffer is enabled
  13006. * @returns the current stencil buffer state
  13007. */
  13008. Engine.prototype.getStencilBuffer = function () {
  13009. return this._stencilState.stencilTest;
  13010. };
  13011. /**
  13012. * Enable or disable the stencil buffer
  13013. * @param enable defines if the stencil buffer must be enabled or disabled
  13014. */
  13015. Engine.prototype.setStencilBuffer = function (enable) {
  13016. this._stencilState.stencilTest = enable;
  13017. };
  13018. /**
  13019. * Gets the current stencil mask
  13020. * @returns a number defining the new stencil mask to use
  13021. */
  13022. Engine.prototype.getStencilMask = function () {
  13023. return this._stencilState.stencilMask;
  13024. };
  13025. /**
  13026. * Sets the current stencil mask
  13027. * @param mask defines the new stencil mask to use
  13028. */
  13029. Engine.prototype.setStencilMask = function (mask) {
  13030. this._stencilState.stencilMask = mask;
  13031. };
  13032. /**
  13033. * Gets the current stencil function
  13034. * @returns a number defining the stencil function to use
  13035. */
  13036. Engine.prototype.getStencilFunction = function () {
  13037. return this._stencilState.stencilFunc;
  13038. };
  13039. /**
  13040. * Gets the current stencil reference value
  13041. * @returns a number defining the stencil reference value to use
  13042. */
  13043. Engine.prototype.getStencilFunctionReference = function () {
  13044. return this._stencilState.stencilFuncRef;
  13045. };
  13046. /**
  13047. * Gets the current stencil mask
  13048. * @returns a number defining the stencil mask to use
  13049. */
  13050. Engine.prototype.getStencilFunctionMask = function () {
  13051. return this._stencilState.stencilFuncMask;
  13052. };
  13053. /**
  13054. * Sets the current stencil function
  13055. * @param stencilFunc defines the new stencil function to use
  13056. */
  13057. Engine.prototype.setStencilFunction = function (stencilFunc) {
  13058. this._stencilState.stencilFunc = stencilFunc;
  13059. };
  13060. /**
  13061. * Sets the current stencil reference
  13062. * @param reference defines the new stencil reference to use
  13063. */
  13064. Engine.prototype.setStencilFunctionReference = function (reference) {
  13065. this._stencilState.stencilFuncRef = reference;
  13066. };
  13067. /**
  13068. * Sets the current stencil mask
  13069. * @param mask defines the new stencil mask to use
  13070. */
  13071. Engine.prototype.setStencilFunctionMask = function (mask) {
  13072. this._stencilState.stencilFuncMask = mask;
  13073. };
  13074. /**
  13075. * Gets the current stencil operation when stencil fails
  13076. * @returns a number defining stencil operation to use when stencil fails
  13077. */
  13078. Engine.prototype.getStencilOperationFail = function () {
  13079. return this._stencilState.stencilOpStencilFail;
  13080. };
  13081. /**
  13082. * Gets the current stencil operation when depth fails
  13083. * @returns a number defining stencil operation to use when depth fails
  13084. */
  13085. Engine.prototype.getStencilOperationDepthFail = function () {
  13086. return this._stencilState.stencilOpDepthFail;
  13087. };
  13088. /**
  13089. * Gets the current stencil operation when stencil passes
  13090. * @returns a number defining stencil operation to use when stencil passes
  13091. */
  13092. Engine.prototype.getStencilOperationPass = function () {
  13093. return this._stencilState.stencilOpStencilDepthPass;
  13094. };
  13095. /**
  13096. * Sets the stencil operation to use when stencil fails
  13097. * @param operation defines the stencil operation to use when stencil fails
  13098. */
  13099. Engine.prototype.setStencilOperationFail = function (operation) {
  13100. this._stencilState.stencilOpStencilFail = operation;
  13101. };
  13102. /**
  13103. * Sets the stencil operation to use when depth fails
  13104. * @param operation defines the stencil operation to use when depth fails
  13105. */
  13106. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  13107. this._stencilState.stencilOpDepthFail = operation;
  13108. };
  13109. /**
  13110. * Sets the stencil operation to use when stencil passes
  13111. * @param operation defines the stencil operation to use when stencil passes
  13112. */
  13113. Engine.prototype.setStencilOperationPass = function (operation) {
  13114. this._stencilState.stencilOpStencilDepthPass = operation;
  13115. };
  13116. /**
  13117. * Sets a boolean indicating if the dithering state is enabled or disabled
  13118. * @param value defines the dithering state
  13119. */
  13120. Engine.prototype.setDitheringState = function (value) {
  13121. if (value) {
  13122. this._gl.enable(this._gl.DITHER);
  13123. }
  13124. else {
  13125. this._gl.disable(this._gl.DITHER);
  13126. }
  13127. };
  13128. /**
  13129. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  13130. * @param value defines the rasterizer state
  13131. */
  13132. Engine.prototype.setRasterizerState = function (value) {
  13133. if (value) {
  13134. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  13135. }
  13136. else {
  13137. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  13138. }
  13139. };
  13140. /**
  13141. * stop executing a render loop function and remove it from the execution array
  13142. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  13143. */
  13144. Engine.prototype.stopRenderLoop = function (renderFunction) {
  13145. if (!renderFunction) {
  13146. this._activeRenderLoops = [];
  13147. return;
  13148. }
  13149. var index = this._activeRenderLoops.indexOf(renderFunction);
  13150. if (index >= 0) {
  13151. this._activeRenderLoops.splice(index, 1);
  13152. }
  13153. };
  13154. /** @hidden */
  13155. Engine.prototype._renderLoop = function () {
  13156. if (!this._contextWasLost) {
  13157. var shouldRender = true;
  13158. if (!this.renderEvenInBackground && this._windowIsBackground) {
  13159. shouldRender = false;
  13160. }
  13161. if (shouldRender) {
  13162. // Start new frame
  13163. this.beginFrame();
  13164. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  13165. var renderFunction = this._activeRenderLoops[index];
  13166. renderFunction();
  13167. }
  13168. // Present
  13169. this.endFrame();
  13170. }
  13171. }
  13172. if (this._activeRenderLoops.length > 0) {
  13173. // Register new frame
  13174. var requester = null;
  13175. if (this._vrDisplay && this._vrDisplay.isPresenting)
  13176. requester = this._vrDisplay;
  13177. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  13178. }
  13179. else {
  13180. this._renderingQueueLaunched = false;
  13181. }
  13182. };
  13183. /**
  13184. * Register and execute a render loop. The engine can have more than one render function
  13185. * @param renderFunction defines the function to continuously execute
  13186. */
  13187. Engine.prototype.runRenderLoop = function (renderFunction) {
  13188. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  13189. return;
  13190. }
  13191. this._activeRenderLoops.push(renderFunction);
  13192. if (!this._renderingQueueLaunched) {
  13193. this._renderingQueueLaunched = true;
  13194. this._bindedRenderFunction = this._renderLoop.bind(this);
  13195. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13196. }
  13197. };
  13198. /**
  13199. * Toggle full screen mode
  13200. * @param requestPointerLock defines if a pointer lock should be requested from the user
  13201. */
  13202. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  13203. if (this.isFullscreen) {
  13204. BABYLON.Tools.ExitFullscreen();
  13205. }
  13206. else {
  13207. this._pointerLockRequested = requestPointerLock;
  13208. if (this._renderingCanvas) {
  13209. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  13210. }
  13211. }
  13212. };
  13213. /**
  13214. * Clear the current render buffer or the current render target (if any is set up)
  13215. * @param color defines the color to use
  13216. * @param backBuffer defines if the back buffer must be cleared
  13217. * @param depth defines if the depth buffer must be cleared
  13218. * @param stencil defines if the stencil buffer must be cleared
  13219. */
  13220. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  13221. if (stencil === void 0) { stencil = false; }
  13222. this.applyStates();
  13223. var mode = 0;
  13224. if (backBuffer && color) {
  13225. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  13226. mode |= this._gl.COLOR_BUFFER_BIT;
  13227. }
  13228. if (depth) {
  13229. this._gl.clearDepth(1.0);
  13230. mode |= this._gl.DEPTH_BUFFER_BIT;
  13231. }
  13232. if (stencil) {
  13233. this._gl.clearStencil(0);
  13234. mode |= this._gl.STENCIL_BUFFER_BIT;
  13235. }
  13236. this._gl.clear(mode);
  13237. };
  13238. /**
  13239. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  13240. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  13241. * @param y defines the y-coordinate of the corner of the clear rectangle
  13242. * @param width defines the width of the clear rectangle
  13243. * @param height defines the height of the clear rectangle
  13244. * @param clearColor defines the clear color
  13245. */
  13246. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  13247. var gl = this._gl;
  13248. // Save state
  13249. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  13250. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  13251. // Change state
  13252. gl.enable(gl.SCISSOR_TEST);
  13253. gl.scissor(x, y, width, height);
  13254. // Clear
  13255. this.clear(clearColor, true, true, true);
  13256. // Restore state
  13257. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  13258. if (curScissor === true) {
  13259. gl.enable(gl.SCISSOR_TEST);
  13260. }
  13261. else {
  13262. gl.disable(gl.SCISSOR_TEST);
  13263. }
  13264. };
  13265. /** @hidden */
  13266. Engine.prototype._viewport = function (x, y, width, height) {
  13267. if (x !== this._viewportCached.x ||
  13268. y !== this._viewportCached.y ||
  13269. width !== this._viewportCached.z ||
  13270. height !== this._viewportCached.w) {
  13271. this._viewportCached.x = x;
  13272. this._viewportCached.y = y;
  13273. this._viewportCached.z = width;
  13274. this._viewportCached.w = height;
  13275. this._gl.viewport(x, y, width, height);
  13276. }
  13277. };
  13278. /**
  13279. * Set the WebGL's viewport
  13280. * @param viewport defines the viewport element to be used
  13281. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13282. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13283. */
  13284. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13285. var width = requiredWidth || this.getRenderWidth();
  13286. var height = requiredHeight || this.getRenderHeight();
  13287. var x = viewport.x || 0;
  13288. var y = viewport.y || 0;
  13289. this._cachedViewport = viewport;
  13290. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13291. };
  13292. /**
  13293. * Directly set the WebGL Viewport
  13294. * @param x defines the x coordinate of the viewport (in screen space)
  13295. * @param y defines the y coordinate of the viewport (in screen space)
  13296. * @param width defines the width of the viewport (in screen space)
  13297. * @param height defines the height of the viewport (in screen space)
  13298. * @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
  13299. */
  13300. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13301. var currentViewport = this._cachedViewport;
  13302. this._cachedViewport = null;
  13303. this._viewport(x, y, width, height);
  13304. return currentViewport;
  13305. };
  13306. /**
  13307. * Begin a new frame
  13308. */
  13309. Engine.prototype.beginFrame = function () {
  13310. this.onBeginFrameObservable.notifyObservers(this);
  13311. this._measureFps();
  13312. };
  13313. /**
  13314. * Enf the current frame
  13315. */
  13316. Engine.prototype.endFrame = function () {
  13317. // Force a flush in case we are using a bad OS.
  13318. if (this._badOS) {
  13319. this.flushFramebuffer();
  13320. }
  13321. // Submit frame to the vr device, if enabled
  13322. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13323. // TODO: We should only submit the frame if we read frameData successfully.
  13324. this._vrDisplay.submitFrame();
  13325. }
  13326. this.onEndFrameObservable.notifyObservers(this);
  13327. };
  13328. /**
  13329. * Resize the view according to the canvas' size
  13330. */
  13331. Engine.prototype.resize = function () {
  13332. // We're not resizing the size of the canvas while in VR mode & presenting
  13333. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13334. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13335. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13336. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13337. }
  13338. };
  13339. /**
  13340. * Force a specific size of the canvas
  13341. * @param width defines the new canvas' width
  13342. * @param height defines the new canvas' height
  13343. */
  13344. Engine.prototype.setSize = function (width, height) {
  13345. if (!this._renderingCanvas) {
  13346. return;
  13347. }
  13348. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13349. return;
  13350. }
  13351. this._renderingCanvas.width = width;
  13352. this._renderingCanvas.height = height;
  13353. for (var index = 0; index < this.scenes.length; index++) {
  13354. var scene = this.scenes[index];
  13355. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13356. var cam = scene.cameras[camIndex];
  13357. cam._currentRenderId = 0;
  13358. }
  13359. }
  13360. if (this.onResizeObservable.hasObservers) {
  13361. this.onResizeObservable.notifyObservers(this);
  13362. }
  13363. };
  13364. // WebVR functions
  13365. /**
  13366. * Gets a boolean indicating if a webVR device was detected
  13367. * @returns true if a webVR device was detected
  13368. */
  13369. Engine.prototype.isVRDevicePresent = function () {
  13370. return !!this._vrDisplay;
  13371. };
  13372. /**
  13373. * Gets the current webVR device
  13374. * @returns the current webVR device (or null)
  13375. */
  13376. Engine.prototype.getVRDevice = function () {
  13377. return this._vrDisplay;
  13378. };
  13379. /**
  13380. * Initializes a webVR display and starts listening to display change events
  13381. * The onVRDisplayChangedObservable will be notified upon these changes
  13382. * @returns The onVRDisplayChangedObservable
  13383. */
  13384. Engine.prototype.initWebVR = function () {
  13385. this.initWebVRAsync();
  13386. return this.onVRDisplayChangedObservable;
  13387. };
  13388. /**
  13389. * Initializes a webVR display and starts listening to display change events
  13390. * The onVRDisplayChangedObservable will be notified upon these changes
  13391. * @returns A promise containing a VRDisplay and if vr is supported
  13392. */
  13393. Engine.prototype.initWebVRAsync = function () {
  13394. var _this = this;
  13395. var notifyObservers = function () {
  13396. var eventArgs = {
  13397. vrDisplay: _this._vrDisplay,
  13398. vrSupported: _this._vrSupported
  13399. };
  13400. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13401. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13402. };
  13403. if (!this._onVrDisplayConnect) {
  13404. this._onVrDisplayConnect = function (event) {
  13405. _this._vrDisplay = event.display;
  13406. notifyObservers();
  13407. };
  13408. this._onVrDisplayDisconnect = function () {
  13409. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13410. _this._vrDisplay = undefined;
  13411. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13412. notifyObservers();
  13413. };
  13414. this._onVrDisplayPresentChange = function () {
  13415. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13416. };
  13417. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13418. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13419. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13420. }
  13421. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13422. this._webVRInitPromise.then(notifyObservers);
  13423. return this._webVRInitPromise;
  13424. };
  13425. /**
  13426. * Call this function to switch to webVR mode
  13427. * Will do nothing if webVR is not supported or if there is no webVR device
  13428. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13429. */
  13430. Engine.prototype.enableVR = function () {
  13431. var _this = this;
  13432. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13433. var onResolved = function () {
  13434. _this.onVRRequestPresentComplete.notifyObservers(true);
  13435. _this._onVRFullScreenTriggered();
  13436. };
  13437. var onRejected = function () {
  13438. _this.onVRRequestPresentComplete.notifyObservers(false);
  13439. };
  13440. this.onVRRequestPresentStart.notifyObservers(this);
  13441. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13442. }
  13443. };
  13444. /**
  13445. * Call this function to leave webVR mode
  13446. * Will do nothing if webVR is not supported or if there is no webVR device
  13447. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13448. */
  13449. Engine.prototype.disableVR = function () {
  13450. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13451. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13452. }
  13453. };
  13454. Engine.prototype._getVRDisplaysAsync = function () {
  13455. var _this = this;
  13456. return new Promise(function (res, rej) {
  13457. if (navigator.getVRDisplays) {
  13458. navigator.getVRDisplays().then(function (devices) {
  13459. _this._vrSupported = true;
  13460. // note that devices may actually be an empty array. This is fine;
  13461. // we expect this._vrDisplay to be undefined in this case.
  13462. _this._vrDisplay = devices[0];
  13463. res({
  13464. vrDisplay: _this._vrDisplay,
  13465. vrSupported: _this._vrSupported
  13466. });
  13467. });
  13468. }
  13469. else {
  13470. _this._vrDisplay = undefined;
  13471. _this._vrSupported = false;
  13472. res({
  13473. vrDisplay: _this._vrDisplay,
  13474. vrSupported: _this._vrSupported
  13475. });
  13476. }
  13477. });
  13478. };
  13479. /**
  13480. * Binds the frame buffer to the specified texture.
  13481. * @param texture The texture to render to or null for the default canvas
  13482. * @param faceIndex The face of the texture to render to in case of cube texture
  13483. * @param requiredWidth The width of the target to render to
  13484. * @param requiredHeight The height of the target to render to
  13485. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13486. * @param depthStencilTexture The depth stencil texture to use to render
  13487. * @param lodLevel defines le lod level to bind to the frame buffer
  13488. */
  13489. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13490. if (lodLevel === void 0) { lodLevel = 0; }
  13491. if (this._currentRenderTarget) {
  13492. this.unBindFramebuffer(this._currentRenderTarget);
  13493. }
  13494. this._currentRenderTarget = texture;
  13495. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13496. var gl = this._gl;
  13497. if (texture.isCube) {
  13498. if (faceIndex === undefined) {
  13499. faceIndex = 0;
  13500. }
  13501. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13502. if (depthStencilTexture) {
  13503. if (depthStencilTexture._generateStencilBuffer) {
  13504. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13505. }
  13506. else {
  13507. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13508. }
  13509. }
  13510. }
  13511. if (this._cachedViewport && !forceFullscreenViewport) {
  13512. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13513. }
  13514. else {
  13515. if (!requiredWidth) {
  13516. requiredWidth = texture.width;
  13517. if (lodLevel) {
  13518. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13519. }
  13520. }
  13521. if (!requiredHeight) {
  13522. requiredHeight = texture.height;
  13523. if (lodLevel) {
  13524. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13525. }
  13526. }
  13527. this._viewport(0, 0, requiredWidth, requiredHeight);
  13528. }
  13529. this.wipeCaches();
  13530. };
  13531. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13532. if (this._currentFramebuffer !== framebuffer) {
  13533. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13534. this._currentFramebuffer = framebuffer;
  13535. }
  13536. };
  13537. /**
  13538. * Unbind the current render target texture from the webGL context
  13539. * @param texture defines the render target texture to unbind
  13540. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13541. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13542. */
  13543. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13544. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13545. this._currentRenderTarget = null;
  13546. // If MSAA, we need to bitblt back to main texture
  13547. var gl = this._gl;
  13548. if (texture._MSAAFramebuffer) {
  13549. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13550. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13551. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13552. }
  13553. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13554. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13555. gl.generateMipmap(gl.TEXTURE_2D);
  13556. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13557. }
  13558. if (onBeforeUnbind) {
  13559. if (texture._MSAAFramebuffer) {
  13560. // Bind the correct framebuffer
  13561. this.bindUnboundFramebuffer(texture._framebuffer);
  13562. }
  13563. onBeforeUnbind();
  13564. }
  13565. this.bindUnboundFramebuffer(null);
  13566. };
  13567. /**
  13568. * Unbind a list of render target textures from the webGL context
  13569. * This is used only when drawBuffer extension or webGL2 are active
  13570. * @param textures defines the render target textures to unbind
  13571. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13572. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13573. */
  13574. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13575. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13576. this._currentRenderTarget = null;
  13577. // If MSAA, we need to bitblt back to main texture
  13578. var gl = this._gl;
  13579. if (textures[0]._MSAAFramebuffer) {
  13580. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13581. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13582. var attachments = textures[0]._attachments;
  13583. if (!attachments) {
  13584. attachments = new Array(textures.length);
  13585. textures[0]._attachments = attachments;
  13586. }
  13587. for (var i = 0; i < textures.length; i++) {
  13588. var texture = textures[i];
  13589. for (var j = 0; j < attachments.length; j++) {
  13590. attachments[j] = gl.NONE;
  13591. }
  13592. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13593. gl.readBuffer(attachments[i]);
  13594. gl.drawBuffers(attachments);
  13595. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13596. }
  13597. for (var i = 0; i < attachments.length; i++) {
  13598. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13599. }
  13600. gl.drawBuffers(attachments);
  13601. }
  13602. for (var i = 0; i < textures.length; i++) {
  13603. var texture = textures[i];
  13604. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13605. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13606. gl.generateMipmap(gl.TEXTURE_2D);
  13607. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13608. }
  13609. }
  13610. if (onBeforeUnbind) {
  13611. if (textures[0]._MSAAFramebuffer) {
  13612. // Bind the correct framebuffer
  13613. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13614. }
  13615. onBeforeUnbind();
  13616. }
  13617. this.bindUnboundFramebuffer(null);
  13618. };
  13619. /**
  13620. * Force the mipmap generation for the given render target texture
  13621. * @param texture defines the render target texture to use
  13622. */
  13623. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13624. if (texture.generateMipMaps) {
  13625. var gl = this._gl;
  13626. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13627. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13628. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13629. }
  13630. };
  13631. /**
  13632. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13633. */
  13634. Engine.prototype.flushFramebuffer = function () {
  13635. this._gl.flush();
  13636. };
  13637. /**
  13638. * Unbind the current render target and bind the default framebuffer
  13639. */
  13640. Engine.prototype.restoreDefaultFramebuffer = function () {
  13641. if (this._currentRenderTarget) {
  13642. this.unBindFramebuffer(this._currentRenderTarget);
  13643. }
  13644. else {
  13645. this.bindUnboundFramebuffer(null);
  13646. }
  13647. if (this._cachedViewport) {
  13648. this.setViewport(this._cachedViewport);
  13649. }
  13650. this.wipeCaches();
  13651. };
  13652. // UBOs
  13653. /**
  13654. * Create an uniform buffer
  13655. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13656. * @param elements defines the content of the uniform buffer
  13657. * @returns the webGL uniform buffer
  13658. */
  13659. Engine.prototype.createUniformBuffer = function (elements) {
  13660. var ubo = this._gl.createBuffer();
  13661. if (!ubo) {
  13662. throw new Error("Unable to create uniform buffer");
  13663. }
  13664. this.bindUniformBuffer(ubo);
  13665. if (elements instanceof Float32Array) {
  13666. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13667. }
  13668. else {
  13669. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13670. }
  13671. this.bindUniformBuffer(null);
  13672. ubo.references = 1;
  13673. return ubo;
  13674. };
  13675. /**
  13676. * Create a dynamic uniform buffer
  13677. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13678. * @param elements defines the content of the uniform buffer
  13679. * @returns the webGL uniform buffer
  13680. */
  13681. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13682. var ubo = this._gl.createBuffer();
  13683. if (!ubo) {
  13684. throw new Error("Unable to create dynamic uniform buffer");
  13685. }
  13686. this.bindUniformBuffer(ubo);
  13687. if (elements instanceof Float32Array) {
  13688. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13689. }
  13690. else {
  13691. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13692. }
  13693. this.bindUniformBuffer(null);
  13694. ubo.references = 1;
  13695. return ubo;
  13696. };
  13697. /**
  13698. * Update an existing uniform buffer
  13699. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13700. * @param uniformBuffer defines the target uniform buffer
  13701. * @param elements defines the content to update
  13702. * @param offset defines the offset in the uniform buffer where update should start
  13703. * @param count defines the size of the data to update
  13704. */
  13705. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13706. this.bindUniformBuffer(uniformBuffer);
  13707. if (offset === undefined) {
  13708. offset = 0;
  13709. }
  13710. if (count === undefined) {
  13711. if (elements instanceof Float32Array) {
  13712. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13713. }
  13714. else {
  13715. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13716. }
  13717. }
  13718. else {
  13719. if (elements instanceof Float32Array) {
  13720. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13721. }
  13722. else {
  13723. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13724. }
  13725. }
  13726. this.bindUniformBuffer(null);
  13727. };
  13728. // VBOs
  13729. Engine.prototype._resetVertexBufferBinding = function () {
  13730. this.bindArrayBuffer(null);
  13731. this._cachedVertexBuffers = null;
  13732. };
  13733. /**
  13734. * Creates a vertex buffer
  13735. * @param data the data for the vertex buffer
  13736. * @returns the new WebGL static buffer
  13737. */
  13738. Engine.prototype.createVertexBuffer = function (data) {
  13739. var vbo = this._gl.createBuffer();
  13740. if (!vbo) {
  13741. throw new Error("Unable to create vertex buffer");
  13742. }
  13743. this.bindArrayBuffer(vbo);
  13744. if (data instanceof Array) {
  13745. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13746. }
  13747. else {
  13748. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13749. }
  13750. this._resetVertexBufferBinding();
  13751. vbo.references = 1;
  13752. return vbo;
  13753. };
  13754. /**
  13755. * Creates a dynamic vertex buffer
  13756. * @param data the data for the dynamic vertex buffer
  13757. * @returns the new WebGL dynamic buffer
  13758. */
  13759. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13760. var vbo = this._gl.createBuffer();
  13761. if (!vbo) {
  13762. throw new Error("Unable to create dynamic vertex buffer");
  13763. }
  13764. this.bindArrayBuffer(vbo);
  13765. if (data instanceof Array) {
  13766. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13767. }
  13768. else {
  13769. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13770. }
  13771. this._resetVertexBufferBinding();
  13772. vbo.references = 1;
  13773. return vbo;
  13774. };
  13775. /**
  13776. * Update a dynamic index buffer
  13777. * @param indexBuffer defines the target index buffer
  13778. * @param indices defines the data to update
  13779. * @param offset defines the offset in the target index buffer where update should start
  13780. */
  13781. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13782. if (offset === void 0) { offset = 0; }
  13783. // Force cache update
  13784. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13785. this.bindIndexBuffer(indexBuffer);
  13786. var arrayBuffer;
  13787. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13788. arrayBuffer = indices;
  13789. }
  13790. else {
  13791. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13792. }
  13793. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13794. this._resetIndexBufferBinding();
  13795. };
  13796. /**
  13797. * Updates a dynamic vertex buffer.
  13798. * @param vertexBuffer the vertex buffer to update
  13799. * @param data the data used to update the vertex buffer
  13800. * @param byteOffset the byte offset of the data
  13801. * @param byteLength the byte length of the data
  13802. */
  13803. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13804. this.bindArrayBuffer(vertexBuffer);
  13805. if (byteOffset === undefined) {
  13806. byteOffset = 0;
  13807. }
  13808. if (byteLength === undefined) {
  13809. if (data instanceof Array) {
  13810. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13811. }
  13812. else {
  13813. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13814. }
  13815. }
  13816. else {
  13817. if (data instanceof Array) {
  13818. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13819. }
  13820. else {
  13821. if (data instanceof ArrayBuffer) {
  13822. data = new Uint8Array(data, byteOffset, byteLength);
  13823. }
  13824. else {
  13825. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13826. }
  13827. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13828. }
  13829. }
  13830. this._resetVertexBufferBinding();
  13831. };
  13832. Engine.prototype._resetIndexBufferBinding = function () {
  13833. this.bindIndexBuffer(null);
  13834. this._cachedIndexBuffer = null;
  13835. };
  13836. /**
  13837. * Creates a new index buffer
  13838. * @param indices defines the content of the index buffer
  13839. * @param updatable defines if the index buffer must be updatable
  13840. * @returns a new webGL buffer
  13841. */
  13842. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13843. var vbo = this._gl.createBuffer();
  13844. if (!vbo) {
  13845. throw new Error("Unable to create index buffer");
  13846. }
  13847. this.bindIndexBuffer(vbo);
  13848. // Check for 32 bits indices
  13849. var arrayBuffer;
  13850. var need32Bits = false;
  13851. if (indices instanceof Uint16Array) {
  13852. arrayBuffer = indices;
  13853. }
  13854. else {
  13855. //check 32 bit support
  13856. if (this._caps.uintIndices) {
  13857. if (indices instanceof Uint32Array) {
  13858. arrayBuffer = indices;
  13859. need32Bits = true;
  13860. }
  13861. else {
  13862. //number[] or Int32Array, check if 32 bit is necessary
  13863. for (var index = 0; index < indices.length; index++) {
  13864. if (indices[index] > 65535) {
  13865. need32Bits = true;
  13866. break;
  13867. }
  13868. }
  13869. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13870. }
  13871. }
  13872. else {
  13873. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13874. arrayBuffer = new Uint16Array(indices);
  13875. }
  13876. }
  13877. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13878. this._resetIndexBufferBinding();
  13879. vbo.references = 1;
  13880. vbo.is32Bits = need32Bits;
  13881. return vbo;
  13882. };
  13883. /**
  13884. * Bind a webGL buffer to the webGL context
  13885. * @param buffer defines the buffer to bind
  13886. */
  13887. Engine.prototype.bindArrayBuffer = function (buffer) {
  13888. if (!this._vaoRecordInProgress) {
  13889. this._unbindVertexArrayObject();
  13890. }
  13891. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13892. };
  13893. /**
  13894. * Bind an uniform buffer to the current webGL context
  13895. * @param buffer defines the buffer to bind
  13896. */
  13897. Engine.prototype.bindUniformBuffer = function (buffer) {
  13898. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13899. };
  13900. /**
  13901. * Bind a buffer to the current webGL context at a given location
  13902. * @param buffer defines the buffer to bind
  13903. * @param location defines the index where to bind the buffer
  13904. */
  13905. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13906. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13907. };
  13908. /**
  13909. * Bind a specific block at a given index in a specific shader program
  13910. * @param shaderProgram defines the shader program
  13911. * @param blockName defines the block name
  13912. * @param index defines the index where to bind the block
  13913. */
  13914. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13915. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13916. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13917. };
  13918. ;
  13919. Engine.prototype.bindIndexBuffer = function (buffer) {
  13920. if (!this._vaoRecordInProgress) {
  13921. this._unbindVertexArrayObject();
  13922. }
  13923. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13924. };
  13925. Engine.prototype.bindBuffer = function (buffer, target) {
  13926. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13927. this._gl.bindBuffer(target, buffer);
  13928. this._currentBoundBuffer[target] = buffer;
  13929. }
  13930. };
  13931. /**
  13932. * update the bound buffer with the given data
  13933. * @param data defines the data to update
  13934. */
  13935. Engine.prototype.updateArrayBuffer = function (data) {
  13936. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13937. };
  13938. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13939. var pointer = this._currentBufferPointers[indx];
  13940. var changed = false;
  13941. if (!pointer.active) {
  13942. changed = true;
  13943. pointer.active = true;
  13944. pointer.index = indx;
  13945. pointer.size = size;
  13946. pointer.type = type;
  13947. pointer.normalized = normalized;
  13948. pointer.stride = stride;
  13949. pointer.offset = offset;
  13950. pointer.buffer = buffer;
  13951. }
  13952. else {
  13953. if (pointer.buffer !== buffer) {
  13954. pointer.buffer = buffer;
  13955. changed = true;
  13956. }
  13957. if (pointer.size !== size) {
  13958. pointer.size = size;
  13959. changed = true;
  13960. }
  13961. if (pointer.type !== type) {
  13962. pointer.type = type;
  13963. changed = true;
  13964. }
  13965. if (pointer.normalized !== normalized) {
  13966. pointer.normalized = normalized;
  13967. changed = true;
  13968. }
  13969. if (pointer.stride !== stride) {
  13970. pointer.stride = stride;
  13971. changed = true;
  13972. }
  13973. if (pointer.offset !== offset) {
  13974. pointer.offset = offset;
  13975. changed = true;
  13976. }
  13977. }
  13978. if (changed || this._vaoRecordInProgress) {
  13979. this.bindArrayBuffer(buffer);
  13980. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13981. }
  13982. };
  13983. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13984. if (indexBuffer == null) {
  13985. return;
  13986. }
  13987. if (this._cachedIndexBuffer !== indexBuffer) {
  13988. this._cachedIndexBuffer = indexBuffer;
  13989. this.bindIndexBuffer(indexBuffer);
  13990. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13991. }
  13992. };
  13993. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13994. var attributes = effect.getAttributesNames();
  13995. if (!this._vaoRecordInProgress) {
  13996. this._unbindVertexArrayObject();
  13997. }
  13998. this.unbindAllAttributes();
  13999. for (var index = 0; index < attributes.length; index++) {
  14000. var order = effect.getAttributeLocation(index);
  14001. if (order >= 0) {
  14002. var vertexBuffer = vertexBuffers[attributes[index]];
  14003. if (!vertexBuffer) {
  14004. continue;
  14005. }
  14006. this._gl.enableVertexAttribArray(order);
  14007. if (!this._vaoRecordInProgress) {
  14008. this._vertexAttribArraysEnabled[order] = true;
  14009. }
  14010. var buffer = vertexBuffer.getBuffer();
  14011. if (buffer) {
  14012. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  14013. if (vertexBuffer.getIsInstanced()) {
  14014. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  14015. if (!this._vaoRecordInProgress) {
  14016. this._currentInstanceLocations.push(order);
  14017. this._currentInstanceBuffers.push(buffer);
  14018. }
  14019. }
  14020. }
  14021. }
  14022. }
  14023. };
  14024. /**
  14025. * Records a vertex array object
  14026. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14027. * @param vertexBuffers defines the list of vertex buffers to store
  14028. * @param indexBuffer defines the index buffer to store
  14029. * @param effect defines the effect to store
  14030. * @returns the new vertex array object
  14031. */
  14032. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  14033. var vao = this._gl.createVertexArray();
  14034. this._vaoRecordInProgress = true;
  14035. this._gl.bindVertexArray(vao);
  14036. this._mustWipeVertexAttributes = true;
  14037. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14038. this.bindIndexBuffer(indexBuffer);
  14039. this._vaoRecordInProgress = false;
  14040. this._gl.bindVertexArray(null);
  14041. return vao;
  14042. };
  14043. /**
  14044. * Bind a specific vertex array object
  14045. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14046. * @param vertexArrayObject defines the vertex array object to bind
  14047. * @param indexBuffer defines the index buffer to bind
  14048. */
  14049. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  14050. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  14051. this._cachedVertexArrayObject = vertexArrayObject;
  14052. this._gl.bindVertexArray(vertexArrayObject);
  14053. this._cachedVertexBuffers = null;
  14054. this._cachedIndexBuffer = null;
  14055. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  14056. this._mustWipeVertexAttributes = true;
  14057. }
  14058. };
  14059. /**
  14060. * Bind webGl buffers directly to the webGL context
  14061. * @param vertexBuffer defines the vertex buffer to bind
  14062. * @param indexBuffer defines the index buffer to bind
  14063. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  14064. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  14065. * @param effect defines the effect associated with the vertex buffer
  14066. */
  14067. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  14068. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  14069. this._cachedVertexBuffers = vertexBuffer;
  14070. this._cachedEffectForVertexBuffers = effect;
  14071. var attributesCount = effect.getAttributesCount();
  14072. this._unbindVertexArrayObject();
  14073. this.unbindAllAttributes();
  14074. var offset = 0;
  14075. for (var index = 0; index < attributesCount; index++) {
  14076. if (index < vertexDeclaration.length) {
  14077. var order = effect.getAttributeLocation(index);
  14078. if (order >= 0) {
  14079. this._gl.enableVertexAttribArray(order);
  14080. this._vertexAttribArraysEnabled[order] = true;
  14081. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  14082. }
  14083. offset += vertexDeclaration[index] * 4;
  14084. }
  14085. }
  14086. }
  14087. this._bindIndexBufferWithCache(indexBuffer);
  14088. };
  14089. Engine.prototype._unbindVertexArrayObject = function () {
  14090. if (!this._cachedVertexArrayObject) {
  14091. return;
  14092. }
  14093. this._cachedVertexArrayObject = null;
  14094. this._gl.bindVertexArray(null);
  14095. };
  14096. /**
  14097. * Bind a list of vertex buffers to the webGL context
  14098. * @param vertexBuffers defines the list of vertex buffers to bind
  14099. * @param indexBuffer defines the index buffer to bind
  14100. * @param effect defines the effect associated with the vertex buffers
  14101. */
  14102. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  14103. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  14104. this._cachedVertexBuffers = vertexBuffers;
  14105. this._cachedEffectForVertexBuffers = effect;
  14106. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14107. }
  14108. this._bindIndexBufferWithCache(indexBuffer);
  14109. };
  14110. /**
  14111. * Unbind all instance attributes
  14112. */
  14113. Engine.prototype.unbindInstanceAttributes = function () {
  14114. var boundBuffer;
  14115. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  14116. var instancesBuffer = this._currentInstanceBuffers[i];
  14117. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  14118. boundBuffer = instancesBuffer;
  14119. this.bindArrayBuffer(instancesBuffer);
  14120. }
  14121. var offsetLocation = this._currentInstanceLocations[i];
  14122. this._gl.vertexAttribDivisor(offsetLocation, 0);
  14123. }
  14124. this._currentInstanceBuffers.length = 0;
  14125. this._currentInstanceLocations.length = 0;
  14126. };
  14127. /**
  14128. * Release and free the memory of a vertex array object
  14129. * @param vao defines the vertex array object to delete
  14130. */
  14131. Engine.prototype.releaseVertexArrayObject = function (vao) {
  14132. this._gl.deleteVertexArray(vao);
  14133. };
  14134. /** @hidden */
  14135. Engine.prototype._releaseBuffer = function (buffer) {
  14136. buffer.references--;
  14137. if (buffer.references === 0) {
  14138. this._gl.deleteBuffer(buffer);
  14139. return true;
  14140. }
  14141. return false;
  14142. };
  14143. /**
  14144. * Creates a webGL buffer to use with instanciation
  14145. * @param capacity defines the size of the buffer
  14146. * @returns the webGL buffer
  14147. */
  14148. Engine.prototype.createInstancesBuffer = function (capacity) {
  14149. var buffer = this._gl.createBuffer();
  14150. if (!buffer) {
  14151. throw new Error("Unable to create instance buffer");
  14152. }
  14153. buffer.capacity = capacity;
  14154. this.bindArrayBuffer(buffer);
  14155. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  14156. return buffer;
  14157. };
  14158. /**
  14159. * Delete a webGL buffer used with instanciation
  14160. * @param buffer defines the webGL buffer to delete
  14161. */
  14162. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  14163. this._gl.deleteBuffer(buffer);
  14164. };
  14165. /**
  14166. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  14167. * @param instancesBuffer defines the webGL buffer to update and bind
  14168. * @param data defines the data to store in the buffer
  14169. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  14170. */
  14171. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  14172. this.bindArrayBuffer(instancesBuffer);
  14173. if (data) {
  14174. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14175. }
  14176. if (offsetLocations[0].index !== undefined) {
  14177. var stride = 0;
  14178. for (var i = 0; i < offsetLocations.length; i++) {
  14179. var ai = offsetLocations[i];
  14180. stride += ai.attributeSize * 4;
  14181. }
  14182. for (var i = 0; i < offsetLocations.length; i++) {
  14183. var ai = offsetLocations[i];
  14184. if (!this._vertexAttribArraysEnabled[ai.index]) {
  14185. this._gl.enableVertexAttribArray(ai.index);
  14186. this._vertexAttribArraysEnabled[ai.index] = true;
  14187. }
  14188. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  14189. this._gl.vertexAttribDivisor(ai.index, 1);
  14190. this._currentInstanceLocations.push(ai.index);
  14191. this._currentInstanceBuffers.push(instancesBuffer);
  14192. }
  14193. }
  14194. else {
  14195. for (var index = 0; index < 4; index++) {
  14196. var offsetLocation = offsetLocations[index];
  14197. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  14198. this._gl.enableVertexAttribArray(offsetLocation);
  14199. this._vertexAttribArraysEnabled[offsetLocation] = true;
  14200. }
  14201. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  14202. this._gl.vertexAttribDivisor(offsetLocation, 1);
  14203. this._currentInstanceLocations.push(offsetLocation);
  14204. this._currentInstanceBuffers.push(instancesBuffer);
  14205. }
  14206. }
  14207. };
  14208. /**
  14209. * Apply all cached states (depth, culling, stencil and alpha)
  14210. */
  14211. Engine.prototype.applyStates = function () {
  14212. this._depthCullingState.apply(this._gl);
  14213. this._stencilState.apply(this._gl);
  14214. this._alphaState.apply(this._gl);
  14215. };
  14216. /**
  14217. * Send a draw order
  14218. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14219. * @param indexStart defines the starting index
  14220. * @param indexCount defines the number of index to draw
  14221. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14222. */
  14223. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  14224. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  14225. };
  14226. /**
  14227. * Draw a list of points
  14228. * @param verticesStart defines the index of first vertex to draw
  14229. * @param verticesCount defines the count of vertices to draw
  14230. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14231. */
  14232. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  14233. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  14234. };
  14235. /**
  14236. * Draw a list of unindexed primitives
  14237. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14238. * @param verticesStart defines the index of first vertex to draw
  14239. * @param verticesCount defines the count of vertices to draw
  14240. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14241. */
  14242. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  14243. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  14244. };
  14245. /**
  14246. * Draw a list of indexed primitives
  14247. * @param fillMode defines the primitive to use
  14248. * @param indexStart defines the starting index
  14249. * @param indexCount defines the number of index to draw
  14250. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14251. */
  14252. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  14253. // Apply states
  14254. this.applyStates();
  14255. this._drawCalls.addCount(1, false);
  14256. // Render
  14257. var drawMode = this._drawMode(fillMode);
  14258. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  14259. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  14260. if (instancesCount) {
  14261. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  14262. }
  14263. else {
  14264. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  14265. }
  14266. };
  14267. /**
  14268. * Draw a list of unindexed primitives
  14269. * @param fillMode defines the primitive to use
  14270. * @param verticesStart defines the index of first vertex to draw
  14271. * @param verticesCount defines the count of vertices to draw
  14272. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14273. */
  14274. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14275. // Apply states
  14276. this.applyStates();
  14277. this._drawCalls.addCount(1, false);
  14278. var drawMode = this._drawMode(fillMode);
  14279. if (instancesCount) {
  14280. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14281. }
  14282. else {
  14283. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14284. }
  14285. };
  14286. Engine.prototype._drawMode = function (fillMode) {
  14287. switch (fillMode) {
  14288. // Triangle views
  14289. case BABYLON.Material.TriangleFillMode:
  14290. return this._gl.TRIANGLES;
  14291. case BABYLON.Material.PointFillMode:
  14292. return this._gl.POINTS;
  14293. case BABYLON.Material.WireFrameFillMode:
  14294. return this._gl.LINES;
  14295. // Draw modes
  14296. case BABYLON.Material.PointListDrawMode:
  14297. return this._gl.POINTS;
  14298. case BABYLON.Material.LineListDrawMode:
  14299. return this._gl.LINES;
  14300. case BABYLON.Material.LineLoopDrawMode:
  14301. return this._gl.LINE_LOOP;
  14302. case BABYLON.Material.LineStripDrawMode:
  14303. return this._gl.LINE_STRIP;
  14304. case BABYLON.Material.TriangleStripDrawMode:
  14305. return this._gl.TRIANGLE_STRIP;
  14306. case BABYLON.Material.TriangleFanDrawMode:
  14307. return this._gl.TRIANGLE_FAN;
  14308. default:
  14309. return this._gl.TRIANGLES;
  14310. }
  14311. };
  14312. // Shaders
  14313. /** @hidden */
  14314. Engine.prototype._releaseEffect = function (effect) {
  14315. if (this._compiledEffects[effect._key]) {
  14316. delete this._compiledEffects[effect._key];
  14317. this._deleteProgram(effect.getProgram());
  14318. }
  14319. };
  14320. /** @hidden */
  14321. Engine.prototype._deleteProgram = function (program) {
  14322. if (program) {
  14323. program.__SPECTOR_rebuildProgram = null;
  14324. if (program.transformFeedback) {
  14325. this.deleteTransformFeedback(program.transformFeedback);
  14326. program.transformFeedback = null;
  14327. }
  14328. this._gl.deleteProgram(program);
  14329. }
  14330. };
  14331. /**
  14332. * Create a new effect (used to store vertex/fragment shaders)
  14333. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14334. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14335. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14336. * @param samplers defines an array of string used to represent textures
  14337. * @param defines defines the string containing the defines to use to compile the shaders
  14338. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14339. * @param onCompiled defines a function to call when the effect creation is successful
  14340. * @param onError defines a function to call when the effect creation has failed
  14341. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14342. * @returns the new Effect
  14343. */
  14344. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14345. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14346. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14347. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14348. if (this._compiledEffects[name]) {
  14349. var compiledEffect = this._compiledEffects[name];
  14350. if (onCompiled && compiledEffect.isReady()) {
  14351. onCompiled(compiledEffect);
  14352. }
  14353. return compiledEffect;
  14354. }
  14355. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14356. effect._key = name;
  14357. this._compiledEffects[name] = effect;
  14358. return effect;
  14359. };
  14360. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  14361. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  14362. };
  14363. ;
  14364. Engine.prototype._compileRawShader = function (source, type) {
  14365. var gl = this._gl;
  14366. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  14367. gl.shaderSource(shader, source);
  14368. gl.compileShader(shader);
  14369. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  14370. var log = gl.getShaderInfoLog(shader);
  14371. if (log) {
  14372. throw new Error(log);
  14373. }
  14374. }
  14375. if (!shader) {
  14376. throw new Error("Something went wrong while compile the shader.");
  14377. }
  14378. return shader;
  14379. };
  14380. ;
  14381. /**
  14382. * Directly creates a webGL program
  14383. * @param vertexCode defines the vertex shader code to use
  14384. * @param fragmentCode defines the fragment shader code to use
  14385. * @param context defines the webGL context to use (if not set, the current one will be used)
  14386. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14387. * @returns the new webGL program
  14388. */
  14389. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14390. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14391. context = context || this._gl;
  14392. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  14393. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  14394. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14395. };
  14396. /**
  14397. * Creates a webGL program
  14398. * @param vertexCode defines the vertex shader code to use
  14399. * @param fragmentCode defines the fragment shader code to use
  14400. * @param defines defines the string containing the defines to use to compile the shaders
  14401. * @param context defines the webGL context to use (if not set, the current one will be used)
  14402. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14403. * @returns the new webGL program
  14404. */
  14405. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14406. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14407. context = context || this._gl;
  14408. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14409. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14410. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  14411. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  14412. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14413. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14414. return program;
  14415. };
  14416. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14417. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14418. var shaderProgram = context.createProgram();
  14419. if (!shaderProgram) {
  14420. throw new Error("Unable to create program");
  14421. }
  14422. context.attachShader(shaderProgram, vertexShader);
  14423. context.attachShader(shaderProgram, fragmentShader);
  14424. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14425. var transformFeedback = this.createTransformFeedback();
  14426. this.bindTransformFeedback(transformFeedback);
  14427. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14428. shaderProgram.transformFeedback = transformFeedback;
  14429. }
  14430. context.linkProgram(shaderProgram);
  14431. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14432. this.bindTransformFeedback(null);
  14433. }
  14434. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14435. if (!linked) {
  14436. var error = context.getProgramInfoLog(shaderProgram);
  14437. if (error) {
  14438. throw new Error(error);
  14439. }
  14440. }
  14441. if (this.validateShaderPrograms) {
  14442. context.validateProgram(shaderProgram);
  14443. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14444. if (!validated) {
  14445. var error = context.getProgramInfoLog(shaderProgram);
  14446. if (error) {
  14447. throw new Error(error);
  14448. }
  14449. }
  14450. }
  14451. context.deleteShader(vertexShader);
  14452. context.deleteShader(fragmentShader);
  14453. return shaderProgram;
  14454. };
  14455. /**
  14456. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14457. * @param shaderProgram defines the webGL program to use
  14458. * @param uniformsNames defines the list of uniform names
  14459. * @returns an array of webGL uniform locations
  14460. */
  14461. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14462. var results = new Array();
  14463. for (var index = 0; index < uniformsNames.length; index++) {
  14464. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14465. }
  14466. return results;
  14467. };
  14468. /**
  14469. * Gets the lsit of active attributes for a given webGL program
  14470. * @param shaderProgram defines the webGL program to use
  14471. * @param attributesNames defines the list of attribute names to get
  14472. * @returns an array of indices indicating the offset of each attribute
  14473. */
  14474. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14475. var results = [];
  14476. for (var index = 0; index < attributesNames.length; index++) {
  14477. try {
  14478. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14479. }
  14480. catch (e) {
  14481. results.push(-1);
  14482. }
  14483. }
  14484. return results;
  14485. };
  14486. /**
  14487. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14488. * @param effect defines the effect to activate
  14489. */
  14490. Engine.prototype.enableEffect = function (effect) {
  14491. if (!effect || effect === this._currentEffect) {
  14492. return;
  14493. }
  14494. // Use program
  14495. this.bindSamplers(effect);
  14496. this._currentEffect = effect;
  14497. if (effect.onBind) {
  14498. effect.onBind(effect);
  14499. }
  14500. if (effect._onBindObservable) {
  14501. effect._onBindObservable.notifyObservers(effect);
  14502. }
  14503. };
  14504. /**
  14505. * Set the value of an uniform to an array of int32
  14506. * @param uniform defines the webGL uniform location where to store the value
  14507. * @param array defines the array of int32 to store
  14508. */
  14509. Engine.prototype.setIntArray = function (uniform, array) {
  14510. if (!uniform)
  14511. return;
  14512. this._gl.uniform1iv(uniform, array);
  14513. };
  14514. /**
  14515. * Set the value of an uniform to an array of int32 (stored as vec2)
  14516. * @param uniform defines the webGL uniform location where to store the value
  14517. * @param array defines the array of int32 to store
  14518. */
  14519. Engine.prototype.setIntArray2 = function (uniform, array) {
  14520. if (!uniform || array.length % 2 !== 0)
  14521. return;
  14522. this._gl.uniform2iv(uniform, array);
  14523. };
  14524. /**
  14525. * Set the value of an uniform to an array of int32 (stored as vec3)
  14526. * @param uniform defines the webGL uniform location where to store the value
  14527. * @param array defines the array of int32 to store
  14528. */
  14529. Engine.prototype.setIntArray3 = function (uniform, array) {
  14530. if (!uniform || array.length % 3 !== 0)
  14531. return;
  14532. this._gl.uniform3iv(uniform, array);
  14533. };
  14534. /**
  14535. * Set the value of an uniform to an array of int32 (stored as vec4)
  14536. * @param uniform defines the webGL uniform location where to store the value
  14537. * @param array defines the array of int32 to store
  14538. */
  14539. Engine.prototype.setIntArray4 = function (uniform, array) {
  14540. if (!uniform || array.length % 4 !== 0)
  14541. return;
  14542. this._gl.uniform4iv(uniform, array);
  14543. };
  14544. /**
  14545. * Set the value of an uniform to an array of float32
  14546. * @param uniform defines the webGL uniform location where to store the value
  14547. * @param array defines the array of float32 to store
  14548. */
  14549. Engine.prototype.setFloatArray = function (uniform, array) {
  14550. if (!uniform)
  14551. return;
  14552. this._gl.uniform1fv(uniform, array);
  14553. };
  14554. /**
  14555. * Set the value of an uniform to an array of float32 (stored as vec2)
  14556. * @param uniform defines the webGL uniform location where to store the value
  14557. * @param array defines the array of float32 to store
  14558. */
  14559. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14560. if (!uniform || array.length % 2 !== 0)
  14561. return;
  14562. this._gl.uniform2fv(uniform, array);
  14563. };
  14564. /**
  14565. * Set the value of an uniform to an array of float32 (stored as vec3)
  14566. * @param uniform defines the webGL uniform location where to store the value
  14567. * @param array defines the array of float32 to store
  14568. */
  14569. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14570. if (!uniform || array.length % 3 !== 0)
  14571. return;
  14572. this._gl.uniform3fv(uniform, array);
  14573. };
  14574. /**
  14575. * Set the value of an uniform to an array of float32 (stored as vec4)
  14576. * @param uniform defines the webGL uniform location where to store the value
  14577. * @param array defines the array of float32 to store
  14578. */
  14579. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14580. if (!uniform || array.length % 4 !== 0)
  14581. return;
  14582. this._gl.uniform4fv(uniform, array);
  14583. };
  14584. /**
  14585. * Set the value of an uniform to an array of number
  14586. * @param uniform defines the webGL uniform location where to store the value
  14587. * @param array defines the array of number to store
  14588. */
  14589. Engine.prototype.setArray = function (uniform, array) {
  14590. if (!uniform)
  14591. return;
  14592. this._gl.uniform1fv(uniform, array);
  14593. };
  14594. /**
  14595. * Set the value of an uniform to an array of number (stored as vec2)
  14596. * @param uniform defines the webGL uniform location where to store the value
  14597. * @param array defines the array of number to store
  14598. */
  14599. Engine.prototype.setArray2 = function (uniform, array) {
  14600. if (!uniform || array.length % 2 !== 0)
  14601. return;
  14602. this._gl.uniform2fv(uniform, array);
  14603. };
  14604. /**
  14605. * Set the value of an uniform to an array of number (stored as vec3)
  14606. * @param uniform defines the webGL uniform location where to store the value
  14607. * @param array defines the array of number to store
  14608. */
  14609. Engine.prototype.setArray3 = function (uniform, array) {
  14610. if (!uniform || array.length % 3 !== 0)
  14611. return;
  14612. this._gl.uniform3fv(uniform, array);
  14613. };
  14614. /**
  14615. * Set the value of an uniform to an array of number (stored as vec4)
  14616. * @param uniform defines the webGL uniform location where to store the value
  14617. * @param array defines the array of number to store
  14618. */
  14619. Engine.prototype.setArray4 = function (uniform, array) {
  14620. if (!uniform || array.length % 4 !== 0)
  14621. return;
  14622. this._gl.uniform4fv(uniform, array);
  14623. };
  14624. /**
  14625. * Set the value of an uniform to an array of float32 (stored as matrices)
  14626. * @param uniform defines the webGL uniform location where to store the value
  14627. * @param matrices defines the array of float32 to store
  14628. */
  14629. Engine.prototype.setMatrices = function (uniform, matrices) {
  14630. if (!uniform)
  14631. return;
  14632. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14633. };
  14634. /**
  14635. * Set the value of an uniform to a matrix
  14636. * @param uniform defines the webGL uniform location where to store the value
  14637. * @param matrix defines the matrix to store
  14638. */
  14639. Engine.prototype.setMatrix = function (uniform, matrix) {
  14640. if (!uniform)
  14641. return;
  14642. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14643. };
  14644. /**
  14645. * Set the value of an uniform to a matrix (3x3)
  14646. * @param uniform defines the webGL uniform location where to store the value
  14647. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14648. */
  14649. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14650. if (!uniform)
  14651. return;
  14652. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14653. };
  14654. /**
  14655. * Set the value of an uniform to a matrix (2x2)
  14656. * @param uniform defines the webGL uniform location where to store the value
  14657. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14658. */
  14659. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14660. if (!uniform)
  14661. return;
  14662. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14663. };
  14664. /**
  14665. * Set the value of an uniform to a number (int)
  14666. * @param uniform defines the webGL uniform location where to store the value
  14667. * @param value defines the int number to store
  14668. */
  14669. Engine.prototype.setInt = function (uniform, value) {
  14670. if (!uniform)
  14671. return;
  14672. this._gl.uniform1i(uniform, value);
  14673. };
  14674. /**
  14675. * Set the value of an uniform to a number (float)
  14676. * @param uniform defines the webGL uniform location where to store the value
  14677. * @param value defines the float number to store
  14678. */
  14679. Engine.prototype.setFloat = function (uniform, value) {
  14680. if (!uniform)
  14681. return;
  14682. this._gl.uniform1f(uniform, value);
  14683. };
  14684. /**
  14685. * Set the value of an uniform to a vec2
  14686. * @param uniform defines the webGL uniform location where to store the value
  14687. * @param x defines the 1st component of the value
  14688. * @param y defines the 2nd component of the value
  14689. */
  14690. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14691. if (!uniform)
  14692. return;
  14693. this._gl.uniform2f(uniform, x, y);
  14694. };
  14695. /**
  14696. * Set the value of an uniform to a vec3
  14697. * @param uniform defines the webGL uniform location where to store the value
  14698. * @param x defines the 1st component of the value
  14699. * @param y defines the 2nd component of the value
  14700. * @param z defines the 3rd component of the value
  14701. */
  14702. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14703. if (!uniform)
  14704. return;
  14705. this._gl.uniform3f(uniform, x, y, z);
  14706. };
  14707. /**
  14708. * Set the value of an uniform to a boolean
  14709. * @param uniform defines the webGL uniform location where to store the value
  14710. * @param bool defines the boolean to store
  14711. */
  14712. Engine.prototype.setBool = function (uniform, bool) {
  14713. if (!uniform)
  14714. return;
  14715. this._gl.uniform1i(uniform, bool);
  14716. };
  14717. /**
  14718. * Set the value of an uniform to a vec4
  14719. * @param uniform defines the webGL uniform location where to store the value
  14720. * @param x defines the 1st component of the value
  14721. * @param y defines the 2nd component of the value
  14722. * @param z defines the 3rd component of the value
  14723. * @param w defines the 4th component of the value
  14724. */
  14725. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14726. if (!uniform)
  14727. return;
  14728. this._gl.uniform4f(uniform, x, y, z, w);
  14729. };
  14730. /**
  14731. * Set the value of an uniform to a Color3
  14732. * @param uniform defines the webGL uniform location where to store the value
  14733. * @param color3 defines the color to store
  14734. */
  14735. Engine.prototype.setColor3 = function (uniform, color3) {
  14736. if (!uniform)
  14737. return;
  14738. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14739. };
  14740. /**
  14741. * Set the value of an uniform to a Color3 and an alpha value
  14742. * @param uniform defines the webGL uniform location where to store the value
  14743. * @param color3 defines the color to store
  14744. * @param alpha defines the alpha component to store
  14745. */
  14746. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14747. if (!uniform)
  14748. return;
  14749. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14750. };
  14751. /**
  14752. * Sets a Color4 on a uniform variable
  14753. * @param uniform defines the uniform location
  14754. * @param color4 defines the value to be set
  14755. */
  14756. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14757. if (!uniform)
  14758. return;
  14759. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14760. };
  14761. // States
  14762. /**
  14763. * Set various states to the webGL context
  14764. * @param culling defines backface culling state
  14765. * @param zOffset defines the value to apply to zOffset (0 by default)
  14766. * @param force defines if states must be applied even if cache is up to date
  14767. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14768. */
  14769. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14770. if (zOffset === void 0) { zOffset = 0; }
  14771. if (reverseSide === void 0) { reverseSide = false; }
  14772. // Culling
  14773. if (this._depthCullingState.cull !== culling || force) {
  14774. this._depthCullingState.cull = culling;
  14775. }
  14776. // Cull face
  14777. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14778. if (this._depthCullingState.cullFace !== cullFace || force) {
  14779. this._depthCullingState.cullFace = cullFace;
  14780. }
  14781. // Z offset
  14782. this.setZOffset(zOffset);
  14783. // Front face
  14784. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14785. if (this._depthCullingState.frontFace !== frontFace || force) {
  14786. this._depthCullingState.frontFace = frontFace;
  14787. }
  14788. };
  14789. /**
  14790. * Set the z offset to apply to current rendering
  14791. * @param value defines the offset to apply
  14792. */
  14793. Engine.prototype.setZOffset = function (value) {
  14794. this._depthCullingState.zOffset = value;
  14795. };
  14796. /**
  14797. * Gets the current value of the zOffset
  14798. * @returns the current zOffset state
  14799. */
  14800. Engine.prototype.getZOffset = function () {
  14801. return this._depthCullingState.zOffset;
  14802. };
  14803. /**
  14804. * Enable or disable depth buffering
  14805. * @param enable defines the state to set
  14806. */
  14807. Engine.prototype.setDepthBuffer = function (enable) {
  14808. this._depthCullingState.depthTest = enable;
  14809. };
  14810. /**
  14811. * Gets a boolean indicating if depth writing is enabled
  14812. * @returns the current depth writing state
  14813. */
  14814. Engine.prototype.getDepthWrite = function () {
  14815. return this._depthCullingState.depthMask;
  14816. };
  14817. /**
  14818. * Enable or disable depth writing
  14819. * @param enable defines the state to set
  14820. */
  14821. Engine.prototype.setDepthWrite = function (enable) {
  14822. this._depthCullingState.depthMask = enable;
  14823. };
  14824. /**
  14825. * Enable or disable color writing
  14826. * @param enable defines the state to set
  14827. */
  14828. Engine.prototype.setColorWrite = function (enable) {
  14829. this._gl.colorMask(enable, enable, enable, enable);
  14830. this._colorWrite = enable;
  14831. };
  14832. /**
  14833. * Gets a boolean indicating if color writing is enabled
  14834. * @returns the current color writing state
  14835. */
  14836. Engine.prototype.getColorWrite = function () {
  14837. return this._colorWrite;
  14838. };
  14839. /**
  14840. * Sets alpha constants used by some alpha blending modes
  14841. * @param r defines the red component
  14842. * @param g defines the green component
  14843. * @param b defines the blue component
  14844. * @param a defines the alpha component
  14845. */
  14846. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14847. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14848. };
  14849. /**
  14850. * Sets the current alpha mode
  14851. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14852. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14853. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14854. */
  14855. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14856. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14857. if (this._alphaMode === mode) {
  14858. return;
  14859. }
  14860. switch (mode) {
  14861. case Engine.ALPHA_DISABLE:
  14862. this._alphaState.alphaBlend = false;
  14863. break;
  14864. case Engine.ALPHA_PREMULTIPLIED:
  14865. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14866. this._alphaState.alphaBlend = true;
  14867. break;
  14868. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14869. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14870. this._alphaState.alphaBlend = true;
  14871. break;
  14872. case Engine.ALPHA_COMBINE:
  14873. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14874. this._alphaState.alphaBlend = true;
  14875. break;
  14876. case Engine.ALPHA_ONEONE:
  14877. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14878. this._alphaState.alphaBlend = true;
  14879. break;
  14880. case Engine.ALPHA_ADD:
  14881. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14882. this._alphaState.alphaBlend = true;
  14883. break;
  14884. case Engine.ALPHA_SUBTRACT:
  14885. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14886. this._alphaState.alphaBlend = true;
  14887. break;
  14888. case Engine.ALPHA_MULTIPLY:
  14889. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14890. this._alphaState.alphaBlend = true;
  14891. break;
  14892. case Engine.ALPHA_MAXIMIZED:
  14893. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14894. this._alphaState.alphaBlend = true;
  14895. break;
  14896. case Engine.ALPHA_INTERPOLATE:
  14897. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14898. this._alphaState.alphaBlend = true;
  14899. break;
  14900. case Engine.ALPHA_SCREENMODE:
  14901. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14902. this._alphaState.alphaBlend = true;
  14903. break;
  14904. }
  14905. if (!noDepthWriteChange) {
  14906. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14907. }
  14908. this._alphaMode = mode;
  14909. };
  14910. /**
  14911. * Gets the current alpha mode
  14912. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14913. * @returns the current alpha mode
  14914. */
  14915. Engine.prototype.getAlphaMode = function () {
  14916. return this._alphaMode;
  14917. };
  14918. // Textures
  14919. /**
  14920. * Clears the list of texture accessible through engine.
  14921. * This can help preventing texture load conflict due to name collision.
  14922. */
  14923. Engine.prototype.clearInternalTexturesCache = function () {
  14924. this._internalTexturesCache = [];
  14925. };
  14926. /**
  14927. * Force the entire cache to be cleared
  14928. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14929. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14930. */
  14931. Engine.prototype.wipeCaches = function (bruteForce) {
  14932. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14933. return;
  14934. }
  14935. this._currentEffect = null;
  14936. this._viewportCached.x = 0;
  14937. this._viewportCached.y = 0;
  14938. this._viewportCached.z = 0;
  14939. this._viewportCached.w = 0;
  14940. if (bruteForce) {
  14941. this.resetTextureCache();
  14942. this._currentProgram = null;
  14943. this._stencilState.reset();
  14944. this._depthCullingState.reset();
  14945. this.setDepthFunctionToLessOrEqual();
  14946. this._alphaState.reset();
  14947. this._unpackFlipYCached = null;
  14948. }
  14949. this._resetVertexBufferBinding();
  14950. this._cachedIndexBuffer = null;
  14951. this._cachedEffectForVertexBuffers = null;
  14952. this._unbindVertexArrayObject();
  14953. this.bindIndexBuffer(null);
  14954. };
  14955. /**
  14956. * Set the compressed texture format to use, based on the formats you have, and the formats
  14957. * supported by the hardware / browser.
  14958. *
  14959. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14960. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14961. * to API arguments needed to compressed textures. This puts the burden on the container
  14962. * generator to house the arcane code for determining these for current & future formats.
  14963. *
  14964. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14965. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14966. *
  14967. * Note: The result of this call is not taken into account when a texture is base64.
  14968. *
  14969. * @param formatsAvailable defines the list of those format families you have created
  14970. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14971. *
  14972. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14973. * @returns The extension selected.
  14974. */
  14975. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14976. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14977. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14978. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14979. return this._textureFormatInUse = this._texturesSupported[i];
  14980. }
  14981. }
  14982. }
  14983. // actively set format to nothing, to allow this to be called more than once
  14984. // and possibly fail the 2nd time
  14985. this._textureFormatInUse = null;
  14986. return null;
  14987. };
  14988. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14989. var gl = this._gl;
  14990. var magFilter = gl.NEAREST;
  14991. var minFilter = gl.NEAREST;
  14992. switch (samplingMode) {
  14993. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14994. magFilter = gl.LINEAR;
  14995. if (generateMipMaps) {
  14996. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14997. }
  14998. else {
  14999. minFilter = gl.LINEAR;
  15000. }
  15001. break;
  15002. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  15003. magFilter = gl.LINEAR;
  15004. if (generateMipMaps) {
  15005. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15006. }
  15007. else {
  15008. minFilter = gl.LINEAR;
  15009. }
  15010. break;
  15011. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  15012. magFilter = gl.NEAREST;
  15013. if (generateMipMaps) {
  15014. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15015. }
  15016. else {
  15017. minFilter = gl.NEAREST;
  15018. }
  15019. break;
  15020. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  15021. magFilter = gl.NEAREST;
  15022. if (generateMipMaps) {
  15023. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15024. }
  15025. else {
  15026. minFilter = gl.NEAREST;
  15027. }
  15028. break;
  15029. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  15030. magFilter = gl.NEAREST;
  15031. if (generateMipMaps) {
  15032. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15033. }
  15034. else {
  15035. minFilter = gl.LINEAR;
  15036. }
  15037. break;
  15038. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  15039. magFilter = gl.NEAREST;
  15040. if (generateMipMaps) {
  15041. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15042. }
  15043. else {
  15044. minFilter = gl.LINEAR;
  15045. }
  15046. break;
  15047. case Engine.TEXTURE_NEAREST_LINEAR:
  15048. magFilter = gl.NEAREST;
  15049. minFilter = gl.LINEAR;
  15050. break;
  15051. case Engine.TEXTURE_NEAREST_NEAREST:
  15052. magFilter = gl.NEAREST;
  15053. minFilter = gl.NEAREST;
  15054. break;
  15055. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  15056. magFilter = gl.LINEAR;
  15057. if (generateMipMaps) {
  15058. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15059. }
  15060. else {
  15061. minFilter = gl.NEAREST;
  15062. }
  15063. break;
  15064. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  15065. magFilter = gl.LINEAR;
  15066. if (generateMipMaps) {
  15067. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15068. }
  15069. else {
  15070. minFilter = gl.NEAREST;
  15071. }
  15072. break;
  15073. case Engine.TEXTURE_LINEAR_LINEAR:
  15074. magFilter = gl.LINEAR;
  15075. minFilter = gl.LINEAR;
  15076. break;
  15077. case Engine.TEXTURE_LINEAR_NEAREST:
  15078. magFilter = gl.LINEAR;
  15079. minFilter = gl.NEAREST;
  15080. break;
  15081. }
  15082. return {
  15083. min: minFilter,
  15084. mag: magFilter
  15085. };
  15086. };
  15087. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  15088. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15089. var img;
  15090. var onload = function () {
  15091. loadedImages[index] = img;
  15092. loadedImages._internalCount++;
  15093. if (scene) {
  15094. scene._removePendingData(img);
  15095. }
  15096. if (loadedImages._internalCount === 6) {
  15097. onfinish(loadedImages);
  15098. }
  15099. };
  15100. var onerror = function (message, exception) {
  15101. if (scene) {
  15102. scene._removePendingData(img);
  15103. }
  15104. if (onErrorCallBack) {
  15105. onErrorCallBack(message, exception);
  15106. }
  15107. };
  15108. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  15109. if (scene) {
  15110. scene._addPendingData(img);
  15111. }
  15112. };
  15113. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  15114. if (onError === void 0) { onError = null; }
  15115. var loadedImages = [];
  15116. loadedImages._internalCount = 0;
  15117. for (var index = 0; index < 6; index++) {
  15118. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  15119. }
  15120. };
  15121. ;
  15122. /** @hidden */
  15123. Engine.prototype._createTexture = function () {
  15124. var texture = this._gl.createTexture();
  15125. if (!texture) {
  15126. throw new Error("Unable to create texture");
  15127. }
  15128. return texture;
  15129. };
  15130. /**
  15131. * Usually called from BABYLON.Texture.ts.
  15132. * Passed information to create a WebGLTexture
  15133. * @param urlArg defines a value which contains one of the following:
  15134. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  15135. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  15136. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  15137. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  15138. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  15139. * @param scene needed for loading to the correct scene
  15140. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  15141. * @param onLoad optional callback to be called upon successful completion
  15142. * @param onError optional callback to be called upon failure
  15143. * @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
  15144. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  15145. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  15146. * @param forcedExtension defines the extension to use to pick the right loader
  15147. * @returns a InternalTexture for assignment back into BABYLON.Texture
  15148. */
  15149. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  15150. var _this = this;
  15151. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15152. if (onLoad === void 0) { onLoad = null; }
  15153. if (onError === void 0) { onError = null; }
  15154. if (buffer === void 0) { buffer = null; }
  15155. if (fallback === void 0) { fallback = null; }
  15156. if (format === void 0) { format = null; }
  15157. if (forcedExtension === void 0) { forcedExtension = null; }
  15158. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  15159. var fromData = url.substr(0, 5) === "data:";
  15160. var fromBlob = url.substr(0, 5) === "blob:";
  15161. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  15162. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  15163. // establish the file extension, if possible
  15164. var lastDot = url.lastIndexOf('.');
  15165. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  15166. var loader = null;
  15167. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15168. var availableLoader = _a[_i];
  15169. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  15170. loader = availableLoader;
  15171. break;
  15172. }
  15173. }
  15174. if (loader) {
  15175. url = loader.transformUrl(url, this._textureFormatInUse);
  15176. }
  15177. if (scene) {
  15178. scene._addPendingData(texture);
  15179. }
  15180. texture.url = url;
  15181. texture.generateMipMaps = !noMipmap;
  15182. texture.samplingMode = samplingMode;
  15183. texture.invertY = invertY;
  15184. if (!this._doNotHandleContextLost) {
  15185. // Keep a link to the buffer only if we plan to handle context lost
  15186. texture._buffer = buffer;
  15187. }
  15188. var onLoadObserver = null;
  15189. if (onLoad && !fallback) {
  15190. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  15191. }
  15192. if (!fallback)
  15193. this._internalTexturesCache.push(texture);
  15194. var onInternalError = function (message, exception) {
  15195. if (scene) {
  15196. scene._removePendingData(texture);
  15197. }
  15198. var customFallback = false;
  15199. if (loader) {
  15200. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  15201. if (fallbackUrl) {
  15202. // Add Back
  15203. customFallback = true;
  15204. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15205. }
  15206. }
  15207. if (!customFallback) {
  15208. if (onLoadObserver) {
  15209. texture.onLoadedObservable.remove(onLoadObserver);
  15210. }
  15211. if (BABYLON.Tools.UseFallbackTexture) {
  15212. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15213. }
  15214. }
  15215. if (onError) {
  15216. onError(message || "Unknown error", exception);
  15217. }
  15218. };
  15219. // processing for non-image formats
  15220. if (loader) {
  15221. var callback = function (data) {
  15222. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  15223. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  15224. done();
  15225. return false;
  15226. }, samplingMode);
  15227. });
  15228. };
  15229. if (!buffer) {
  15230. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  15231. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  15232. });
  15233. }
  15234. else {
  15235. callback(buffer);
  15236. }
  15237. }
  15238. else {
  15239. var onload = function (img) {
  15240. if (fromBlob && !_this._doNotHandleContextLost) {
  15241. // We need to store the image if we need to rebuild the texture
  15242. // in case of a webgl context lost
  15243. texture._buffer = img;
  15244. }
  15245. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  15246. var gl = _this._gl;
  15247. var isPot = (img.width === potWidth && img.height === potHeight);
  15248. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  15249. if (isPot) {
  15250. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15251. return false;
  15252. }
  15253. var maxTextureSize = _this._caps.maxTextureSize;
  15254. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  15255. _this._prepareWorkingCanvas();
  15256. if (!_this._workingCanvas || !_this._workingContext) {
  15257. return false;
  15258. }
  15259. _this._workingCanvas.width = potWidth;
  15260. _this._workingCanvas.height = potHeight;
  15261. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  15262. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15263. texture.width = potWidth;
  15264. texture.height = potHeight;
  15265. return false;
  15266. }
  15267. else {
  15268. // Using shaders when possible to rescale because canvas.drawImage is lossy
  15269. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15270. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  15271. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15272. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15273. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15274. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15275. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15276. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  15277. _this._releaseTexture(source_1);
  15278. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15279. continuationCallback();
  15280. });
  15281. }
  15282. return true;
  15283. }, samplingMode);
  15284. };
  15285. if (!fromData || isBase64) {
  15286. if (buffer instanceof HTMLImageElement) {
  15287. onload(buffer);
  15288. }
  15289. else {
  15290. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  15291. }
  15292. }
  15293. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  15294. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  15295. }
  15296. else {
  15297. onload(buffer);
  15298. }
  15299. }
  15300. return texture;
  15301. };
  15302. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  15303. var _this = this;
  15304. var rtt = this.createRenderTargetTexture({
  15305. width: destination.width,
  15306. height: destination.height,
  15307. }, {
  15308. generateMipMaps: false,
  15309. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  15310. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  15311. generateDepthBuffer: false,
  15312. generateStencilBuffer: false
  15313. });
  15314. if (!this._rescalePostProcess) {
  15315. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  15316. }
  15317. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  15318. _this._rescalePostProcess.onApply = function (effect) {
  15319. effect._bindTexture("textureSampler", source);
  15320. };
  15321. var hostingScene = scene;
  15322. if (!hostingScene) {
  15323. hostingScene = _this.scenes[_this.scenes.length - 1];
  15324. }
  15325. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  15326. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  15327. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  15328. _this.unBindFramebuffer(rtt);
  15329. _this._releaseTexture(rtt);
  15330. if (onComplete) {
  15331. onComplete();
  15332. }
  15333. });
  15334. };
  15335. /**
  15336. * Update a raw texture
  15337. * @param texture defines the texture to update
  15338. * @param data defines the data to store in the texture
  15339. * @param format defines the format of the data
  15340. * @param invertY defines if data must be stored with Y axis inverted
  15341. * @param compression defines the compression used (null by default)
  15342. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15343. */
  15344. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  15345. if (compression === void 0) { compression = null; }
  15346. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15347. if (!texture) {
  15348. return;
  15349. }
  15350. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15351. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15352. // babylon's internalFormat but gl's texImage2D format
  15353. var internalFormat = this._getInternalFormat(format);
  15354. var textureType = this._getWebGLTextureType(type);
  15355. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15356. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15357. if (!this._doNotHandleContextLost) {
  15358. texture._bufferView = data;
  15359. texture.format = format;
  15360. texture.type = type;
  15361. texture.invertY = invertY;
  15362. texture._compression = compression;
  15363. }
  15364. if (texture.width % 4 !== 0) {
  15365. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15366. }
  15367. if (compression && data) {
  15368. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15369. }
  15370. else {
  15371. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15372. }
  15373. if (texture.generateMipMaps) {
  15374. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15375. }
  15376. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15377. // this.resetTextureCache();
  15378. texture.isReady = true;
  15379. };
  15380. /**
  15381. * Creates a raw texture
  15382. * @param data defines the data to store in the texture
  15383. * @param width defines the width of the texture
  15384. * @param height defines the height of the texture
  15385. * @param format defines the format of the data
  15386. * @param generateMipMaps defines if the engine should generate the mip levels
  15387. * @param invertY defines if data must be stored with Y axis inverted
  15388. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15389. * @param compression defines the compression used (null by default)
  15390. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15391. * @returns the raw texture inside an InternalTexture
  15392. */
  15393. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15394. if (compression === void 0) { compression = null; }
  15395. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15396. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15397. texture.baseWidth = width;
  15398. texture.baseHeight = height;
  15399. texture.width = width;
  15400. texture.height = height;
  15401. texture.format = format;
  15402. texture.generateMipMaps = generateMipMaps;
  15403. texture.samplingMode = samplingMode;
  15404. texture.invertY = invertY;
  15405. texture._compression = compression;
  15406. texture.type = type;
  15407. if (!this._doNotHandleContextLost) {
  15408. texture._bufferView = data;
  15409. }
  15410. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15411. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15412. // Filters
  15413. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15414. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15415. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15416. if (generateMipMaps) {
  15417. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15418. }
  15419. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15420. this._internalTexturesCache.push(texture);
  15421. return texture;
  15422. };
  15423. /** @hidden */
  15424. Engine.prototype._unpackFlipY = function (value) {
  15425. if (this._unpackFlipYCached !== value) {
  15426. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15427. if (this.enableUnpackFlipYCached) {
  15428. this._unpackFlipYCached = value;
  15429. }
  15430. }
  15431. };
  15432. /** @hidden */
  15433. Engine.prototype._getUnpackAlignement = function () {
  15434. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  15435. };
  15436. /**
  15437. * Creates a dynamic texture
  15438. * @param width defines the width of the texture
  15439. * @param height defines the height of the texture
  15440. * @param generateMipMaps defines if the engine should generate the mip levels
  15441. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15442. * @returns the dynamic texture inside an InternalTexture
  15443. */
  15444. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15445. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15446. texture.baseWidth = width;
  15447. texture.baseHeight = height;
  15448. if (generateMipMaps) {
  15449. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15450. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15451. }
  15452. // this.resetTextureCache();
  15453. texture.width = width;
  15454. texture.height = height;
  15455. texture.isReady = false;
  15456. texture.generateMipMaps = generateMipMaps;
  15457. texture.samplingMode = samplingMode;
  15458. this.updateTextureSamplingMode(samplingMode, texture);
  15459. this._internalTexturesCache.push(texture);
  15460. return texture;
  15461. };
  15462. /**
  15463. * Update the sampling mode of a given texture
  15464. * @param samplingMode defines the required sampling mode
  15465. * @param texture defines the texture to update
  15466. */
  15467. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15468. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  15469. if (texture.isCube) {
  15470. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15471. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15472. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15473. }
  15474. else if (texture.is3D) {
  15475. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15476. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15477. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15478. }
  15479. else {
  15480. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15481. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15482. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15483. }
  15484. texture.samplingMode = samplingMode;
  15485. };
  15486. /**
  15487. * Update the content of a dynamic texture
  15488. * @param texture defines the texture to update
  15489. * @param canvas defines the canvas containing the source
  15490. * @param invertY defines if data must be stored with Y axis inverted
  15491. * @param premulAlpha defines if alpha is stored as premultiplied
  15492. * @param format defines the format of the data
  15493. */
  15494. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15495. if (premulAlpha === void 0) { premulAlpha = false; }
  15496. if (!texture) {
  15497. return;
  15498. }
  15499. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15500. this._unpackFlipY(invertY);
  15501. if (premulAlpha) {
  15502. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15503. }
  15504. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15505. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15506. if (texture.generateMipMaps) {
  15507. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15508. }
  15509. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15510. if (premulAlpha) {
  15511. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15512. }
  15513. texture.isReady = true;
  15514. };
  15515. /**
  15516. * Update a video texture
  15517. * @param texture defines the texture to update
  15518. * @param video defines the video element to use
  15519. * @param invertY defines if data must be stored with Y axis inverted
  15520. */
  15521. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15522. if (!texture || texture._isDisabled) {
  15523. return;
  15524. }
  15525. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15526. this._unpackFlipY(!invertY); // Video are upside down by default
  15527. try {
  15528. // Testing video texture support
  15529. if (this._videoTextureSupported === undefined) {
  15530. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15531. if (this._gl.getError() !== 0) {
  15532. this._videoTextureSupported = false;
  15533. }
  15534. else {
  15535. this._videoTextureSupported = true;
  15536. }
  15537. }
  15538. // Copy video through the current working canvas if video texture is not supported
  15539. if (!this._videoTextureSupported) {
  15540. if (!texture._workingCanvas) {
  15541. texture._workingCanvas = document.createElement("canvas");
  15542. var context = texture._workingCanvas.getContext("2d");
  15543. if (!context) {
  15544. throw new Error("Unable to get 2d context");
  15545. }
  15546. texture._workingContext = context;
  15547. texture._workingCanvas.width = texture.width;
  15548. texture._workingCanvas.height = texture.height;
  15549. }
  15550. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15551. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15552. }
  15553. else {
  15554. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15555. }
  15556. if (texture.generateMipMaps) {
  15557. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15558. }
  15559. if (!wasPreviouslyBound) {
  15560. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15561. }
  15562. // this.resetTextureCache();
  15563. texture.isReady = true;
  15564. }
  15565. catch (ex) {
  15566. // Something unexpected
  15567. // Let's disable the texture
  15568. texture._isDisabled = true;
  15569. }
  15570. };
  15571. /**
  15572. * Updates a depth texture Comparison Mode and Function.
  15573. * If the comparison Function is equal to 0, the mode will be set to none.
  15574. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15575. * @param texture The texture to set the comparison function for
  15576. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15577. */
  15578. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15579. if (this.webGLVersion === 1) {
  15580. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15581. return;
  15582. }
  15583. var gl = this._gl;
  15584. if (texture.isCube) {
  15585. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15586. if (comparisonFunction === 0) {
  15587. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15588. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15589. }
  15590. else {
  15591. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15592. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15593. }
  15594. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15595. }
  15596. else {
  15597. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15598. if (comparisonFunction === 0) {
  15599. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15600. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15601. }
  15602. else {
  15603. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15604. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15605. }
  15606. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15607. }
  15608. texture._comparisonFunction = comparisonFunction;
  15609. };
  15610. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15611. var width = size.width || size;
  15612. var height = size.height || size;
  15613. internalTexture.baseWidth = width;
  15614. internalTexture.baseHeight = height;
  15615. internalTexture.width = width;
  15616. internalTexture.height = height;
  15617. internalTexture.isReady = true;
  15618. internalTexture.samples = 1;
  15619. internalTexture.generateMipMaps = false;
  15620. internalTexture._generateDepthBuffer = true;
  15621. internalTexture._generateStencilBuffer = generateStencil;
  15622. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15623. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15624. internalTexture._comparisonFunction = comparisonFunction;
  15625. var gl = this._gl;
  15626. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15627. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15628. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15629. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15630. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15631. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15632. if (comparisonFunction === 0) {
  15633. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15634. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15635. }
  15636. else {
  15637. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15638. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15639. }
  15640. };
  15641. /**
  15642. * Creates a depth stencil texture.
  15643. * This is only available in WebGL 2 or with the depth texture extension available.
  15644. * @param size The size of face edge in the texture.
  15645. * @param options The options defining the texture.
  15646. * @returns The texture
  15647. */
  15648. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15649. if (options.isCube) {
  15650. var width = size.width || size;
  15651. return this._createDepthStencilCubeTexture(width, options);
  15652. }
  15653. else {
  15654. return this._createDepthStencilTexture(size, options);
  15655. }
  15656. };
  15657. /**
  15658. * Creates a depth stencil texture.
  15659. * This is only available in WebGL 2 or with the depth texture extension available.
  15660. * @param size The size of face edge in the texture.
  15661. * @param options The options defining the texture.
  15662. * @returns The texture
  15663. */
  15664. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15665. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15666. if (!this._caps.depthTextureExtension) {
  15667. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15668. return internalTexture;
  15669. }
  15670. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15671. var gl = this._gl;
  15672. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15673. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15674. if (this.webGLVersion > 1) {
  15675. if (internalOptions.generateStencil) {
  15676. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15677. }
  15678. else {
  15679. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15680. }
  15681. }
  15682. else {
  15683. if (internalOptions.generateStencil) {
  15684. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15685. }
  15686. else {
  15687. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15688. }
  15689. }
  15690. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15691. return internalTexture;
  15692. };
  15693. /**
  15694. * Creates a depth stencil cube texture.
  15695. * This is only available in WebGL 2.
  15696. * @param size The size of face edge in the cube texture.
  15697. * @param options The options defining the cube texture.
  15698. * @returns The cube texture
  15699. */
  15700. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15701. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15702. internalTexture.isCube = true;
  15703. if (this.webGLVersion === 1) {
  15704. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15705. return internalTexture;
  15706. }
  15707. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15708. var gl = this._gl;
  15709. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15710. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15711. // Create the depth/stencil buffer
  15712. for (var face = 0; face < 6; face++) {
  15713. if (internalOptions.generateStencil) {
  15714. 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);
  15715. }
  15716. else {
  15717. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15718. }
  15719. }
  15720. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15721. return internalTexture;
  15722. };
  15723. /**
  15724. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15725. * @param renderTarget The render target to set the frame buffer for
  15726. */
  15727. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15728. // Create the framebuffer
  15729. var internalTexture = renderTarget.getInternalTexture();
  15730. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15731. return;
  15732. }
  15733. var gl = this._gl;
  15734. var depthStencilTexture = renderTarget.depthStencilTexture;
  15735. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15736. if (depthStencilTexture.isCube) {
  15737. if (depthStencilTexture._generateStencilBuffer) {
  15738. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15739. }
  15740. else {
  15741. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15742. }
  15743. }
  15744. else {
  15745. if (depthStencilTexture._generateStencilBuffer) {
  15746. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15747. }
  15748. else {
  15749. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15750. }
  15751. }
  15752. this.bindUnboundFramebuffer(null);
  15753. };
  15754. /**
  15755. * Creates a new render target texture
  15756. * @param size defines the size of the texture
  15757. * @param options defines the options used to create the texture
  15758. * @returns a new render target texture stored in an InternalTexture
  15759. */
  15760. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15761. var fullOptions = new RenderTargetCreationOptions();
  15762. if (options !== undefined && typeof options === "object") {
  15763. fullOptions.generateMipMaps = options.generateMipMaps;
  15764. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15765. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15766. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15767. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15768. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15769. }
  15770. else {
  15771. fullOptions.generateMipMaps = options;
  15772. fullOptions.generateDepthBuffer = true;
  15773. fullOptions.generateStencilBuffer = false;
  15774. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15775. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15776. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15777. }
  15778. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15779. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15780. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15781. }
  15782. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15783. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15784. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15785. }
  15786. var gl = this._gl;
  15787. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15788. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15789. var width = size.width || size;
  15790. var height = size.height || size;
  15791. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15792. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15793. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15794. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15795. }
  15796. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15797. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15798. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15799. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15800. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15801. // Create the framebuffer
  15802. var currentFrameBuffer = this._currentFramebuffer;
  15803. var framebuffer = gl.createFramebuffer();
  15804. this.bindUnboundFramebuffer(framebuffer);
  15805. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15806. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15807. if (fullOptions.generateMipMaps) {
  15808. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15809. }
  15810. // Unbind
  15811. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15812. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15813. this.bindUnboundFramebuffer(currentFrameBuffer);
  15814. texture._framebuffer = framebuffer;
  15815. texture.baseWidth = width;
  15816. texture.baseHeight = height;
  15817. texture.width = width;
  15818. texture.height = height;
  15819. texture.isReady = true;
  15820. texture.samples = 1;
  15821. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15822. texture.samplingMode = fullOptions.samplingMode;
  15823. texture.type = fullOptions.type;
  15824. texture.format = fullOptions.format;
  15825. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15826. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15827. // this.resetTextureCache();
  15828. this._internalTexturesCache.push(texture);
  15829. return texture;
  15830. };
  15831. /**
  15832. * Create a multi render target texture
  15833. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15834. * @param size defines the size of the texture
  15835. * @param options defines the creation options
  15836. * @returns the cube texture as an InternalTexture
  15837. */
  15838. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15839. var generateMipMaps = false;
  15840. var generateDepthBuffer = true;
  15841. var generateStencilBuffer = false;
  15842. var generateDepthTexture = false;
  15843. var textureCount = 1;
  15844. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15845. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15846. var types = new Array();
  15847. var samplingModes = new Array();
  15848. if (options !== undefined) {
  15849. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15850. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15851. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15852. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15853. textureCount = options.textureCount || 1;
  15854. if (options.types) {
  15855. types = options.types;
  15856. }
  15857. if (options.samplingModes) {
  15858. samplingModes = options.samplingModes;
  15859. }
  15860. }
  15861. var gl = this._gl;
  15862. // Create the framebuffer
  15863. var framebuffer = gl.createFramebuffer();
  15864. this.bindUnboundFramebuffer(framebuffer);
  15865. var width = size.width || size;
  15866. var height = size.height || size;
  15867. var textures = [];
  15868. var attachments = [];
  15869. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15870. for (var i = 0; i < textureCount; i++) {
  15871. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15872. var type = types[i] || defaultType;
  15873. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15874. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15875. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15876. }
  15877. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15878. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15879. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15880. }
  15881. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15882. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15883. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15884. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15885. }
  15886. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15887. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15888. textures.push(texture);
  15889. attachments.push(attachment);
  15890. gl.activeTexture(gl["TEXTURE" + i]);
  15891. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15892. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15893. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15894. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15895. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15896. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15897. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15898. if (generateMipMaps) {
  15899. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15900. }
  15901. // Unbind
  15902. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15903. texture._framebuffer = framebuffer;
  15904. texture._depthStencilBuffer = depthStencilBuffer;
  15905. texture.baseWidth = width;
  15906. texture.baseHeight = height;
  15907. texture.width = width;
  15908. texture.height = height;
  15909. texture.isReady = true;
  15910. texture.samples = 1;
  15911. texture.generateMipMaps = generateMipMaps;
  15912. texture.samplingMode = samplingMode;
  15913. texture.type = type;
  15914. texture._generateDepthBuffer = generateDepthBuffer;
  15915. texture._generateStencilBuffer = generateStencilBuffer;
  15916. texture._attachments = attachments;
  15917. this._internalTexturesCache.push(texture);
  15918. }
  15919. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15920. // Depth texture
  15921. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15922. gl.activeTexture(gl.TEXTURE0);
  15923. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15924. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15925. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15926. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15927. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15928. 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);
  15929. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15930. depthTexture._framebuffer = framebuffer;
  15931. depthTexture.baseWidth = width;
  15932. depthTexture.baseHeight = height;
  15933. depthTexture.width = width;
  15934. depthTexture.height = height;
  15935. depthTexture.isReady = true;
  15936. depthTexture.samples = 1;
  15937. depthTexture.generateMipMaps = generateMipMaps;
  15938. depthTexture.samplingMode = gl.NEAREST;
  15939. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15940. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15941. textures.push(depthTexture);
  15942. this._internalTexturesCache.push(depthTexture);
  15943. }
  15944. gl.drawBuffers(attachments);
  15945. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15946. this.bindUnboundFramebuffer(null);
  15947. this.resetTextureCache();
  15948. return textures;
  15949. };
  15950. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15951. if (samples === void 0) { samples = 1; }
  15952. var depthStencilBuffer = null;
  15953. var gl = this._gl;
  15954. // Create the depth/stencil buffer
  15955. if (generateStencilBuffer) {
  15956. depthStencilBuffer = gl.createRenderbuffer();
  15957. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15958. if (samples > 1) {
  15959. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15960. }
  15961. else {
  15962. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15963. }
  15964. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15965. }
  15966. else if (generateDepthBuffer) {
  15967. depthStencilBuffer = gl.createRenderbuffer();
  15968. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15969. if (samples > 1) {
  15970. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15971. }
  15972. else {
  15973. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15974. }
  15975. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15976. }
  15977. return depthStencilBuffer;
  15978. };
  15979. /**
  15980. * Updates the sample count of a render target texture
  15981. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15982. * @param texture defines the texture to update
  15983. * @param samples defines the sample count to set
  15984. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15985. */
  15986. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15987. if (this.webGLVersion < 2 || !texture) {
  15988. return 1;
  15989. }
  15990. if (texture.samples === samples) {
  15991. return samples;
  15992. }
  15993. var gl = this._gl;
  15994. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15995. // Dispose previous render buffers
  15996. if (texture._depthStencilBuffer) {
  15997. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15998. texture._depthStencilBuffer = null;
  15999. }
  16000. if (texture._MSAAFramebuffer) {
  16001. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16002. texture._MSAAFramebuffer = null;
  16003. }
  16004. if (texture._MSAARenderBuffer) {
  16005. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16006. texture._MSAARenderBuffer = null;
  16007. }
  16008. if (samples > 1) {
  16009. var framebuffer = gl.createFramebuffer();
  16010. if (!framebuffer) {
  16011. throw new Error("Unable to create multi sampled framebuffer");
  16012. }
  16013. texture._MSAAFramebuffer = framebuffer;
  16014. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  16015. var colorRenderbuffer = gl.createRenderbuffer();
  16016. if (!colorRenderbuffer) {
  16017. throw new Error("Unable to create multi sampled framebuffer");
  16018. }
  16019. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16020. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16021. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  16022. texture._MSAARenderBuffer = colorRenderbuffer;
  16023. }
  16024. else {
  16025. this.bindUnboundFramebuffer(texture._framebuffer);
  16026. }
  16027. texture.samples = samples;
  16028. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  16029. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16030. this.bindUnboundFramebuffer(null);
  16031. return samples;
  16032. };
  16033. /**
  16034. * Update the sample count for a given multiple render target texture
  16035. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16036. * @param textures defines the textures to update
  16037. * @param samples defines the sample count to set
  16038. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16039. */
  16040. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  16041. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  16042. return 1;
  16043. }
  16044. if (textures[0].samples === samples) {
  16045. return samples;
  16046. }
  16047. var gl = this._gl;
  16048. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16049. // Dispose previous render buffers
  16050. if (textures[0]._depthStencilBuffer) {
  16051. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  16052. textures[0]._depthStencilBuffer = null;
  16053. }
  16054. if (textures[0]._MSAAFramebuffer) {
  16055. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  16056. textures[0]._MSAAFramebuffer = null;
  16057. }
  16058. for (var i = 0; i < textures.length; i++) {
  16059. if (textures[i]._MSAARenderBuffer) {
  16060. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  16061. textures[i]._MSAARenderBuffer = null;
  16062. }
  16063. }
  16064. if (samples > 1) {
  16065. var framebuffer = gl.createFramebuffer();
  16066. if (!framebuffer) {
  16067. throw new Error("Unable to create multi sampled framebuffer");
  16068. }
  16069. this.bindUnboundFramebuffer(framebuffer);
  16070. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  16071. var attachments = [];
  16072. for (var i = 0; i < textures.length; i++) {
  16073. var texture = textures[i];
  16074. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16075. var colorRenderbuffer = gl.createRenderbuffer();
  16076. if (!colorRenderbuffer) {
  16077. throw new Error("Unable to create multi sampled framebuffer");
  16078. }
  16079. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16080. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16081. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  16082. texture._MSAAFramebuffer = framebuffer;
  16083. texture._MSAARenderBuffer = colorRenderbuffer;
  16084. texture.samples = samples;
  16085. texture._depthStencilBuffer = depthStencilBuffer;
  16086. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16087. attachments.push(attachment);
  16088. }
  16089. gl.drawBuffers(attachments);
  16090. }
  16091. else {
  16092. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  16093. }
  16094. this.bindUnboundFramebuffer(null);
  16095. return samples;
  16096. };
  16097. /** @hidden */
  16098. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  16099. if (faceIndex === void 0) { faceIndex = 0; }
  16100. if (lod === void 0) { lod = 0; }
  16101. var gl = this._gl;
  16102. var target = gl.TEXTURE_2D;
  16103. if (texture.isCube) {
  16104. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16105. }
  16106. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  16107. };
  16108. /** @hidden */
  16109. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  16110. if (faceIndex === void 0) { faceIndex = 0; }
  16111. if (lod === void 0) { lod = 0; }
  16112. var gl = this._gl;
  16113. var textureType = this._getWebGLTextureType(texture.type);
  16114. var format = this._getInternalFormat(texture.format);
  16115. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16116. this._unpackFlipY(texture.invertY);
  16117. var target = gl.TEXTURE_2D;
  16118. if (texture.isCube) {
  16119. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16120. }
  16121. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  16122. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  16123. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  16124. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  16125. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  16126. };
  16127. /** @hidden */
  16128. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  16129. if (faceIndex === void 0) { faceIndex = 0; }
  16130. if (lod === void 0) { lod = 0; }
  16131. var gl = this._gl;
  16132. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16133. this._bindTextureDirectly(bindTarget, texture, true);
  16134. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  16135. this._bindTextureDirectly(bindTarget, null, true);
  16136. };
  16137. /** @hidden */
  16138. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  16139. if (faceIndex === void 0) { faceIndex = 0; }
  16140. if (lod === void 0) { lod = 0; }
  16141. var gl = this._gl;
  16142. var textureType = this._getWebGLTextureType(texture.type);
  16143. var format = this._getInternalFormat(texture.format);
  16144. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16145. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16146. this._bindTextureDirectly(bindTarget, texture, true);
  16147. this._unpackFlipY(texture.invertY);
  16148. var target = gl.TEXTURE_2D;
  16149. if (texture.isCube) {
  16150. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16151. }
  16152. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  16153. this._bindTextureDirectly(bindTarget, null, true);
  16154. };
  16155. /**
  16156. * Creates a new render target cube texture
  16157. * @param size defines the size of the texture
  16158. * @param options defines the options used to create the texture
  16159. * @returns a new render target cube texture stored in an InternalTexture
  16160. */
  16161. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  16162. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  16163. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  16164. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16165. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16166. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16167. }
  16168. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16169. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16170. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16171. }
  16172. var gl = this._gl;
  16173. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16174. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16175. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  16176. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16177. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16178. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  16179. }
  16180. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16181. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16182. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16183. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16184. for (var face = 0; face < 6; face++) {
  16185. 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);
  16186. }
  16187. // Create the framebuffer
  16188. var framebuffer = gl.createFramebuffer();
  16189. this.bindUnboundFramebuffer(framebuffer);
  16190. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  16191. // MipMaps
  16192. if (fullOptions.generateMipMaps) {
  16193. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16194. }
  16195. // Unbind
  16196. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16197. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16198. this.bindUnboundFramebuffer(null);
  16199. texture._framebuffer = framebuffer;
  16200. texture.width = size;
  16201. texture.height = size;
  16202. texture.isReady = true;
  16203. texture.isCube = true;
  16204. texture.samples = 1;
  16205. texture.generateMipMaps = fullOptions.generateMipMaps;
  16206. texture.samplingMode = fullOptions.samplingMode;
  16207. texture.type = fullOptions.type;
  16208. texture.format = fullOptions.format;
  16209. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16210. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  16211. this._internalTexturesCache.push(texture);
  16212. return texture;
  16213. };
  16214. /**
  16215. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  16216. * @param rootUrl defines the url where the file to load is located
  16217. * @param scene defines the current scene
  16218. * @param lodScale defines scale to apply to the mip map selection
  16219. * @param lodOffset defines offset to apply to the mip map selection
  16220. * @param onLoad defines an optional callback raised when the texture is loaded
  16221. * @param onError defines an optional callback raised if there is an issue to load the texture
  16222. * @param format defines the format of the data
  16223. * @param forcedExtension defines the extension to use to pick the right loader
  16224. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  16225. * @returns the cube texture as an InternalTexture
  16226. */
  16227. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  16228. var _this = this;
  16229. if (onLoad === void 0) { onLoad = null; }
  16230. if (onError === void 0) { onError = null; }
  16231. if (forcedExtension === void 0) { forcedExtension = null; }
  16232. if (createPolynomials === void 0) { createPolynomials = true; }
  16233. var callback = function (loadData) {
  16234. if (!loadData) {
  16235. if (onLoad) {
  16236. onLoad(null);
  16237. }
  16238. return;
  16239. }
  16240. var texture = loadData.texture;
  16241. if (!createPolynomials) {
  16242. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  16243. }
  16244. else if (loadData.info.sphericalPolynomial) {
  16245. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  16246. }
  16247. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  16248. if (_this._caps.textureLOD) {
  16249. // Do not add extra process if texture lod is supported.
  16250. if (onLoad) {
  16251. onLoad(texture);
  16252. }
  16253. return;
  16254. }
  16255. var mipSlices = 3;
  16256. var gl = _this._gl;
  16257. var width = loadData.width;
  16258. if (!width) {
  16259. return;
  16260. }
  16261. var textures = [];
  16262. for (var i = 0; i < mipSlices; i++) {
  16263. //compute LOD from even spacing in smoothness (matching shader calculation)
  16264. var smoothness = i / (mipSlices - 1);
  16265. var roughness = 1 - smoothness;
  16266. var minLODIndex = lodOffset; // roughness = 0
  16267. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  16268. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  16269. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  16270. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  16271. glTextureFromLod.type = texture.type;
  16272. glTextureFromLod.format = texture.format;
  16273. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  16274. glTextureFromLod.height = glTextureFromLod.width;
  16275. glTextureFromLod.isCube = true;
  16276. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  16277. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16278. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  16279. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16280. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16281. if (loadData.isDDS) {
  16282. var info = loadData.info;
  16283. var data = loadData.data;
  16284. _this._unpackFlipY(info.isCompressed);
  16285. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  16286. }
  16287. else {
  16288. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  16289. }
  16290. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16291. // Wrap in a base texture for easy binding.
  16292. var lodTexture = new BABYLON.BaseTexture(scene);
  16293. lodTexture.isCube = true;
  16294. lodTexture._texture = glTextureFromLod;
  16295. glTextureFromLod.isReady = true;
  16296. textures.push(lodTexture);
  16297. }
  16298. texture._lodTextureHigh = textures[2];
  16299. texture._lodTextureMid = textures[1];
  16300. texture._lodTextureLow = textures[0];
  16301. if (onLoad) {
  16302. onLoad(texture);
  16303. }
  16304. };
  16305. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  16306. };
  16307. /**
  16308. * Creates a cube texture
  16309. * @param rootUrl defines the url where the files to load is located
  16310. * @param scene defines the current scene
  16311. * @param files defines the list of files to load (1 per face)
  16312. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  16313. * @param onLoad defines an optional callback raised when the texture is loaded
  16314. * @param onError defines an optional callback raised if there is an issue to load the texture
  16315. * @param format defines the format of the data
  16316. * @param forcedExtension defines the extension to use to pick the right loader
  16317. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  16318. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  16319. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  16320. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  16321. * @returns the cube texture as an InternalTexture
  16322. */
  16323. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  16324. var _this = this;
  16325. if (onLoad === void 0) { onLoad = null; }
  16326. if (onError === void 0) { onError = null; }
  16327. if (forcedExtension === void 0) { forcedExtension = null; }
  16328. if (createPolynomials === void 0) { createPolynomials = false; }
  16329. if (lodScale === void 0) { lodScale = 0; }
  16330. if (lodOffset === void 0) { lodOffset = 0; }
  16331. if (fallback === void 0) { fallback = null; }
  16332. var gl = this._gl;
  16333. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  16334. texture.isCube = true;
  16335. texture.url = rootUrl;
  16336. texture.generateMipMaps = !noMipmap;
  16337. texture._lodGenerationScale = lodScale;
  16338. texture._lodGenerationOffset = lodOffset;
  16339. if (!this._doNotHandleContextLost) {
  16340. texture._extension = forcedExtension;
  16341. texture._files = files;
  16342. }
  16343. var lastDot = rootUrl.lastIndexOf('.');
  16344. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  16345. var loader = null;
  16346. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  16347. var availableLoader = _a[_i];
  16348. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  16349. loader = availableLoader;
  16350. break;
  16351. }
  16352. }
  16353. var onInternalError = function (request, exception) {
  16354. if (loader) {
  16355. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  16356. if (fallbackUrl) {
  16357. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  16358. }
  16359. }
  16360. if (onError && request) {
  16361. onError(request.status + " " + request.statusText, exception);
  16362. }
  16363. };
  16364. if (loader) {
  16365. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  16366. var onloaddata = function (data) {
  16367. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16368. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  16369. };
  16370. if (files && files.length === 6) {
  16371. if (loader.supportCascades) {
  16372. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  16373. }
  16374. else if (onError) {
  16375. onError("Textures type does not support cascades.");
  16376. }
  16377. }
  16378. else {
  16379. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  16380. }
  16381. }
  16382. else {
  16383. if (!files) {
  16384. throw new Error("Cannot load cubemap because files were not defined");
  16385. }
  16386. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16387. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16388. var height = width;
  16389. _this._prepareWorkingCanvas();
  16390. if (!_this._workingCanvas || !_this._workingContext) {
  16391. return;
  16392. }
  16393. _this._workingCanvas.width = width;
  16394. _this._workingCanvas.height = height;
  16395. var faces = [
  16396. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16397. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16398. ];
  16399. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16400. _this._unpackFlipY(false);
  16401. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16402. for (var index = 0; index < faces.length; index++) {
  16403. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16404. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16405. }
  16406. if (!noMipmap) {
  16407. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16408. }
  16409. _this._setCubeMapTextureParams(!noMipmap);
  16410. texture.width = width;
  16411. texture.height = height;
  16412. texture.isReady = true;
  16413. if (format) {
  16414. texture.format = format;
  16415. }
  16416. texture.onLoadedObservable.notifyObservers(texture);
  16417. texture.onLoadedObservable.clear();
  16418. if (onLoad) {
  16419. onLoad();
  16420. }
  16421. }, files, onError);
  16422. }
  16423. this._internalTexturesCache.push(texture);
  16424. return texture;
  16425. };
  16426. /**
  16427. * @hidden
  16428. */
  16429. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  16430. var gl = this._gl;
  16431. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16432. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16433. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16434. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16435. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16436. // this.resetTextureCache();
  16437. };
  16438. /**
  16439. * Update a raw cube texture
  16440. * @param texture defines the texture to udpdate
  16441. * @param data defines the data to store
  16442. * @param format defines the data format
  16443. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16444. * @param invertY defines if data must be stored with Y axis inverted
  16445. * @param compression defines the compression used (null by default)
  16446. * @param level defines which level of the texture to update
  16447. */
  16448. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16449. if (compression === void 0) { compression = null; }
  16450. if (level === void 0) { level = 0; }
  16451. texture._bufferViewArray = data;
  16452. texture.format = format;
  16453. texture.type = type;
  16454. texture.invertY = invertY;
  16455. texture._compression = compression;
  16456. var gl = this._gl;
  16457. var textureType = this._getWebGLTextureType(type);
  16458. var internalFormat = this._getInternalFormat(format);
  16459. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16460. var needConversion = false;
  16461. if (internalFormat === gl.RGB) {
  16462. internalFormat = gl.RGBA;
  16463. needConversion = true;
  16464. }
  16465. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16466. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16467. if (texture.width % 4 !== 0) {
  16468. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16469. }
  16470. // Data are known to be in +X +Y +Z -X -Y -Z
  16471. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16472. var faceData = data[faceIndex];
  16473. if (compression) {
  16474. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16475. }
  16476. else {
  16477. if (needConversion) {
  16478. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16479. }
  16480. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16481. }
  16482. }
  16483. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16484. if (isPot && texture.generateMipMaps && level === 0) {
  16485. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16486. }
  16487. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16488. // this.resetTextureCache();
  16489. texture.isReady = true;
  16490. };
  16491. /**
  16492. * Creates a new raw cube texture
  16493. * @param data defines the array of data to use to create each face
  16494. * @param size defines the size of the textures
  16495. * @param format defines the format of the data
  16496. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16497. * @param generateMipMaps defines if the engine should generate the mip levels
  16498. * @param invertY defines if data must be stored with Y axis inverted
  16499. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16500. * @param compression defines the compression used (null by default)
  16501. * @returns the cube texture as an InternalTexture
  16502. */
  16503. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16504. if (compression === void 0) { compression = null; }
  16505. var gl = this._gl;
  16506. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16507. texture.isCube = true;
  16508. texture.format = format;
  16509. texture.type = type;
  16510. if (!this._doNotHandleContextLost) {
  16511. texture._bufferViewArray = data;
  16512. }
  16513. var textureType = this._getWebGLTextureType(type);
  16514. var internalFormat = this._getInternalFormat(format);
  16515. if (internalFormat === gl.RGB) {
  16516. internalFormat = gl.RGBA;
  16517. }
  16518. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16519. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16520. generateMipMaps = false;
  16521. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16522. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16523. }
  16524. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16525. generateMipMaps = false;
  16526. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16527. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16528. }
  16529. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16530. generateMipMaps = false;
  16531. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16532. }
  16533. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16534. generateMipMaps = false;
  16535. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16536. }
  16537. var width = size;
  16538. var height = width;
  16539. texture.width = width;
  16540. texture.height = height;
  16541. // Double check on POT to generate Mips.
  16542. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16543. if (!isPot) {
  16544. generateMipMaps = false;
  16545. }
  16546. // Upload data if needed. The texture won't be ready until then.
  16547. if (data) {
  16548. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16549. }
  16550. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16551. // Filters
  16552. if (data && generateMipMaps) {
  16553. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16554. }
  16555. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16556. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16557. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16558. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16559. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16560. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16561. texture.generateMipMaps = generateMipMaps;
  16562. return texture;
  16563. };
  16564. /**
  16565. * Creates a new raw cube texture from a specified url
  16566. * @param url defines the url where the data is located
  16567. * @param scene defines the current scene
  16568. * @param size defines the size of the textures
  16569. * @param format defines the format of the data
  16570. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16571. * @param noMipmap defines if the engine should avoid generating the mip levels
  16572. * @param callback defines a callback used to extract texture data from loaded data
  16573. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16574. * @param onLoad defines a callback called when texture is loaded
  16575. * @param onError defines a callback called if there is an error
  16576. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16577. * @param invertY defines if data must be stored with Y axis inverted
  16578. * @returns the cube texture as an InternalTexture
  16579. */
  16580. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16581. var _this = this;
  16582. if (onLoad === void 0) { onLoad = null; }
  16583. if (onError === void 0) { onError = null; }
  16584. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16585. if (invertY === void 0) { invertY = false; }
  16586. var gl = this._gl;
  16587. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16588. scene._addPendingData(texture);
  16589. texture.url = url;
  16590. this._internalTexturesCache.push(texture);
  16591. var onerror = function (request, exception) {
  16592. scene._removePendingData(texture);
  16593. if (onError && request) {
  16594. onError(request.status + " " + request.statusText, exception);
  16595. }
  16596. };
  16597. var internalCallback = function (data) {
  16598. var width = texture.width;
  16599. var faceDataArrays = callback(data);
  16600. if (!faceDataArrays) {
  16601. return;
  16602. }
  16603. if (mipmapGenerator) {
  16604. var textureType = _this._getWebGLTextureType(type);
  16605. var internalFormat = _this._getInternalFormat(format);
  16606. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16607. var needConversion = false;
  16608. if (internalFormat === gl.RGB) {
  16609. internalFormat = gl.RGBA;
  16610. needConversion = true;
  16611. }
  16612. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16613. _this._unpackFlipY(false);
  16614. var mipData = mipmapGenerator(faceDataArrays);
  16615. for (var level = 0; level < mipData.length; level++) {
  16616. var mipSize = width >> level;
  16617. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16618. var mipFaceData = mipData[level][faceIndex];
  16619. if (needConversion) {
  16620. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16621. }
  16622. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16623. }
  16624. }
  16625. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16626. }
  16627. else {
  16628. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16629. }
  16630. texture.isReady = true;
  16631. // this.resetTextureCache();
  16632. scene._removePendingData(texture);
  16633. if (onLoad) {
  16634. onLoad();
  16635. }
  16636. };
  16637. this._loadFile(url, function (data) {
  16638. internalCallback(data);
  16639. }, undefined, scene.database, true, onerror);
  16640. return texture;
  16641. };
  16642. ;
  16643. /**
  16644. * Update a raw 3D texture
  16645. * @param texture defines the texture to update
  16646. * @param data defines the data to store
  16647. * @param format defines the data format
  16648. * @param invertY defines if data must be stored with Y axis inverted
  16649. * @param compression defines the used compression (can be null)
  16650. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16651. */
  16652. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16653. if (compression === void 0) { compression = null; }
  16654. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16655. var internalType = this._getWebGLTextureType(textureType);
  16656. var internalFormat = this._getInternalFormat(format);
  16657. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16658. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16659. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16660. if (!this._doNotHandleContextLost) {
  16661. texture._bufferView = data;
  16662. texture.format = format;
  16663. texture.invertY = invertY;
  16664. texture._compression = compression;
  16665. }
  16666. if (texture.width % 4 !== 0) {
  16667. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16668. }
  16669. if (compression && data) {
  16670. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16671. }
  16672. else {
  16673. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16674. }
  16675. if (texture.generateMipMaps) {
  16676. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16677. }
  16678. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16679. // this.resetTextureCache();
  16680. texture.isReady = true;
  16681. };
  16682. /**
  16683. * Creates a new raw 3D texture
  16684. * @param data defines the data used to create the texture
  16685. * @param width defines the width of the texture
  16686. * @param height defines the height of the texture
  16687. * @param depth defines the depth of the texture
  16688. * @param format defines the format of the texture
  16689. * @param generateMipMaps defines if the engine must generate mip levels
  16690. * @param invertY defines if data must be stored with Y axis inverted
  16691. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16692. * @param compression defines the compressed used (can be null)
  16693. * @param textureType defines the compressed used (can be null)
  16694. * @returns a new raw 3D texture (stored in an InternalTexture)
  16695. */
  16696. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16697. if (compression === void 0) { compression = null; }
  16698. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16699. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16700. texture.baseWidth = width;
  16701. texture.baseHeight = height;
  16702. texture.baseDepth = depth;
  16703. texture.width = width;
  16704. texture.height = height;
  16705. texture.depth = depth;
  16706. texture.format = format;
  16707. texture.type = textureType;
  16708. texture.generateMipMaps = generateMipMaps;
  16709. texture.samplingMode = samplingMode;
  16710. texture.is3D = true;
  16711. if (!this._doNotHandleContextLost) {
  16712. texture._bufferView = data;
  16713. }
  16714. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16715. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16716. // Filters
  16717. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16718. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16719. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16720. if (generateMipMaps) {
  16721. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16722. }
  16723. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16724. this._internalTexturesCache.push(texture);
  16725. return texture;
  16726. };
  16727. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16728. var gl = this._gl;
  16729. if (!gl) {
  16730. return;
  16731. }
  16732. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16733. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16734. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16735. if (!noMipmap && !isCompressed) {
  16736. gl.generateMipmap(gl.TEXTURE_2D);
  16737. }
  16738. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16739. // this.resetTextureCache();
  16740. if (scene) {
  16741. scene._removePendingData(texture);
  16742. }
  16743. texture.onLoadedObservable.notifyObservers(texture);
  16744. texture.onLoadedObservable.clear();
  16745. };
  16746. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16747. var _this = this;
  16748. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16749. var maxTextureSize = this.getCaps().maxTextureSize;
  16750. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16751. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16752. var gl = this._gl;
  16753. if (!gl) {
  16754. return;
  16755. }
  16756. if (!texture._webGLTexture) {
  16757. // this.resetTextureCache();
  16758. if (scene) {
  16759. scene._removePendingData(texture);
  16760. }
  16761. return;
  16762. }
  16763. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16764. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16765. texture.baseWidth = width;
  16766. texture.baseHeight = height;
  16767. texture.width = potWidth;
  16768. texture.height = potHeight;
  16769. texture.isReady = true;
  16770. if (processFunction(potWidth, potHeight, function () {
  16771. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16772. })) {
  16773. // Returning as texture needs extra async steps
  16774. return;
  16775. }
  16776. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16777. };
  16778. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16779. // Create new RGBA data container.
  16780. var rgbaData;
  16781. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16782. rgbaData = new Float32Array(width * height * 4);
  16783. }
  16784. else {
  16785. rgbaData = new Uint32Array(width * height * 4);
  16786. }
  16787. // Convert each pixel.
  16788. for (var x = 0; x < width; x++) {
  16789. for (var y = 0; y < height; y++) {
  16790. var index = (y * width + x) * 3;
  16791. var newIndex = (y * width + x) * 4;
  16792. // Map Old Value to new value.
  16793. rgbaData[newIndex + 0] = rgbData[index + 0];
  16794. rgbaData[newIndex + 1] = rgbData[index + 1];
  16795. rgbaData[newIndex + 2] = rgbData[index + 2];
  16796. // Add fully opaque alpha channel.
  16797. rgbaData[newIndex + 3] = 1;
  16798. }
  16799. }
  16800. return rgbaData;
  16801. };
  16802. /** @hidden */
  16803. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16804. var gl = this._gl;
  16805. if (texture._framebuffer) {
  16806. gl.deleteFramebuffer(texture._framebuffer);
  16807. texture._framebuffer = null;
  16808. }
  16809. if (texture._depthStencilBuffer) {
  16810. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16811. texture._depthStencilBuffer = null;
  16812. }
  16813. if (texture._MSAAFramebuffer) {
  16814. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16815. texture._MSAAFramebuffer = null;
  16816. }
  16817. if (texture._MSAARenderBuffer) {
  16818. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16819. texture._MSAARenderBuffer = null;
  16820. }
  16821. };
  16822. /** @hidden */
  16823. Engine.prototype._releaseTexture = function (texture) {
  16824. var gl = this._gl;
  16825. this._releaseFramebufferObjects(texture);
  16826. gl.deleteTexture(texture._webGLTexture);
  16827. // Unbind channels
  16828. this.unbindAllTextures();
  16829. var index = this._internalTexturesCache.indexOf(texture);
  16830. if (index !== -1) {
  16831. this._internalTexturesCache.splice(index, 1);
  16832. }
  16833. // Integrated fixed lod samplers.
  16834. if (texture._lodTextureHigh) {
  16835. texture._lodTextureHigh.dispose();
  16836. }
  16837. if (texture._lodTextureMid) {
  16838. texture._lodTextureMid.dispose();
  16839. }
  16840. if (texture._lodTextureLow) {
  16841. texture._lodTextureLow.dispose();
  16842. }
  16843. // Set output texture of post process to null if the texture has been released/disposed
  16844. this.scenes.forEach(function (scene) {
  16845. scene.postProcesses.forEach(function (postProcess) {
  16846. if (postProcess._outputTexture == texture) {
  16847. postProcess._outputTexture = null;
  16848. }
  16849. });
  16850. scene.cameras.forEach(function (camera) {
  16851. camera._postProcesses.forEach(function (postProcess) {
  16852. if (postProcess) {
  16853. if (postProcess._outputTexture == texture) {
  16854. postProcess._outputTexture = null;
  16855. }
  16856. }
  16857. });
  16858. });
  16859. });
  16860. };
  16861. Engine.prototype.setProgram = function (program) {
  16862. if (this._currentProgram !== program) {
  16863. this._gl.useProgram(program);
  16864. this._currentProgram = program;
  16865. }
  16866. };
  16867. /**
  16868. * Binds an effect to the webGL context
  16869. * @param effect defines the effect to bind
  16870. */
  16871. Engine.prototype.bindSamplers = function (effect) {
  16872. this.setProgram(effect.getProgram());
  16873. var samplers = effect.getSamplers();
  16874. for (var index = 0; index < samplers.length; index++) {
  16875. var uniform = effect.getUniform(samplers[index]);
  16876. if (uniform) {
  16877. this._boundUniforms[index] = uniform;
  16878. }
  16879. }
  16880. this._currentEffect = null;
  16881. };
  16882. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16883. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16884. return;
  16885. }
  16886. // Remove
  16887. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16888. // Bind last to it
  16889. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16890. // Bind to dummy
  16891. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16892. };
  16893. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16894. if (!internalTexture) {
  16895. return -1;
  16896. }
  16897. internalTexture._initialSlot = channel;
  16898. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16899. if (channel !== internalTexture._designatedSlot) {
  16900. this._textureCollisions.addCount(1, false);
  16901. }
  16902. }
  16903. else {
  16904. if (channel !== internalTexture._designatedSlot) {
  16905. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16906. return internalTexture._designatedSlot;
  16907. }
  16908. else {
  16909. // No slot for this texture, let's pick a new one (if we find a free slot)
  16910. if (this._nextFreeTextureSlots.length) {
  16911. return this._nextFreeTextureSlots[0];
  16912. }
  16913. // We need to recycle the oldest bound texture, sorry.
  16914. this._textureCollisions.addCount(1, false);
  16915. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16916. }
  16917. }
  16918. }
  16919. return channel;
  16920. };
  16921. Engine.prototype._linkTrackers = function (previous, next) {
  16922. previous.next = next;
  16923. next.previous = previous;
  16924. };
  16925. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16926. var currentSlot = internalTexture._designatedSlot;
  16927. if (currentSlot === -1) {
  16928. return -1;
  16929. }
  16930. internalTexture._designatedSlot = -1;
  16931. if (this.disableTextureBindingOptimization) {
  16932. return -1;
  16933. }
  16934. // Remove from bound list
  16935. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16936. // Free the slot
  16937. this._boundTexturesCache[currentSlot] = null;
  16938. this._nextFreeTextureSlots.push(currentSlot);
  16939. return currentSlot;
  16940. };
  16941. Engine.prototype._activateCurrentTexture = function () {
  16942. if (this._currentTextureChannel !== this._activeChannel) {
  16943. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16944. this._currentTextureChannel = this._activeChannel;
  16945. }
  16946. };
  16947. /** @hidden */
  16948. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16949. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16950. if (force === void 0) { force = false; }
  16951. var wasPreviouslyBound = false;
  16952. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16953. this._activeChannel = texture._designatedSlot;
  16954. }
  16955. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16956. var isTextureForRendering = texture && texture._initialSlot > -1;
  16957. if (currentTextureBound !== texture || force) {
  16958. if (currentTextureBound) {
  16959. this._removeDesignatedSlot(currentTextureBound);
  16960. }
  16961. this._activateCurrentTexture();
  16962. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16963. this._boundTexturesCache[this._activeChannel] = texture;
  16964. if (texture) {
  16965. if (!this.disableTextureBindingOptimization) {
  16966. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16967. if (slotIndex > -1) {
  16968. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16969. }
  16970. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16971. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16972. }
  16973. texture._designatedSlot = this._activeChannel;
  16974. }
  16975. }
  16976. else if (forTextureDataUpdate) {
  16977. wasPreviouslyBound = true;
  16978. this._activateCurrentTexture();
  16979. }
  16980. if (isTextureForRendering && !forTextureDataUpdate) {
  16981. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16982. }
  16983. return wasPreviouslyBound;
  16984. };
  16985. /** @hidden */
  16986. Engine.prototype._bindTexture = function (channel, texture) {
  16987. if (channel < 0) {
  16988. return;
  16989. }
  16990. if (texture) {
  16991. channel = this._getCorrectTextureChannel(channel, texture);
  16992. }
  16993. this._activeChannel = channel;
  16994. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16995. };
  16996. /**
  16997. * Sets a texture to the webGL context from a postprocess
  16998. * @param channel defines the channel to use
  16999. * @param postProcess defines the source postprocess
  17000. */
  17001. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17002. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  17003. };
  17004. /**
  17005. * Binds the output of the passed in post process to the texture channel specified
  17006. * @param channel The channel the texture should be bound to
  17007. * @param postProcess The post process which's output should be bound
  17008. */
  17009. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  17010. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  17011. };
  17012. /**
  17013. * Unbind all textures from the webGL context
  17014. */
  17015. Engine.prototype.unbindAllTextures = function () {
  17016. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  17017. this._activeChannel = channel;
  17018. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17019. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17020. if (this.webGLVersion > 1) {
  17021. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17022. }
  17023. }
  17024. };
  17025. /**
  17026. * Sets a texture to the according uniform.
  17027. * @param channel The texture channel
  17028. * @param uniform The uniform to set
  17029. * @param texture The texture to apply
  17030. */
  17031. Engine.prototype.setTexture = function (channel, uniform, texture) {
  17032. if (channel < 0) {
  17033. return;
  17034. }
  17035. if (uniform) {
  17036. this._boundUniforms[channel] = uniform;
  17037. }
  17038. this._setTexture(channel, texture);
  17039. };
  17040. /**
  17041. * Sets a depth stencil texture from a render target to the according uniform.
  17042. * @param channel The texture channel
  17043. * @param uniform The uniform to set
  17044. * @param texture The render target texture containing the depth stencil texture to apply
  17045. */
  17046. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  17047. if (channel < 0) {
  17048. return;
  17049. }
  17050. if (uniform) {
  17051. this._boundUniforms[channel] = uniform;
  17052. }
  17053. if (!texture || !texture.depthStencilTexture) {
  17054. this._setTexture(channel, null);
  17055. }
  17056. else {
  17057. this._setTexture(channel, texture, false, true);
  17058. }
  17059. };
  17060. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  17061. var uniform = this._boundUniforms[sourceSlot];
  17062. if (uniform._currentState === destination) {
  17063. return;
  17064. }
  17065. this._gl.uniform1i(uniform, destination);
  17066. uniform._currentState = destination;
  17067. };
  17068. Engine.prototype._getTextureWrapMode = function (mode) {
  17069. switch (mode) {
  17070. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  17071. return this._gl.REPEAT;
  17072. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  17073. return this._gl.CLAMP_TO_EDGE;
  17074. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  17075. return this._gl.MIRRORED_REPEAT;
  17076. }
  17077. return this._gl.REPEAT;
  17078. };
  17079. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  17080. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  17081. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  17082. // Not ready?
  17083. if (!texture) {
  17084. if (this._boundTexturesCache[channel] != null) {
  17085. this._activeChannel = channel;
  17086. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17087. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17088. if (this.webGLVersion > 1) {
  17089. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17090. }
  17091. }
  17092. return false;
  17093. }
  17094. // Video
  17095. if (texture.video) {
  17096. this._activeChannel = channel;
  17097. texture.update();
  17098. }
  17099. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  17100. texture.delayLoad();
  17101. return false;
  17102. }
  17103. var internalTexture;
  17104. if (depthStencilTexture) {
  17105. internalTexture = texture.depthStencilTexture;
  17106. }
  17107. else if (texture.isReady()) {
  17108. internalTexture = texture.getInternalTexture();
  17109. }
  17110. else if (texture.isCube) {
  17111. internalTexture = this.emptyCubeTexture;
  17112. }
  17113. else if (texture.is3D) {
  17114. internalTexture = this.emptyTexture3D;
  17115. }
  17116. else {
  17117. internalTexture = this.emptyTexture;
  17118. }
  17119. if (!isPartOfTextureArray) {
  17120. channel = this._getCorrectTextureChannel(channel, internalTexture);
  17121. }
  17122. var needToBind = true;
  17123. if (this._boundTexturesCache[channel] === internalTexture) {
  17124. this._moveBoundTextureOnTop(internalTexture);
  17125. if (!isPartOfTextureArray) {
  17126. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  17127. }
  17128. needToBind = false;
  17129. }
  17130. this._activeChannel = channel;
  17131. if (internalTexture && internalTexture.is3D) {
  17132. if (needToBind) {
  17133. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  17134. }
  17135. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17136. internalTexture._cachedWrapU = texture.wrapU;
  17137. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17138. }
  17139. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17140. internalTexture._cachedWrapV = texture.wrapV;
  17141. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17142. }
  17143. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  17144. internalTexture._cachedWrapR = texture.wrapR;
  17145. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  17146. }
  17147. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  17148. }
  17149. else if (internalTexture && internalTexture.isCube) {
  17150. if (needToBind) {
  17151. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  17152. }
  17153. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  17154. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  17155. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  17156. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  17157. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  17158. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  17159. }
  17160. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  17161. }
  17162. else {
  17163. if (needToBind) {
  17164. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  17165. }
  17166. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17167. internalTexture._cachedWrapU = texture.wrapU;
  17168. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17169. }
  17170. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17171. internalTexture._cachedWrapV = texture.wrapV;
  17172. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17173. }
  17174. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  17175. }
  17176. return true;
  17177. };
  17178. /**
  17179. * Sets an array of texture to the webGL context
  17180. * @param channel defines the channel where the texture array must be set
  17181. * @param uniform defines the associated uniform location
  17182. * @param textures defines the array of textures to bind
  17183. */
  17184. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  17185. if (channel < 0 || !uniform) {
  17186. return;
  17187. }
  17188. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  17189. this._textureUnits = new Int32Array(textures.length);
  17190. }
  17191. for (var i = 0; i < textures.length; i++) {
  17192. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  17193. }
  17194. this._gl.uniform1iv(uniform, this._textureUnits);
  17195. for (var index = 0; index < textures.length; index++) {
  17196. this._setTexture(this._textureUnits[index], textures[index], true);
  17197. }
  17198. };
  17199. /** @hidden */
  17200. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  17201. var internalTexture = texture.getInternalTexture();
  17202. if (!internalTexture) {
  17203. return;
  17204. }
  17205. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  17206. var value = texture.anisotropicFilteringLevel;
  17207. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  17208. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  17209. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  17210. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  17211. }
  17212. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  17213. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  17214. internalTexture._cachedAnisotropicFilteringLevel = value;
  17215. }
  17216. };
  17217. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  17218. this._bindTextureDirectly(target, texture, true, true);
  17219. this._gl.texParameterf(target, parameter, value);
  17220. };
  17221. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  17222. if (texture) {
  17223. this._bindTextureDirectly(target, texture, true, true);
  17224. }
  17225. this._gl.texParameteri(target, parameter, value);
  17226. };
  17227. /**
  17228. * Reads pixels from the current frame buffer. Please note that this function can be slow
  17229. * @param x defines the x coordinate of the rectangle where pixels must be read
  17230. * @param y defines the y coordinate of the rectangle where pixels must be read
  17231. * @param width defines the width of the rectangle where pixels must be read
  17232. * @param height defines the height of the rectangle where pixels must be read
  17233. * @returns a Uint8Array containing RGBA colors
  17234. */
  17235. Engine.prototype.readPixels = function (x, y, width, height) {
  17236. var data = new Uint8Array(height * width * 4);
  17237. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  17238. return data;
  17239. };
  17240. /**
  17241. * Add an externaly attached data from its key.
  17242. * This method call will fail and return false, if such key already exists.
  17243. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17244. * @param key the unique key that identifies the data
  17245. * @param data the data object to associate to the key for this Engine instance
  17246. * @return true if no such key were already present and the data was added successfully, false otherwise
  17247. */
  17248. Engine.prototype.addExternalData = function (key, data) {
  17249. if (!this._externalData) {
  17250. this._externalData = new BABYLON.StringDictionary();
  17251. }
  17252. return this._externalData.add(key, data);
  17253. };
  17254. /**
  17255. * Get an externaly attached data from its key
  17256. * @param key the unique key that identifies the data
  17257. * @return the associated data, if present (can be null), or undefined if not present
  17258. */
  17259. Engine.prototype.getExternalData = function (key) {
  17260. if (!this._externalData) {
  17261. this._externalData = new BABYLON.StringDictionary();
  17262. }
  17263. return this._externalData.get(key);
  17264. };
  17265. /**
  17266. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17267. * @param key the unique key that identifies the data
  17268. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17269. * @return the associated data, can be null if the factory returned null.
  17270. */
  17271. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17272. if (!this._externalData) {
  17273. this._externalData = new BABYLON.StringDictionary();
  17274. }
  17275. return this._externalData.getOrAddWithFactory(key, factory);
  17276. };
  17277. /**
  17278. * Remove an externaly attached data from the Engine instance
  17279. * @param key the unique key that identifies the data
  17280. * @return true if the data was successfully removed, false if it doesn't exist
  17281. */
  17282. Engine.prototype.removeExternalData = function (key) {
  17283. if (!this._externalData) {
  17284. this._externalData = new BABYLON.StringDictionary();
  17285. }
  17286. return this._externalData.remove(key);
  17287. };
  17288. /**
  17289. * Unbind all vertex attributes from the webGL context
  17290. */
  17291. Engine.prototype.unbindAllAttributes = function () {
  17292. if (this._mustWipeVertexAttributes) {
  17293. this._mustWipeVertexAttributes = false;
  17294. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  17295. this._gl.disableVertexAttribArray(i);
  17296. this._vertexAttribArraysEnabled[i] = false;
  17297. this._currentBufferPointers[i].active = false;
  17298. }
  17299. return;
  17300. }
  17301. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  17302. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  17303. continue;
  17304. }
  17305. this._gl.disableVertexAttribArray(i);
  17306. this._vertexAttribArraysEnabled[i] = false;
  17307. this._currentBufferPointers[i].active = false;
  17308. }
  17309. };
  17310. /**
  17311. * 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
  17312. */
  17313. Engine.prototype.releaseEffects = function () {
  17314. for (var name in this._compiledEffects) {
  17315. this._deleteProgram(this._compiledEffects[name]._program);
  17316. }
  17317. this._compiledEffects = {};
  17318. };
  17319. /**
  17320. * Dispose and release all associated resources
  17321. */
  17322. Engine.prototype.dispose = function () {
  17323. this.hideLoadingUI();
  17324. this.stopRenderLoop();
  17325. // Release postProcesses
  17326. while (this.postProcesses.length) {
  17327. this.postProcesses[0].dispose();
  17328. }
  17329. // Empty texture
  17330. if (this._emptyTexture) {
  17331. this._releaseTexture(this._emptyTexture);
  17332. this._emptyTexture = null;
  17333. }
  17334. if (this._emptyCubeTexture) {
  17335. this._releaseTexture(this._emptyCubeTexture);
  17336. this._emptyCubeTexture = null;
  17337. }
  17338. // Rescale PP
  17339. if (this._rescalePostProcess) {
  17340. this._rescalePostProcess.dispose();
  17341. }
  17342. // Release scenes
  17343. while (this.scenes.length) {
  17344. this.scenes[0].dispose();
  17345. }
  17346. // Release audio engine
  17347. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  17348. Engine.audioEngine.dispose();
  17349. }
  17350. // Release effects
  17351. this.releaseEffects();
  17352. // Unbind
  17353. this.unbindAllAttributes();
  17354. this._boundUniforms = [];
  17355. if (this._dummyFramebuffer) {
  17356. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17357. }
  17358. //WebVR
  17359. this.disableVR();
  17360. // Events
  17361. if (BABYLON.Tools.IsWindowObjectExist()) {
  17362. window.removeEventListener("blur", this._onBlur);
  17363. window.removeEventListener("focus", this._onFocus);
  17364. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17365. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17366. if (this._renderingCanvas) {
  17367. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17368. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17369. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17370. if (!this._doNotHandleContextLost) {
  17371. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17372. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17373. }
  17374. }
  17375. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17376. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17377. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17378. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17379. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17380. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17381. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17382. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17383. if (this._onVrDisplayConnect) {
  17384. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17385. if (this._onVrDisplayDisconnect) {
  17386. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17387. }
  17388. if (this._onVrDisplayPresentChange) {
  17389. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17390. }
  17391. this._onVrDisplayConnect = null;
  17392. this._onVrDisplayDisconnect = null;
  17393. }
  17394. }
  17395. // Remove from Instances
  17396. var index = Engine.Instances.indexOf(this);
  17397. if (index >= 0) {
  17398. Engine.Instances.splice(index, 1);
  17399. }
  17400. this._workingCanvas = null;
  17401. this._workingContext = null;
  17402. this._currentBufferPointers = [];
  17403. this._renderingCanvas = null;
  17404. this._currentProgram = null;
  17405. this._bindedRenderFunction = null;
  17406. this.onResizeObservable.clear();
  17407. this.onCanvasBlurObservable.clear();
  17408. this.onCanvasFocusObservable.clear();
  17409. this.onCanvasPointerOutObservable.clear();
  17410. this.onBeginFrameObservable.clear();
  17411. this.onEndFrameObservable.clear();
  17412. BABYLON.Effect.ResetCache();
  17413. // Abort active requests
  17414. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17415. var request = _a[_i];
  17416. request.abort();
  17417. }
  17418. };
  17419. // Loading screen
  17420. /**
  17421. * Display the loading screen
  17422. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17423. */
  17424. Engine.prototype.displayLoadingUI = function () {
  17425. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17426. return;
  17427. }
  17428. var loadingScreen = this.loadingScreen;
  17429. if (loadingScreen) {
  17430. loadingScreen.displayLoadingUI();
  17431. }
  17432. };
  17433. /**
  17434. * Hide the loading screen
  17435. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17436. */
  17437. Engine.prototype.hideLoadingUI = function () {
  17438. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17439. return;
  17440. }
  17441. var loadingScreen = this.loadingScreen;
  17442. if (loadingScreen) {
  17443. loadingScreen.hideLoadingUI();
  17444. }
  17445. };
  17446. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17447. /**
  17448. * Gets the current loading screen object
  17449. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17450. */
  17451. get: function () {
  17452. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  17453. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17454. return this._loadingScreen;
  17455. },
  17456. /**
  17457. * Sets the current loading screen object
  17458. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17459. */
  17460. set: function (loadingScreen) {
  17461. this._loadingScreen = loadingScreen;
  17462. },
  17463. enumerable: true,
  17464. configurable: true
  17465. });
  17466. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17467. /**
  17468. * Sets the current loading screen text
  17469. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17470. */
  17471. set: function (text) {
  17472. this.loadingScreen.loadingUIText = text;
  17473. },
  17474. enumerable: true,
  17475. configurable: true
  17476. });
  17477. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17478. /**
  17479. * Sets the current loading screen background color
  17480. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17481. */
  17482. set: function (color) {
  17483. this.loadingScreen.loadingUIBackgroundColor = color;
  17484. },
  17485. enumerable: true,
  17486. configurable: true
  17487. });
  17488. /**
  17489. * Attach a new callback raised when context lost event is fired
  17490. * @param callback defines the callback to call
  17491. */
  17492. Engine.prototype.attachContextLostEvent = function (callback) {
  17493. if (this._renderingCanvas) {
  17494. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17495. }
  17496. };
  17497. /**
  17498. * Attach a new callback raised when context restored event is fired
  17499. * @param callback defines the callback to call
  17500. */
  17501. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17502. if (this._renderingCanvas) {
  17503. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17504. }
  17505. };
  17506. /**
  17507. * Gets the source code of the vertex shader associated with a specific webGL program
  17508. * @param program defines the program to use
  17509. * @returns a string containing the source code of the vertex shader associated with the program
  17510. */
  17511. Engine.prototype.getVertexShaderSource = function (program) {
  17512. var shaders = this._gl.getAttachedShaders(program);
  17513. if (!shaders) {
  17514. return null;
  17515. }
  17516. return this._gl.getShaderSource(shaders[0]);
  17517. };
  17518. /**
  17519. * Gets the source code of the fragment shader associated with a specific webGL program
  17520. * @param program defines the program to use
  17521. * @returns a string containing the source code of the fragment shader associated with the program
  17522. */
  17523. Engine.prototype.getFragmentShaderSource = function (program) {
  17524. var shaders = this._gl.getAttachedShaders(program);
  17525. if (!shaders) {
  17526. return null;
  17527. }
  17528. return this._gl.getShaderSource(shaders[1]);
  17529. };
  17530. /**
  17531. * Get the current error code of the webGL context
  17532. * @returns the error code
  17533. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17534. */
  17535. Engine.prototype.getError = function () {
  17536. return this._gl.getError();
  17537. };
  17538. // FPS
  17539. /**
  17540. * Gets the current framerate
  17541. * @returns a number representing the framerate
  17542. */
  17543. Engine.prototype.getFps = function () {
  17544. return this._fps;
  17545. };
  17546. /**
  17547. * Gets the time spent between current and previous frame
  17548. * @returns a number representing the delta time in ms
  17549. */
  17550. Engine.prototype.getDeltaTime = function () {
  17551. return this._deltaTime;
  17552. };
  17553. Engine.prototype._measureFps = function () {
  17554. this._performanceMonitor.sampleFrame();
  17555. this._fps = this._performanceMonitor.averageFPS;
  17556. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17557. };
  17558. /** @hidden */
  17559. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17560. if (faceIndex === void 0) { faceIndex = -1; }
  17561. if (level === void 0) { level = 0; }
  17562. if (buffer === void 0) { buffer = null; }
  17563. var gl = this._gl;
  17564. if (!this._dummyFramebuffer) {
  17565. var dummy = gl.createFramebuffer();
  17566. if (!dummy) {
  17567. throw new Error("Unable to create dummy framebuffer");
  17568. }
  17569. this._dummyFramebuffer = dummy;
  17570. }
  17571. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17572. if (faceIndex > -1) {
  17573. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17574. }
  17575. else {
  17576. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17577. }
  17578. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17579. switch (readType) {
  17580. case gl.UNSIGNED_BYTE:
  17581. if (!buffer) {
  17582. buffer = new Uint8Array(4 * width * height);
  17583. }
  17584. readType = gl.UNSIGNED_BYTE;
  17585. break;
  17586. default:
  17587. if (!buffer) {
  17588. buffer = new Float32Array(4 * width * height);
  17589. }
  17590. readType = gl.FLOAT;
  17591. break;
  17592. }
  17593. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17594. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17595. return buffer;
  17596. };
  17597. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17598. if (this._webGLVersion > 1) {
  17599. return this._caps.colorBufferFloat;
  17600. }
  17601. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17602. };
  17603. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17604. if (this._webGLVersion > 1) {
  17605. return this._caps.colorBufferFloat;
  17606. }
  17607. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17608. };
  17609. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17610. Engine.prototype._canRenderToFramebuffer = function (type) {
  17611. var gl = this._gl;
  17612. //clear existing errors
  17613. while (gl.getError() !== gl.NO_ERROR) { }
  17614. var successful = true;
  17615. var texture = gl.createTexture();
  17616. gl.bindTexture(gl.TEXTURE_2D, texture);
  17617. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17618. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17619. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17620. var fb = gl.createFramebuffer();
  17621. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17622. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17623. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17624. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17625. successful = successful && (gl.getError() === gl.NO_ERROR);
  17626. //try render by clearing frame buffer's color buffer
  17627. if (successful) {
  17628. gl.clear(gl.COLOR_BUFFER_BIT);
  17629. successful = successful && (gl.getError() === gl.NO_ERROR);
  17630. }
  17631. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17632. if (successful) {
  17633. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17634. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17635. var readFormat = gl.RGBA;
  17636. var readType = gl.UNSIGNED_BYTE;
  17637. var buffer = new Uint8Array(4);
  17638. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17639. successful = successful && (gl.getError() === gl.NO_ERROR);
  17640. }
  17641. //clean up
  17642. gl.deleteTexture(texture);
  17643. gl.deleteFramebuffer(fb);
  17644. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17645. //clear accumulated errors
  17646. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17647. return successful;
  17648. };
  17649. /** @hidden */
  17650. Engine.prototype._getWebGLTextureType = function (type) {
  17651. if (this._webGLVersion === 1) {
  17652. switch (type) {
  17653. case Engine.TEXTURETYPE_FLOAT:
  17654. return this._gl.FLOAT;
  17655. case Engine.TEXTURETYPE_HALF_FLOAT:
  17656. return this._gl.HALF_FLOAT_OES;
  17657. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17658. return this._gl.UNSIGNED_BYTE;
  17659. }
  17660. return this._gl.UNSIGNED_BYTE;
  17661. }
  17662. switch (type) {
  17663. case Engine.TEXTURETYPE_BYTE:
  17664. return this._gl.BYTE;
  17665. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17666. return this._gl.UNSIGNED_BYTE;
  17667. case Engine.TEXTURETYPE_SHORT:
  17668. return this._gl.SHORT;
  17669. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17670. return this._gl.UNSIGNED_SHORT;
  17671. case Engine.TEXTURETYPE_INT:
  17672. return this._gl.INT;
  17673. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17674. return this._gl.UNSIGNED_INT;
  17675. case Engine.TEXTURETYPE_FLOAT:
  17676. return this._gl.FLOAT;
  17677. case Engine.TEXTURETYPE_HALF_FLOAT:
  17678. return this._gl.HALF_FLOAT;
  17679. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17680. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17681. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17682. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17683. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17684. return this._gl.UNSIGNED_SHORT_5_6_5;
  17685. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17686. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17687. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17688. return this._gl.UNSIGNED_INT_24_8;
  17689. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17690. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17691. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17692. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17693. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17694. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17695. }
  17696. return this._gl.UNSIGNED_BYTE;
  17697. };
  17698. ;
  17699. Engine.prototype._getInternalFormat = function (format) {
  17700. var internalFormat = this._gl.RGBA;
  17701. switch (format) {
  17702. case Engine.TEXTUREFORMAT_ALPHA:
  17703. internalFormat = this._gl.ALPHA;
  17704. break;
  17705. case Engine.TEXTUREFORMAT_LUMINANCE:
  17706. internalFormat = this._gl.LUMINANCE;
  17707. break;
  17708. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17709. internalFormat = this._gl.LUMINANCE_ALPHA;
  17710. break;
  17711. case Engine.TEXTUREFORMAT_RED:
  17712. internalFormat = this._gl.RED;
  17713. break;
  17714. case Engine.TEXTUREFORMAT_RG:
  17715. internalFormat = this._gl.RG;
  17716. break;
  17717. case Engine.TEXTUREFORMAT_RGB:
  17718. internalFormat = this._gl.RGB;
  17719. break;
  17720. case Engine.TEXTUREFORMAT_RGBA:
  17721. internalFormat = this._gl.RGBA;
  17722. break;
  17723. }
  17724. if (this._webGLVersion > 1) {
  17725. switch (format) {
  17726. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17727. internalFormat = this._gl.RED_INTEGER;
  17728. break;
  17729. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17730. internalFormat = this._gl.RG_INTEGER;
  17731. break;
  17732. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17733. internalFormat = this._gl.RGB_INTEGER;
  17734. break;
  17735. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17736. internalFormat = this._gl.RGBA_INTEGER;
  17737. break;
  17738. }
  17739. }
  17740. return internalFormat;
  17741. };
  17742. /** @hidden */
  17743. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17744. if (this._webGLVersion === 1) {
  17745. if (format !== undefined) {
  17746. switch (format) {
  17747. case Engine.TEXTUREFORMAT_ALPHA:
  17748. return this._gl.ALPHA;
  17749. case Engine.TEXTUREFORMAT_LUMINANCE:
  17750. return this._gl.LUMINANCE;
  17751. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17752. return this._gl.LUMINANCE_ALPHA;
  17753. }
  17754. }
  17755. return this._gl.RGBA;
  17756. }
  17757. switch (type) {
  17758. case Engine.TEXTURETYPE_BYTE:
  17759. switch (format) {
  17760. case Engine.TEXTUREFORMAT_RED:
  17761. return this._gl.R8_SNORM;
  17762. case Engine.TEXTUREFORMAT_RG:
  17763. return this._gl.RG8_SNORM;
  17764. case Engine.TEXTUREFORMAT_RGB:
  17765. return this._gl.RGB8_SNORM;
  17766. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17767. return this._gl.R8I;
  17768. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17769. return this._gl.RG8I;
  17770. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17771. return this._gl.RGB8I;
  17772. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17773. return this._gl.RGBA8I;
  17774. default:
  17775. return this._gl.RGBA8_SNORM;
  17776. }
  17777. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17778. switch (format) {
  17779. case Engine.TEXTUREFORMAT_RED:
  17780. return this._gl.R8;
  17781. case Engine.TEXTUREFORMAT_RG:
  17782. return this._gl.RG8;
  17783. case Engine.TEXTUREFORMAT_RGB:
  17784. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17785. case Engine.TEXTUREFORMAT_RGBA:
  17786. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17787. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17788. return this._gl.R8UI;
  17789. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17790. return this._gl.RG8UI;
  17791. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17792. return this._gl.RGB8UI;
  17793. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17794. return this._gl.RGBA8UI;
  17795. default:
  17796. return this._gl.RGBA8;
  17797. }
  17798. case Engine.TEXTURETYPE_SHORT:
  17799. switch (format) {
  17800. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17801. return this._gl.R16I;
  17802. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17803. return this._gl.RG16I;
  17804. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17805. return this._gl.RGB16I;
  17806. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17807. return this._gl.RGBA16I;
  17808. default:
  17809. return this._gl.RGBA16I;
  17810. }
  17811. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17812. switch (format) {
  17813. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17814. return this._gl.R16UI;
  17815. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17816. return this._gl.RG16UI;
  17817. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17818. return this._gl.RGB16UI;
  17819. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17820. return this._gl.RGBA16UI;
  17821. default:
  17822. return this._gl.RGBA16UI;
  17823. }
  17824. case Engine.TEXTURETYPE_INT:
  17825. switch (format) {
  17826. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17827. return this._gl.R32I;
  17828. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17829. return this._gl.RG32I;
  17830. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17831. return this._gl.RGB32I;
  17832. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17833. return this._gl.RGBA32I;
  17834. default:
  17835. return this._gl.RGBA32I;
  17836. }
  17837. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17838. switch (format) {
  17839. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17840. return this._gl.R32UI;
  17841. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17842. return this._gl.RG32UI;
  17843. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17844. return this._gl.RGB32UI;
  17845. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17846. return this._gl.RGBA32UI;
  17847. default:
  17848. return this._gl.RGBA32UI;
  17849. }
  17850. case Engine.TEXTURETYPE_FLOAT:
  17851. switch (format) {
  17852. case Engine.TEXTUREFORMAT_RED:
  17853. return this._gl.R32F; // By default. Other possibility is R16F.
  17854. case Engine.TEXTUREFORMAT_RG:
  17855. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17856. case Engine.TEXTUREFORMAT_RGB:
  17857. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17858. case Engine.TEXTUREFORMAT_RGBA:
  17859. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17860. default:
  17861. return this._gl.RGBA32F;
  17862. }
  17863. case Engine.TEXTURETYPE_HALF_FLOAT:
  17864. switch (format) {
  17865. case Engine.TEXTUREFORMAT_RED:
  17866. return this._gl.R16F;
  17867. case Engine.TEXTUREFORMAT_RG:
  17868. return this._gl.RG16F;
  17869. case Engine.TEXTUREFORMAT_RGB:
  17870. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17871. case Engine.TEXTUREFORMAT_RGBA:
  17872. return this._gl.RGBA16F;
  17873. default:
  17874. return this._gl.RGBA16F;
  17875. }
  17876. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17877. return this._gl.RGB565;
  17878. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17879. return this._gl.R11F_G11F_B10F;
  17880. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17881. return this._gl.RGB9_E5;
  17882. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17883. return this._gl.RGBA4;
  17884. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17885. return this._gl.RGB5_A1;
  17886. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17887. switch (format) {
  17888. case Engine.TEXTUREFORMAT_RGBA:
  17889. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17890. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17891. return this._gl.RGB10_A2UI;
  17892. default:
  17893. return this._gl.RGB10_A2;
  17894. }
  17895. }
  17896. return this._gl.RGBA8;
  17897. };
  17898. ;
  17899. /** @hidden */
  17900. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17901. if (type === Engine.TEXTURETYPE_FLOAT) {
  17902. return this._gl.RGBA32F;
  17903. }
  17904. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17905. return this._gl.RGBA16F;
  17906. }
  17907. return this._gl.RGBA8;
  17908. };
  17909. ;
  17910. /** @hidden */
  17911. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17912. var _this = this;
  17913. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17914. this._activeRequests.push(request);
  17915. request.onCompleteObservable.add(function (request) {
  17916. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17917. });
  17918. return request;
  17919. };
  17920. /** @hidden */
  17921. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17922. var _this = this;
  17923. return new Promise(function (resolve, reject) {
  17924. _this._loadFile(url, function (data) {
  17925. resolve(data);
  17926. }, undefined, database, useArrayBuffer, function (request, exception) {
  17927. reject(exception);
  17928. });
  17929. });
  17930. };
  17931. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17932. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17933. var onload = function (data) {
  17934. loadedFiles[index] = data;
  17935. loadedFiles._internalCount++;
  17936. if (loadedFiles._internalCount === 6) {
  17937. onfinish(loadedFiles);
  17938. }
  17939. };
  17940. var onerror = function (request, exception) {
  17941. if (onErrorCallBack && request) {
  17942. onErrorCallBack(request.status + " " + request.statusText, exception);
  17943. }
  17944. };
  17945. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17946. };
  17947. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17948. if (onError === void 0) { onError = null; }
  17949. var loadedFiles = [];
  17950. loadedFiles._internalCount = 0;
  17951. for (var index = 0; index < 6; index++) {
  17952. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17953. }
  17954. };
  17955. // Statics
  17956. /**
  17957. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17958. * @returns true if the engine can be created
  17959. * @ignorenaming
  17960. */
  17961. Engine.isSupported = function () {
  17962. try {
  17963. var tempcanvas = document.createElement("canvas");
  17964. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17965. return gl != null && !!window.WebGLRenderingContext;
  17966. }
  17967. catch (e) {
  17968. return false;
  17969. }
  17970. };
  17971. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17972. Engine.ExceptionList = [
  17973. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17974. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17975. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17976. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17977. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17978. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17979. ];
  17980. /** Gets the list of created engines */
  17981. Engine.Instances = new Array();
  17982. /**
  17983. * Hidden
  17984. */
  17985. Engine._TextureLoaders = [];
  17986. // Const statics
  17987. /** Defines that alpha blending is disabled */
  17988. Engine.ALPHA_DISABLE = 0;
  17989. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17990. Engine.ALPHA_ADD = 1;
  17991. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17992. Engine.ALPHA_COMBINE = 2;
  17993. /** Defines that alpha blending to DEST - SRC * DEST */
  17994. Engine.ALPHA_SUBTRACT = 3;
  17995. /** Defines that alpha blending to SRC * DEST */
  17996. Engine.ALPHA_MULTIPLY = 4;
  17997. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17998. Engine.ALPHA_MAXIMIZED = 5;
  17999. /** Defines that alpha blending to SRC + DEST */
  18000. Engine.ALPHA_ONEONE = 6;
  18001. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  18002. Engine.ALPHA_PREMULTIPLIED = 7;
  18003. /**
  18004. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  18005. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  18006. */
  18007. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  18008. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  18009. Engine.ALPHA_INTERPOLATE = 9;
  18010. /**
  18011. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  18012. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  18013. */
  18014. Engine.ALPHA_SCREENMODE = 10;
  18015. /** Defines that the ressource is not delayed*/
  18016. Engine.DELAYLOADSTATE_NONE = 0;
  18017. /** Defines that the ressource was successfully delay loaded */
  18018. Engine.DELAYLOADSTATE_LOADED = 1;
  18019. /** Defines that the ressource is currently delay loading */
  18020. Engine.DELAYLOADSTATE_LOADING = 2;
  18021. /** Defines that the ressource is delayed and has not started loading */
  18022. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  18023. // Depht or Stencil test Constants.
  18024. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  18025. Engine.NEVER = 0x0200;
  18026. /** 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 */
  18027. Engine.ALWAYS = 0x0207;
  18028. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  18029. Engine.LESS = 0x0201;
  18030. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  18031. Engine.EQUAL = 0x0202;
  18032. /** 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 */
  18033. Engine.LEQUAL = 0x0203;
  18034. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  18035. Engine.GREATER = 0x0204;
  18036. /** 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 */
  18037. Engine.GEQUAL = 0x0206;
  18038. /** 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 */
  18039. Engine.NOTEQUAL = 0x0205;
  18040. // Stencil Actions Constants.
  18041. /** Passed to stencilOperation to specify that stencil value must be kept */
  18042. Engine.KEEP = 0x1E00;
  18043. /** Passed to stencilOperation to specify that stencil value must be replaced */
  18044. Engine.REPLACE = 0x1E01;
  18045. /** Passed to stencilOperation to specify that stencil value must be incremented */
  18046. Engine.INCR = 0x1E02;
  18047. /** Passed to stencilOperation to specify that stencil value must be decremented */
  18048. Engine.DECR = 0x1E03;
  18049. /** Passed to stencilOperation to specify that stencil value must be inverted */
  18050. Engine.INVERT = 0x150A;
  18051. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  18052. Engine.INCR_WRAP = 0x8507;
  18053. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  18054. Engine.DECR_WRAP = 0x8508;
  18055. /** Texture is not repeating outside of 0..1 UVs */
  18056. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  18057. /** Texture is repeating outside of 0..1 UVs */
  18058. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  18059. /** Texture is repeating and mirrored */
  18060. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  18061. /** ALPHA */
  18062. Engine.TEXTUREFORMAT_ALPHA = 0;
  18063. /** LUMINANCE */
  18064. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  18065. /** LUMINANCE_ALPHA */
  18066. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  18067. /** RGB */
  18068. Engine.TEXTUREFORMAT_RGB = 4;
  18069. /** RGBA */
  18070. Engine.TEXTUREFORMAT_RGBA = 5;
  18071. /** RED */
  18072. Engine.TEXTUREFORMAT_RED = 6;
  18073. /** RED (2nd reference) */
  18074. Engine.TEXTUREFORMAT_R = 6;
  18075. /** RG */
  18076. Engine.TEXTUREFORMAT_RG = 7;
  18077. /** RED_INTEGER */
  18078. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  18079. /** RED_INTEGER (2nd reference) */
  18080. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  18081. /** RG_INTEGER */
  18082. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  18083. /** RGB_INTEGER */
  18084. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  18085. /** RGBA_INTEGER */
  18086. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  18087. /** UNSIGNED_BYTE */
  18088. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  18089. /** UNSIGNED_BYTE (2nd reference) */
  18090. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  18091. /** FLOAT */
  18092. Engine.TEXTURETYPE_FLOAT = 1;
  18093. /** HALF_FLOAT */
  18094. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  18095. /** BYTE */
  18096. Engine.TEXTURETYPE_BYTE = 3;
  18097. /** SHORT */
  18098. Engine.TEXTURETYPE_SHORT = 4;
  18099. /** UNSIGNED_SHORT */
  18100. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  18101. /** INT */
  18102. Engine.TEXTURETYPE_INT = 6;
  18103. /** UNSIGNED_INT */
  18104. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  18105. /** UNSIGNED_SHORT_4_4_4_4 */
  18106. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  18107. /** UNSIGNED_SHORT_5_5_5_1 */
  18108. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  18109. /** UNSIGNED_SHORT_5_6_5 */
  18110. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  18111. /** UNSIGNED_INT_2_10_10_10_REV */
  18112. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  18113. /** UNSIGNED_INT_24_8 */
  18114. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  18115. /** UNSIGNED_INT_10F_11F_11F_REV */
  18116. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  18117. /** UNSIGNED_INT_5_9_9_9_REV */
  18118. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  18119. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  18120. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  18121. /** nearest is mag = nearest and min = nearest and mip = linear */
  18122. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  18123. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18124. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  18125. /** Trilinear is mag = linear and min = linear and mip = linear */
  18126. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  18127. /** nearest is mag = nearest and min = nearest and mip = linear */
  18128. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  18129. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18130. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  18131. /** Trilinear is mag = linear and min = linear and mip = linear */
  18132. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  18133. /** mag = nearest and min = nearest and mip = nearest */
  18134. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  18135. /** mag = nearest and min = linear and mip = nearest */
  18136. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  18137. /** mag = nearest and min = linear and mip = linear */
  18138. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  18139. /** mag = nearest and min = linear and mip = none */
  18140. Engine.TEXTURE_NEAREST_LINEAR = 7;
  18141. /** mag = nearest and min = nearest and mip = none */
  18142. Engine.TEXTURE_NEAREST_NEAREST = 8;
  18143. /** mag = linear and min = nearest and mip = nearest */
  18144. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  18145. /** mag = linear and min = nearest and mip = linear */
  18146. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  18147. /** mag = linear and min = linear and mip = none */
  18148. Engine.TEXTURE_LINEAR_LINEAR = 11;
  18149. /** mag = linear and min = nearest and mip = none */
  18150. Engine.TEXTURE_LINEAR_NEAREST = 12;
  18151. /** Explicit coordinates mode */
  18152. Engine.TEXTURE_EXPLICIT_MODE = 0;
  18153. /** Spherical coordinates mode */
  18154. Engine.TEXTURE_SPHERICAL_MODE = 1;
  18155. /** Planar coordinates mode */
  18156. Engine.TEXTURE_PLANAR_MODE = 2;
  18157. /** Cubic coordinates mode */
  18158. Engine.TEXTURE_CUBIC_MODE = 3;
  18159. /** Projection coordinates mode */
  18160. Engine.TEXTURE_PROJECTION_MODE = 4;
  18161. /** Skybox coordinates mode */
  18162. Engine.TEXTURE_SKYBOX_MODE = 5;
  18163. /** Inverse Cubic coordinates mode */
  18164. Engine.TEXTURE_INVCUBIC_MODE = 6;
  18165. /** Equirectangular coordinates mode */
  18166. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  18167. /** Equirectangular Fixed coordinates mode */
  18168. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  18169. /** Equirectangular Fixed Mirrored coordinates mode */
  18170. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18171. // Texture rescaling mode
  18172. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  18173. Engine.SCALEMODE_FLOOR = 1;
  18174. /** Defines that texture rescaling will look for the nearest power of 2 size */
  18175. Engine.SCALEMODE_NEAREST = 2;
  18176. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  18177. Engine.SCALEMODE_CEILING = 3;
  18178. // Updatable statics so stick with vars here
  18179. /**
  18180. * Gets or sets the epsilon value used by collision engine
  18181. */
  18182. Engine.CollisionsEpsilon = 0.001;
  18183. /**
  18184. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  18185. */
  18186. Engine.CodeRepository = "src/";
  18187. /**
  18188. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  18189. */
  18190. Engine.ShadersRepository = "src/Shaders/";
  18191. return Engine;
  18192. }());
  18193. BABYLON.Engine = Engine;
  18194. })(BABYLON || (BABYLON = {}));
  18195. //# sourceMappingURL=babylon.engine.js.map
  18196. var BABYLON;
  18197. (function (BABYLON) {
  18198. /**
  18199. * Node is the basic class for all scene objects (Mesh, Light, Camera.)
  18200. */
  18201. var Node = /** @class */ (function () {
  18202. /**
  18203. * Creates a new Node
  18204. * @param {string} name - the name and id to be given to this node
  18205. * @param {BABYLON.Scene} the scene this node will be added to
  18206. */
  18207. function Node(name, scene) {
  18208. if (scene === void 0) { scene = null; }
  18209. /**
  18210. * Gets or sets a string used to store user defined state for the node
  18211. */
  18212. this.state = "";
  18213. /**
  18214. * Gets or sets an object used to store user defined information for the node
  18215. */
  18216. this.metadata = null;
  18217. /**
  18218. * Gets or sets a boolean used to define if the node must be serialized
  18219. */
  18220. this.doNotSerialize = false;
  18221. /** @hidden */
  18222. this._isDisposed = false;
  18223. /**
  18224. * Gets a list of Animations associated with the node
  18225. */
  18226. this.animations = new Array();
  18227. this._ranges = {};
  18228. this._isEnabled = true;
  18229. this._isParentEnabled = true;
  18230. this._isReady = true;
  18231. /** @hidden */
  18232. this._currentRenderId = -1;
  18233. this._parentRenderId = -1;
  18234. this._childRenderId = -1;
  18235. /** @hidden */
  18236. this._worldMatrix = BABYLON.Matrix.Identity();
  18237. /** @hidden */
  18238. this._worldMatrixDeterminant = 0;
  18239. /** @hidden */
  18240. this._sceneRootNodesIndex = -1;
  18241. this._animationPropertiesOverride = null;
  18242. /**
  18243. * An event triggered when the mesh is disposed
  18244. */
  18245. this.onDisposeObservable = new BABYLON.Observable();
  18246. // Behaviors
  18247. this._behaviors = new Array();
  18248. this.name = name;
  18249. this.id = name;
  18250. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  18251. this.uniqueId = this._scene.getUniqueId();
  18252. this._initCache();
  18253. this.addToSceneRootNodes();
  18254. }
  18255. /**
  18256. * Add a new node constructor
  18257. * @param type defines the type name of the node to construct
  18258. * @param constructorFunc defines the constructor function
  18259. */
  18260. Node.AddNodeConstructor = function (type, constructorFunc) {
  18261. this._NodeConstructors[type] = constructorFunc;
  18262. };
  18263. /**
  18264. * Returns a node constructor based on type name
  18265. * @param type defines the type name
  18266. * @param name defines the new node name
  18267. * @param scene defines the hosting scene
  18268. * @param options defines optional options to transmit to constructors
  18269. * @returns the new constructor or null
  18270. */
  18271. Node.Construct = function (type, name, scene, options) {
  18272. var constructorFunc = this._NodeConstructors[type];
  18273. if (!constructorFunc) {
  18274. return null;
  18275. }
  18276. return constructorFunc(name, scene, options);
  18277. };
  18278. /**
  18279. * Gets a boolean indicating if the node has been disposed
  18280. * @returns true if the node was disposed
  18281. */
  18282. Node.prototype.isDisposed = function () {
  18283. return this._isDisposed;
  18284. };
  18285. Object.defineProperty(Node.prototype, "parent", {
  18286. get: function () {
  18287. return this._parentNode;
  18288. },
  18289. /**
  18290. * Gets or sets the parent of the node
  18291. */
  18292. set: function (parent) {
  18293. if (this._parentNode === parent) {
  18294. return;
  18295. }
  18296. var previousParentNode = this._parentNode;
  18297. // Remove self from list of children of parent
  18298. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  18299. var index = this._parentNode._children.indexOf(this);
  18300. if (index !== -1) {
  18301. this._parentNode._children.splice(index, 1);
  18302. }
  18303. if (!parent) {
  18304. this.addToSceneRootNodes();
  18305. }
  18306. }
  18307. // Store new parent
  18308. this._parentNode = parent;
  18309. // Add as child to new parent
  18310. if (this._parentNode) {
  18311. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  18312. this._parentNode._children = new Array();
  18313. }
  18314. this._parentNode._children.push(this);
  18315. if (!previousParentNode) {
  18316. this.removeFromSceneRootNodes();
  18317. }
  18318. }
  18319. // Enabled state
  18320. this._syncParentEnabledState();
  18321. },
  18322. enumerable: true,
  18323. configurable: true
  18324. });
  18325. Node.prototype.addToSceneRootNodes = function () {
  18326. if (this._sceneRootNodesIndex === -1) {
  18327. this._sceneRootNodesIndex = this._scene.rootNodes.length;
  18328. this._scene.rootNodes.push(this);
  18329. }
  18330. };
  18331. Node.prototype.removeFromSceneRootNodes = function () {
  18332. if (this._sceneRootNodesIndex !== -1) {
  18333. var rootNodes = this._scene.rootNodes;
  18334. var lastIdx = rootNodes.length - 1;
  18335. rootNodes[this._sceneRootNodesIndex] = rootNodes[lastIdx];
  18336. rootNodes[this._sceneRootNodesIndex]._sceneRootNodesIndex = this._sceneRootNodesIndex;
  18337. this._scene.rootNodes.pop();
  18338. this._sceneRootNodesIndex = -1;
  18339. }
  18340. };
  18341. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  18342. /**
  18343. * Gets or sets the animation properties override
  18344. */
  18345. get: function () {
  18346. if (!this._animationPropertiesOverride) {
  18347. return this._scene.animationPropertiesOverride;
  18348. }
  18349. return this._animationPropertiesOverride;
  18350. },
  18351. set: function (value) {
  18352. this._animationPropertiesOverride = value;
  18353. },
  18354. enumerable: true,
  18355. configurable: true
  18356. });
  18357. /**
  18358. * Gets a string idenfifying the name of the class
  18359. * @returns "Node" string
  18360. */
  18361. Node.prototype.getClassName = function () {
  18362. return "Node";
  18363. };
  18364. Object.defineProperty(Node.prototype, "onDispose", {
  18365. /**
  18366. * Sets a callback that will be raised when the node will be disposed
  18367. */
  18368. set: function (callback) {
  18369. if (this._onDisposeObserver) {
  18370. this.onDisposeObservable.remove(this._onDisposeObserver);
  18371. }
  18372. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18373. },
  18374. enumerable: true,
  18375. configurable: true
  18376. });
  18377. /**
  18378. * Gets the scene of the node
  18379. * @returns a {BABYLON.Scene}
  18380. */
  18381. Node.prototype.getScene = function () {
  18382. return this._scene;
  18383. };
  18384. /**
  18385. * Gets the engine of the node
  18386. * @returns a {BABYLON.Engine}
  18387. */
  18388. Node.prototype.getEngine = function () {
  18389. return this._scene.getEngine();
  18390. };
  18391. /**
  18392. * Attach a behavior to the node
  18393. * @see http://doc.babylonjs.com/features/behaviour
  18394. * @param behavior defines the behavior to attach
  18395. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  18396. * @returns the current Node
  18397. */
  18398. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  18399. var _this = this;
  18400. if (attachImmediately === void 0) { attachImmediately = false; }
  18401. var index = this._behaviors.indexOf(behavior);
  18402. if (index !== -1) {
  18403. return this;
  18404. }
  18405. behavior.init();
  18406. if (this._scene.isLoading && !attachImmediately) {
  18407. // We defer the attach when the scene will be loaded
  18408. this._scene.onDataLoadedObservable.addOnce(function () {
  18409. behavior.attach(_this);
  18410. });
  18411. }
  18412. else {
  18413. behavior.attach(this);
  18414. }
  18415. this._behaviors.push(behavior);
  18416. return this;
  18417. };
  18418. /**
  18419. * Remove an attached behavior
  18420. * @see http://doc.babylonjs.com/features/behaviour
  18421. * @param behavior defines the behavior to attach
  18422. * @returns the current Node
  18423. */
  18424. Node.prototype.removeBehavior = function (behavior) {
  18425. var index = this._behaviors.indexOf(behavior);
  18426. if (index === -1) {
  18427. return this;
  18428. }
  18429. this._behaviors[index].detach();
  18430. this._behaviors.splice(index, 1);
  18431. return this;
  18432. };
  18433. Object.defineProperty(Node.prototype, "behaviors", {
  18434. /**
  18435. * Gets the list of attached behaviors
  18436. * @see http://doc.babylonjs.com/features/behaviour
  18437. */
  18438. get: function () {
  18439. return this._behaviors;
  18440. },
  18441. enumerable: true,
  18442. configurable: true
  18443. });
  18444. /**
  18445. * Gets an attached behavior by name
  18446. * @param name defines the name of the behavior to look for
  18447. * @see http://doc.babylonjs.com/features/behaviour
  18448. * @returns null if behavior was not found else the requested behavior
  18449. */
  18450. Node.prototype.getBehaviorByName = function (name) {
  18451. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  18452. var behavior = _a[_i];
  18453. if (behavior.name === name) {
  18454. return behavior;
  18455. }
  18456. }
  18457. return null;
  18458. };
  18459. /**
  18460. * Returns the latest update of the World matrix
  18461. * @returns a Matrix
  18462. */
  18463. Node.prototype.getWorldMatrix = function () {
  18464. if (this._currentRenderId !== this._scene.getRenderId()) {
  18465. this.computeWorldMatrix();
  18466. }
  18467. return this._worldMatrix;
  18468. };
  18469. /** @hidden */
  18470. Node.prototype._getWorldMatrixDeterminant = function () {
  18471. return this._worldMatrixDeterminant;
  18472. };
  18473. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  18474. /**
  18475. * Returns directly the latest state of the mesh World matrix.
  18476. * A Matrix is returned.
  18477. */
  18478. get: function () {
  18479. return this._worldMatrix;
  18480. },
  18481. enumerable: true,
  18482. configurable: true
  18483. });
  18484. // override it in derived class if you add new variables to the cache
  18485. // and call the parent class method
  18486. /** @hidden */
  18487. Node.prototype._initCache = function () {
  18488. this._cache = {};
  18489. this._cache.parent = undefined;
  18490. };
  18491. /** @hidden */
  18492. Node.prototype.updateCache = function (force) {
  18493. if (!force && this.isSynchronized())
  18494. return;
  18495. this._cache.parent = this.parent;
  18496. this._updateCache();
  18497. };
  18498. // override it in derived class if you add new variables to the cache
  18499. // and call the parent class method if !ignoreParentClass
  18500. /** @hidden */
  18501. Node.prototype._updateCache = function (ignoreParentClass) {
  18502. };
  18503. // override it in derived class if you add new variables to the cache
  18504. /** @hidden */
  18505. Node.prototype._isSynchronized = function () {
  18506. return true;
  18507. };
  18508. /** @hidden */
  18509. Node.prototype._markSyncedWithParent = function () {
  18510. if (this._parentNode) {
  18511. this._parentRenderId = this._parentNode._childRenderId;
  18512. }
  18513. };
  18514. /** @hidden */
  18515. Node.prototype.isSynchronizedWithParent = function () {
  18516. if (!this._parentNode) {
  18517. return true;
  18518. }
  18519. if (this._parentRenderId !== this._parentNode._childRenderId) {
  18520. return false;
  18521. }
  18522. return this._parentNode.isSynchronized();
  18523. };
  18524. /** @hidden */
  18525. Node.prototype.isSynchronized = function () {
  18526. if (this._cache.parent != this._parentNode) {
  18527. this._cache.parent = this._parentNode;
  18528. return false;
  18529. }
  18530. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18531. return false;
  18532. }
  18533. return this._isSynchronized();
  18534. };
  18535. /**
  18536. * Is this node ready to be used/rendered
  18537. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18538. * @return true if the node is ready
  18539. */
  18540. Node.prototype.isReady = function (completeCheck) {
  18541. if (completeCheck === void 0) { completeCheck = false; }
  18542. return this._isReady;
  18543. };
  18544. /**
  18545. * Is this node enabled?
  18546. * 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
  18547. * @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
  18548. * @return whether this node (and its parent) is enabled
  18549. */
  18550. Node.prototype.isEnabled = function (checkAncestors) {
  18551. if (checkAncestors === void 0) { checkAncestors = true; }
  18552. if (checkAncestors === false) {
  18553. return this._isEnabled;
  18554. }
  18555. if (!this._isEnabled) {
  18556. return false;
  18557. }
  18558. return this._isParentEnabled;
  18559. };
  18560. /** @hidden */
  18561. Node.prototype._syncParentEnabledState = function () {
  18562. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18563. if (this._children) {
  18564. this._children.forEach(function (c) {
  18565. c._syncParentEnabledState(); // Force children to update accordingly
  18566. });
  18567. }
  18568. };
  18569. /**
  18570. * Set the enabled state of this node
  18571. * @param value defines the new enabled state
  18572. */
  18573. Node.prototype.setEnabled = function (value) {
  18574. this._isEnabled = value;
  18575. this._syncParentEnabledState();
  18576. };
  18577. /**
  18578. * Is this node a descendant of the given node?
  18579. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18580. * @param ancestor defines the parent node to inspect
  18581. * @returns a boolean indicating if this node is a descendant of the given node
  18582. */
  18583. Node.prototype.isDescendantOf = function (ancestor) {
  18584. if (this.parent) {
  18585. if (this.parent === ancestor) {
  18586. return true;
  18587. }
  18588. return this.parent.isDescendantOf(ancestor);
  18589. }
  18590. return false;
  18591. };
  18592. /** @hidden */
  18593. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18594. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18595. if (!this._children) {
  18596. return;
  18597. }
  18598. for (var index = 0; index < this._children.length; index++) {
  18599. var item = this._children[index];
  18600. if (!predicate || predicate(item)) {
  18601. results.push(item);
  18602. }
  18603. if (!directDescendantsOnly) {
  18604. item._getDescendants(results, false, predicate);
  18605. }
  18606. }
  18607. };
  18608. /**
  18609. * Will return all nodes that have this node as ascendant
  18610. * @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
  18611. * @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
  18612. * @return all children nodes of all types
  18613. */
  18614. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18615. var results = new Array();
  18616. this._getDescendants(results, directDescendantsOnly, predicate);
  18617. return results;
  18618. };
  18619. /**
  18620. * Get all child-meshes of this node
  18621. * @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
  18622. * @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
  18623. * @returns an array of {BABYLON.AbstractMesh}
  18624. */
  18625. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18626. var results = [];
  18627. this._getDescendants(results, directDescendantsOnly, function (node) {
  18628. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18629. });
  18630. return results;
  18631. };
  18632. /**
  18633. * Get all child-transformNodes of this node
  18634. * @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
  18635. * @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
  18636. * @returns an array of {BABYLON.TransformNode}
  18637. */
  18638. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18639. var results = [];
  18640. this._getDescendants(results, directDescendantsOnly, function (node) {
  18641. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18642. });
  18643. return results;
  18644. };
  18645. /**
  18646. * Get all direct children of this node
  18647. * @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
  18648. * @returns an array of {BABYLON.Node}
  18649. */
  18650. Node.prototype.getChildren = function (predicate) {
  18651. return this.getDescendants(true, predicate);
  18652. };
  18653. /** @hidden */
  18654. Node.prototype._setReady = function (state) {
  18655. if (state === this._isReady) {
  18656. return;
  18657. }
  18658. if (!state) {
  18659. this._isReady = false;
  18660. return;
  18661. }
  18662. if (this.onReady) {
  18663. this.onReady(this);
  18664. }
  18665. this._isReady = true;
  18666. };
  18667. /**
  18668. * Get an animation by name
  18669. * @param name defines the name of the animation to look for
  18670. * @returns null if not found else the requested animation
  18671. */
  18672. Node.prototype.getAnimationByName = function (name) {
  18673. for (var i = 0; i < this.animations.length; i++) {
  18674. var animation = this.animations[i];
  18675. if (animation.name === name) {
  18676. return animation;
  18677. }
  18678. }
  18679. return null;
  18680. };
  18681. /**
  18682. * Creates an animation range for this node
  18683. * @param name defines the name of the range
  18684. * @param from defines the starting key
  18685. * @param to defines the end key
  18686. */
  18687. Node.prototype.createAnimationRange = function (name, from, to) {
  18688. // check name not already in use
  18689. if (!this._ranges[name]) {
  18690. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18691. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18692. if (this.animations[i]) {
  18693. this.animations[i].createRange(name, from, to);
  18694. }
  18695. }
  18696. }
  18697. };
  18698. /**
  18699. * Delete a specific animation range
  18700. * @param name defines the name of the range to delete
  18701. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18702. */
  18703. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18704. if (deleteFrames === void 0) { deleteFrames = true; }
  18705. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18706. if (this.animations[i]) {
  18707. this.animations[i].deleteRange(name, deleteFrames);
  18708. }
  18709. }
  18710. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18711. };
  18712. /**
  18713. * Get an animation range by name
  18714. * @param name defines the name of the animation range to look for
  18715. * @returns null if not found else the requested animation range
  18716. */
  18717. Node.prototype.getAnimationRange = function (name) {
  18718. return this._ranges[name];
  18719. };
  18720. /**
  18721. * Will start the animation sequence
  18722. * @param name defines the range frames for animation sequence
  18723. * @param loop defines if the animation should loop (false by default)
  18724. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18725. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18726. * @returns the object created for this animation. If range does not exist, it will return null
  18727. */
  18728. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18729. var range = this.getAnimationRange(name);
  18730. if (!range) {
  18731. return null;
  18732. }
  18733. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18734. };
  18735. /**
  18736. * Serialize animation ranges into a JSON compatible object
  18737. * @returns serialization object
  18738. */
  18739. Node.prototype.serializeAnimationRanges = function () {
  18740. var serializationRanges = [];
  18741. for (var name in this._ranges) {
  18742. var localRange = this._ranges[name];
  18743. if (!localRange) {
  18744. continue;
  18745. }
  18746. var range = {};
  18747. range.name = name;
  18748. range.from = localRange.from;
  18749. range.to = localRange.to;
  18750. serializationRanges.push(range);
  18751. }
  18752. return serializationRanges;
  18753. };
  18754. /**
  18755. * Computes the world matrix of the node
  18756. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18757. * @returns the world matrix
  18758. */
  18759. Node.prototype.computeWorldMatrix = function (force) {
  18760. if (!this._worldMatrix) {
  18761. this._worldMatrix = BABYLON.Matrix.Identity();
  18762. }
  18763. return this._worldMatrix;
  18764. };
  18765. /**
  18766. * Releases resources associated with this node.
  18767. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18768. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18769. */
  18770. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18771. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18772. if (!doNotRecurse) {
  18773. var nodes = this.getDescendants(true);
  18774. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18775. var node = nodes_1[_i];
  18776. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18777. }
  18778. }
  18779. else {
  18780. var transformNodes = this.getChildTransformNodes(true);
  18781. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18782. var transformNode = transformNodes_1[_a];
  18783. transformNode.parent = null;
  18784. transformNode.computeWorldMatrix(true);
  18785. }
  18786. }
  18787. if (!this.parent) {
  18788. this.removeFromSceneRootNodes();
  18789. }
  18790. else {
  18791. this.parent = null;
  18792. }
  18793. // Callback
  18794. this.onDisposeObservable.notifyObservers(this);
  18795. this.onDisposeObservable.clear();
  18796. // Behaviors
  18797. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18798. var behavior = _c[_b];
  18799. behavior.detach();
  18800. }
  18801. this._behaviors = [];
  18802. this._isDisposed = true;
  18803. };
  18804. /**
  18805. * Parse animation range data from a serialization object and store them into a given node
  18806. * @param node defines where to store the animation ranges
  18807. * @param parsedNode defines the serialization object to read data from
  18808. * @param scene defines the hosting scene
  18809. */
  18810. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18811. if (parsedNode.ranges) {
  18812. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18813. var data = parsedNode.ranges[index];
  18814. node.createAnimationRange(data.name, data.from, data.to);
  18815. }
  18816. }
  18817. };
  18818. Node._NodeConstructors = {};
  18819. __decorate([
  18820. BABYLON.serialize()
  18821. ], Node.prototype, "name", void 0);
  18822. __decorate([
  18823. BABYLON.serialize()
  18824. ], Node.prototype, "id", void 0);
  18825. __decorate([
  18826. BABYLON.serialize()
  18827. ], Node.prototype, "uniqueId", void 0);
  18828. __decorate([
  18829. BABYLON.serialize()
  18830. ], Node.prototype, "state", void 0);
  18831. __decorate([
  18832. BABYLON.serialize()
  18833. ], Node.prototype, "metadata", void 0);
  18834. return Node;
  18835. }());
  18836. BABYLON.Node = Node;
  18837. })(BABYLON || (BABYLON = {}));
  18838. //# sourceMappingURL=babylon.node.js.map
  18839. var BABYLON;
  18840. (function (BABYLON) {
  18841. // This matrix is used as a value to reset the bounding box.
  18842. var _identityMatrix = BABYLON.Matrix.Identity();
  18843. /**
  18844. * Class used to store bounding sphere information
  18845. */
  18846. var BoundingSphere = /** @class */ (function () {
  18847. /**
  18848. * Creates a new bounding sphere
  18849. * @param min defines the minimum vector (in local space)
  18850. * @param max defines the maximum vector (in local space)
  18851. */
  18852. function BoundingSphere(min, max) {
  18853. /**
  18854. * Gets the center of the bounding sphere in local space
  18855. */
  18856. this.center = BABYLON.Vector3.Zero();
  18857. /**
  18858. * Gets the center of the bounding sphere in world space
  18859. */
  18860. this.centerWorld = BABYLON.Vector3.Zero();
  18861. /**
  18862. * Gets the minimum vector in local space
  18863. */
  18864. this.minimum = BABYLON.Vector3.Zero();
  18865. /**
  18866. * Gets the maximum vector in local space
  18867. */
  18868. this.maximum = BABYLON.Vector3.Zero();
  18869. this.reConstruct(min, max);
  18870. }
  18871. /**
  18872. * Recreates the entire bounding sphere from scratch
  18873. * @param min defines the new minimum vector (in local space)
  18874. * @param max defines the new maximum vector (in local space)
  18875. */
  18876. BoundingSphere.prototype.reConstruct = function (min, max) {
  18877. this.minimum.copyFrom(min);
  18878. this.maximum.copyFrom(max);
  18879. var distance = BABYLON.Vector3.Distance(min, max);
  18880. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18881. this.radius = distance * 0.5;
  18882. this.centerWorld.set(0, 0, 0);
  18883. this._update(_identityMatrix);
  18884. };
  18885. /**
  18886. * Scale the current bounding sphere by applying a scale factor
  18887. * @param factor defines the scale factor to apply
  18888. * @returns the current bounding box
  18889. */
  18890. BoundingSphere.prototype.scale = function (factor) {
  18891. var newRadius = this.radius * factor;
  18892. var tempRadiusVector = BABYLON.Tmp.Vector3[0].set(newRadius, newRadius, newRadius);
  18893. var min = BABYLON.Tmp.Vector3[1].copyFrom(this.center).subtractInPlace(tempRadiusVector);
  18894. var max = BABYLON.Tmp.Vector3[2].copyFrom(this.center).addInPlace(tempRadiusVector);
  18895. this.reConstruct(min, max);
  18896. return this;
  18897. };
  18898. // Methods
  18899. /** @hidden */
  18900. BoundingSphere.prototype._update = function (world) {
  18901. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18902. var tempVector = BABYLON.Tmp.Vector3[0];
  18903. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, tempVector);
  18904. this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;
  18905. };
  18906. /**
  18907. * Tests if the bounding sphere is intersecting the frustum planes
  18908. * @param frustumPlanes defines the frustum planes to test
  18909. * @returns true if there is an intersection
  18910. */
  18911. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18912. for (var i = 0; i < 6; i++) {
  18913. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18914. return false;
  18915. }
  18916. return true;
  18917. };
  18918. /**
  18919. * Tests if a point is inside the bounding sphere
  18920. * @param point defines the point to test
  18921. * @returns true if the point is inside the bounding sphere
  18922. */
  18923. BoundingSphere.prototype.intersectsPoint = function (point) {
  18924. var x = this.centerWorld.x - point.x;
  18925. var y = this.centerWorld.y - point.y;
  18926. var z = this.centerWorld.z - point.z;
  18927. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18928. if (this.radiusWorld < distance)
  18929. return false;
  18930. return true;
  18931. };
  18932. // Statics
  18933. /**
  18934. * Checks if two sphere intersct
  18935. * @param sphere0 sphere 0
  18936. * @param sphere1 sphere 1
  18937. * @returns true if the speres intersect
  18938. */
  18939. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18940. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18941. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18942. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18943. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18944. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18945. return false;
  18946. return true;
  18947. };
  18948. return BoundingSphere;
  18949. }());
  18950. BABYLON.BoundingSphere = BoundingSphere;
  18951. })(BABYLON || (BABYLON = {}));
  18952. //# sourceMappingURL=babylon.boundingSphere.js.map
  18953. var BABYLON;
  18954. (function (BABYLON) {
  18955. /**
  18956. * Class used to store bounding box information
  18957. */
  18958. var BoundingBox = /** @class */ (function () {
  18959. /**
  18960. * Creates a new bounding box
  18961. * @param min defines the minimum vector (in local space)
  18962. * @param max defines the maximum vector (in local space)
  18963. */
  18964. function BoundingBox(min, max) {
  18965. /**
  18966. * Gets the 8 vectors representing the bounding box in local space
  18967. */
  18968. this.vectors = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18969. /**
  18970. * Gets the center of the bounding box in local space
  18971. */
  18972. this.center = BABYLON.Vector3.Zero();
  18973. /**
  18974. * Gets the center of the bounding box in world space
  18975. */
  18976. this.centerWorld = BABYLON.Vector3.Zero();
  18977. /**
  18978. * Gets the extend size in local space
  18979. */
  18980. this.extendSize = BABYLON.Vector3.Zero();
  18981. /**
  18982. * Gets the extend size in world space
  18983. */
  18984. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18985. /**
  18986. * Gets the OBB (object bounding box) directions
  18987. */
  18988. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18989. /**
  18990. * Gets the 8 vectors representing the bounding box in world space
  18991. */
  18992. this.vectorsWorld = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18993. /**
  18994. * Gets the minimum vector in world space
  18995. */
  18996. this.minimumWorld = BABYLON.Vector3.Zero();
  18997. /**
  18998. * Gets the maximum vector in world space
  18999. */
  19000. this.maximumWorld = BABYLON.Vector3.Zero();
  19001. /**
  19002. * Gets the minimum vector in local space
  19003. */
  19004. this.minimum = BABYLON.Vector3.Zero();
  19005. /**
  19006. * Gets the maximum vector in local space
  19007. */
  19008. this.maximum = BABYLON.Vector3.Zero();
  19009. this.reConstruct(min, max);
  19010. }
  19011. ;
  19012. // Methods
  19013. /**
  19014. * Recreates the entire bounding box from scratch
  19015. * @param min defines the new minimum vector (in local space)
  19016. * @param max defines the new maximum vector (in local space)
  19017. */
  19018. BoundingBox.prototype.reConstruct = function (min, max) {
  19019. this.minimum.copyFrom(min);
  19020. this.maximum.copyFrom(max);
  19021. // Bounding vectors
  19022. this.vectors[0].copyFrom(this.minimum);
  19023. this.vectors[1].copyFrom(this.maximum);
  19024. this.vectors[2].copyFrom(this.minimum);
  19025. this.vectors[3].copyFrom(this.minimum);
  19026. this.vectors[4].copyFrom(this.minimum);
  19027. this.vectors[5].copyFrom(this.maximum);
  19028. this.vectors[6].copyFrom(this.maximum);
  19029. this.vectors[7].copyFrom(this.maximum);
  19030. this.vectors[2].x = this.maximum.x;
  19031. this.vectors[3].y = this.maximum.y;
  19032. this.vectors[4].z = this.maximum.z;
  19033. this.vectors[5].z = this.minimum.z;
  19034. this.vectors[6].x = this.minimum.x;
  19035. this.vectors[7].y = this.minimum.y;
  19036. // OBB
  19037. this.center.copyFrom(this.maximum).addInPlace(this.minimum).scaleInPlace(0.5);
  19038. this.extendSize.copyFrom(this.maximum).subtractInPlace(this.minimum).scaleInPlace(0.5);
  19039. for (var index = 0; index < 3; index++) {
  19040. this.directions[index].copyFromFloats(0, 0, 0);
  19041. }
  19042. // World
  19043. for (var index = 0; index < 8; index++) {
  19044. this.vectorsWorld[index].copyFromFloats(0, 0, 0);
  19045. }
  19046. this.minimumWorld.copyFromFloats(0, 0, 0);
  19047. this.maximumWorld.copyFromFloats(0, 0, 0);
  19048. this.centerWorld.copyFromFloats(0, 0, 0);
  19049. this.extendSizeWorld.copyFromFloats(0, 0, 0);
  19050. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  19051. };
  19052. /**
  19053. * Scale the current bounding box by applying a scale factor
  19054. * @param factor defines the scale factor to apply
  19055. * @returns the current bounding box
  19056. */
  19057. BoundingBox.prototype.scale = function (factor) {
  19058. var diff = BABYLON.Tmp.Vector3[0].copyFrom(this.maximum).subtractInPlace(this.minimum);
  19059. var distance = diff.length() * factor;
  19060. diff.normalize();
  19061. var newRadius = diff.scaleInPlace(distance * 0.5);
  19062. var min = BABYLON.Tmp.Vector3[1].copyFrom(this.center).subtractInPlace(newRadius);
  19063. var max = BABYLON.Tmp.Vector3[2].copyFrom(this.center).addInPlace(newRadius);
  19064. this.reConstruct(min, max);
  19065. return this;
  19066. };
  19067. /**
  19068. * Gets the world matrix of the bounding box
  19069. * @returns a matrix
  19070. */
  19071. BoundingBox.prototype.getWorldMatrix = function () {
  19072. return this._worldMatrix;
  19073. };
  19074. /**
  19075. * Sets the world matrix stored in the bounding box
  19076. * @param matrix defines the matrix to store
  19077. * @returns current bounding box
  19078. */
  19079. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  19080. this._worldMatrix.copyFrom(matrix);
  19081. return this;
  19082. };
  19083. /** @hidden */
  19084. BoundingBox.prototype._update = function (world) {
  19085. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  19086. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  19087. for (var index = 0; index < 8; index++) {
  19088. var v = this.vectorsWorld[index];
  19089. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  19090. this.minimumWorld.minimizeInPlace(v);
  19091. this.maximumWorld.maximizeInPlace(v);
  19092. }
  19093. // Extend
  19094. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  19095. this.extendSizeWorld.scaleInPlace(0.5);
  19096. // OBB
  19097. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  19098. this.centerWorld.scaleInPlace(0.5);
  19099. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  19100. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  19101. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  19102. this._worldMatrix = world;
  19103. };
  19104. /**
  19105. * Tests if the bounding box is intersecting the frustum planes
  19106. * @param frustumPlanes defines the frustum planes to test
  19107. * @returns true if there is an intersection
  19108. */
  19109. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  19110. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  19111. };
  19112. /**
  19113. * Tests if the bounding box is entirely inside the frustum planes
  19114. * @param frustumPlanes defines the frustum planes to test
  19115. * @returns true if there is an inclusion
  19116. */
  19117. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19118. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  19119. };
  19120. /**
  19121. * Tests if a point is inside the bounding box
  19122. * @param point defines the point to test
  19123. * @returns true if the point is inside the bounding box
  19124. */
  19125. BoundingBox.prototype.intersectsPoint = function (point) {
  19126. var delta = -BABYLON.Epsilon;
  19127. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  19128. return false;
  19129. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  19130. return false;
  19131. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  19132. return false;
  19133. return true;
  19134. };
  19135. /**
  19136. * Tests if the bounding box intersects with a bounding sphere
  19137. * @param sphere defines the sphere to test
  19138. * @returns true if there is an intersection
  19139. */
  19140. BoundingBox.prototype.intersectsSphere = function (sphere) {
  19141. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  19142. };
  19143. /**
  19144. * Tests if the bounding box intersects with a box defined by a min and max vectors
  19145. * @param min defines the min vector to use
  19146. * @param max defines the max vector to use
  19147. * @returns true if there is an intersection
  19148. */
  19149. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  19150. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  19151. return false;
  19152. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  19153. return false;
  19154. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  19155. return false;
  19156. return true;
  19157. };
  19158. // Statics
  19159. /**
  19160. * Tests if two bounding boxes are intersections
  19161. * @param box0 defines the first box to test
  19162. * @param box1 defines the second box to test
  19163. * @returns true if there is an intersection
  19164. */
  19165. BoundingBox.Intersects = function (box0, box1) {
  19166. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  19167. return false;
  19168. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  19169. return false;
  19170. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  19171. return false;
  19172. return true;
  19173. };
  19174. /**
  19175. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  19176. * @param minPoint defines the minimum vector of the bounding box
  19177. * @param maxPoint defines the maximum vector of the bounding box
  19178. * @param sphereCenter defines the sphere center
  19179. * @param sphereRadius defines the sphere radius
  19180. * @returns true if there is an intersection
  19181. */
  19182. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  19183. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  19184. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  19185. return (num <= (sphereRadius * sphereRadius));
  19186. };
  19187. /**
  19188. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  19189. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19190. * @param frustumPlanes defines the frustum planes to test
  19191. * @return true if there is an inclusion
  19192. */
  19193. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  19194. for (var p = 0; p < 6; p++) {
  19195. for (var i = 0; i < 8; i++) {
  19196. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19197. return false;
  19198. }
  19199. }
  19200. }
  19201. return true;
  19202. };
  19203. /**
  19204. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  19205. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19206. * @param frustumPlanes defines the frustum planes to test
  19207. * @return true if there is an intersection
  19208. */
  19209. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  19210. for (var p = 0; p < 6; p++) {
  19211. var inCount = 8;
  19212. for (var i = 0; i < 8; i++) {
  19213. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19214. --inCount;
  19215. }
  19216. else {
  19217. break;
  19218. }
  19219. }
  19220. if (inCount === 0)
  19221. return false;
  19222. }
  19223. return true;
  19224. };
  19225. return BoundingBox;
  19226. }());
  19227. BABYLON.BoundingBox = BoundingBox;
  19228. })(BABYLON || (BABYLON = {}));
  19229. //# sourceMappingURL=babylon.boundingBox.js.map
  19230. var BABYLON;
  19231. (function (BABYLON) {
  19232. var computeBoxExtents = function (axis, box) {
  19233. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  19234. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  19235. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  19236. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  19237. var r = r0 + r1 + r2;
  19238. return {
  19239. min: p - r,
  19240. max: p + r
  19241. };
  19242. };
  19243. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  19244. var axisOverlap = function (axis, box0, box1) {
  19245. var result0 = computeBoxExtents(axis, box0);
  19246. var result1 = computeBoxExtents(axis, box1);
  19247. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  19248. };
  19249. /**
  19250. * Info for a bounding data of a mesh
  19251. */
  19252. var BoundingInfo = /** @class */ (function () {
  19253. /**
  19254. * Constructs bounding info
  19255. * @param minimum min vector of the bounding box/sphere
  19256. * @param maximum max vector of the bounding box/sphere
  19257. */
  19258. function BoundingInfo(minimum, maximum) {
  19259. this._isLocked = false;
  19260. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  19261. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  19262. }
  19263. Object.defineProperty(BoundingInfo.prototype, "minimum", {
  19264. /**
  19265. * min vector of the bounding box/sphere
  19266. */
  19267. get: function () {
  19268. return this.boundingBox.minimum;
  19269. },
  19270. enumerable: true,
  19271. configurable: true
  19272. });
  19273. Object.defineProperty(BoundingInfo.prototype, "maximum", {
  19274. /**
  19275. * max vector of the bounding box/sphere
  19276. */
  19277. get: function () {
  19278. return this.boundingBox.maximum;
  19279. },
  19280. enumerable: true,
  19281. configurable: true
  19282. });
  19283. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  19284. /**
  19285. * If the info is locked and won't be updated to avoid perf overhead
  19286. */
  19287. get: function () {
  19288. return this._isLocked;
  19289. },
  19290. set: function (value) {
  19291. this._isLocked = value;
  19292. },
  19293. enumerable: true,
  19294. configurable: true
  19295. });
  19296. // Methods
  19297. /**
  19298. * Updates the boudning sphere and box
  19299. * @param world world matrix to be used to update
  19300. */
  19301. BoundingInfo.prototype.update = function (world) {
  19302. if (this._isLocked) {
  19303. return;
  19304. }
  19305. this.boundingBox._update(world);
  19306. this.boundingSphere._update(world);
  19307. };
  19308. /**
  19309. * Recreate the bounding info to be centered around a specific point given a specific extend.
  19310. * @param center New center of the bounding info
  19311. * @param extend New extend of the bounding info
  19312. * @returns the current bounding info
  19313. */
  19314. BoundingInfo.prototype.centerOn = function (center, extend) {
  19315. var minimum = BABYLON.Tmp.Vector3[0].copyFrom(center).subtractInPlace(extend);
  19316. var maximum = BABYLON.Tmp.Vector3[1].copyFrom(center).addInPlace(extend);
  19317. this.boundingBox.reConstruct(minimum, maximum);
  19318. this.boundingSphere.reConstruct(minimum, maximum);
  19319. return this;
  19320. };
  19321. /**
  19322. * Scale the current bounding info by applying a scale factor
  19323. * @param factor defines the scale factor to apply
  19324. * @returns the current bounding info
  19325. */
  19326. BoundingInfo.prototype.scale = function (factor) {
  19327. this.boundingBox.scale(factor);
  19328. this.boundingSphere.scale(factor);
  19329. return this;
  19330. };
  19331. /**
  19332. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  19333. * @param frustumPlanes defines the frustum to test
  19334. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  19335. * @returns true if the bounding info is in the frustum planes
  19336. */
  19337. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  19338. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  19339. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  19340. return false;
  19341. }
  19342. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  19343. return true;
  19344. }
  19345. return this.boundingBox.isInFrustum(frustumPlanes);
  19346. };
  19347. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  19348. /**
  19349. * Gets the world distance between the min and max points of the bounding box
  19350. */
  19351. get: function () {
  19352. var boundingBox = this.boundingBox;
  19353. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  19354. return size.length();
  19355. },
  19356. enumerable: true,
  19357. configurable: true
  19358. });
  19359. /**
  19360. * Checks if a cullable object (mesh...) is in the camera frustum
  19361. * Unlike isInFrustum this cheks the full bounding box
  19362. * @param frustumPlanes Camera near/planes
  19363. * @returns true if the object is in frustum otherwise false
  19364. */
  19365. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19366. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  19367. };
  19368. /** @hidden */
  19369. BoundingInfo.prototype._checkCollision = function (collider) {
  19370. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  19371. };
  19372. /**
  19373. * Checks if a point is inside the bounding box and bounding sphere or the mesh
  19374. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19375. * @param point the point to check intersection with
  19376. * @returns if the point intersects
  19377. */
  19378. BoundingInfo.prototype.intersectsPoint = function (point) {
  19379. if (!this.boundingSphere.centerWorld) {
  19380. return false;
  19381. }
  19382. if (!this.boundingSphere.intersectsPoint(point)) {
  19383. return false;
  19384. }
  19385. if (!this.boundingBox.intersectsPoint(point)) {
  19386. return false;
  19387. }
  19388. return true;
  19389. };
  19390. /**
  19391. * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
  19392. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19393. * @param boundingInfo the bounding info to check intersection with
  19394. * @param precise if the intersection should be done using OBB
  19395. * @returns if the bounding info intersects
  19396. */
  19397. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  19398. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  19399. return false;
  19400. }
  19401. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  19402. return false;
  19403. }
  19404. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  19405. return false;
  19406. }
  19407. if (!precise) {
  19408. return true;
  19409. }
  19410. var box0 = this.boundingBox;
  19411. var box1 = boundingInfo.boundingBox;
  19412. if (!axisOverlap(box0.directions[0], box0, box1))
  19413. return false;
  19414. if (!axisOverlap(box0.directions[1], box0, box1))
  19415. return false;
  19416. if (!axisOverlap(box0.directions[2], box0, box1))
  19417. return false;
  19418. if (!axisOverlap(box1.directions[0], box0, box1))
  19419. return false;
  19420. if (!axisOverlap(box1.directions[1], box0, box1))
  19421. return false;
  19422. if (!axisOverlap(box1.directions[2], box0, box1))
  19423. return false;
  19424. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  19425. return false;
  19426. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  19427. return false;
  19428. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  19429. return false;
  19430. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  19431. return false;
  19432. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  19433. return false;
  19434. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  19435. return false;
  19436. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  19437. return false;
  19438. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  19439. return false;
  19440. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  19441. return false;
  19442. return true;
  19443. };
  19444. return BoundingInfo;
  19445. }());
  19446. BABYLON.BoundingInfo = BoundingInfo;
  19447. })(BABYLON || (BABYLON = {}));
  19448. //# sourceMappingURL=babylon.boundingInfo.js.map
  19449. var BABYLON;
  19450. (function (BABYLON) {
  19451. var TransformNode = /** @class */ (function (_super) {
  19452. __extends(TransformNode, _super);
  19453. function TransformNode(name, scene, isPure) {
  19454. if (scene === void 0) { scene = null; }
  19455. if (isPure === void 0) { isPure = true; }
  19456. var _this = _super.call(this, name, scene) || this;
  19457. _this._forward = new BABYLON.Vector3(0, 0, 1);
  19458. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  19459. _this._up = new BABYLON.Vector3(0, 1, 0);
  19460. _this._right = new BABYLON.Vector3(1, 0, 0);
  19461. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  19462. // Properties
  19463. _this._position = BABYLON.Vector3.Zero();
  19464. _this._rotation = BABYLON.Vector3.Zero();
  19465. _this._scaling = BABYLON.Vector3.One();
  19466. _this._isDirty = false;
  19467. /**
  19468. * Set the billboard mode. Default is 0.
  19469. *
  19470. * | Value | Type | Description |
  19471. * | --- | --- | --- |
  19472. * | 0 | BILLBOARDMODE_NONE | |
  19473. * | 1 | BILLBOARDMODE_X | |
  19474. * | 2 | BILLBOARDMODE_Y | |
  19475. * | 4 | BILLBOARDMODE_Z | |
  19476. * | 7 | BILLBOARDMODE_ALL | |
  19477. *
  19478. */
  19479. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  19480. _this.scalingDeterminant = 1;
  19481. _this.infiniteDistance = false;
  19482. /**
  19483. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  19484. * By default the system will update normals to compensate
  19485. */
  19486. _this.ignoreNonUniformScaling = false;
  19487. _this._localWorld = BABYLON.Matrix.Zero();
  19488. _this._absolutePosition = BABYLON.Vector3.Zero();
  19489. _this._pivotMatrix = BABYLON.Matrix.Identity();
  19490. _this._postMultiplyPivotMatrix = false;
  19491. _this._isWorldMatrixFrozen = false;
  19492. /**
  19493. * An event triggered after the world matrix is updated
  19494. */
  19495. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  19496. _this._nonUniformScaling = false;
  19497. if (isPure) {
  19498. _this.getScene().addTransformNode(_this);
  19499. }
  19500. return _this;
  19501. }
  19502. /**
  19503. * Gets a string identifying the name of the class
  19504. * @returns "TransformNode" string
  19505. */
  19506. TransformNode.prototype.getClassName = function () {
  19507. return "TransformNode";
  19508. };
  19509. Object.defineProperty(TransformNode.prototype, "position", {
  19510. /**
  19511. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  19512. */
  19513. get: function () {
  19514. return this._position;
  19515. },
  19516. set: function (newPosition) {
  19517. this._position = newPosition;
  19518. this._isDirty = true;
  19519. },
  19520. enumerable: true,
  19521. configurable: true
  19522. });
  19523. Object.defineProperty(TransformNode.prototype, "rotation", {
  19524. /**
  19525. * 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)).
  19526. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  19527. */
  19528. get: function () {
  19529. return this._rotation;
  19530. },
  19531. set: function (newRotation) {
  19532. this._rotation = newRotation;
  19533. this._isDirty = true;
  19534. },
  19535. enumerable: true,
  19536. configurable: true
  19537. });
  19538. Object.defineProperty(TransformNode.prototype, "scaling", {
  19539. /**
  19540. * 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)).
  19541. */
  19542. get: function () {
  19543. return this._scaling;
  19544. },
  19545. set: function (newScaling) {
  19546. this._scaling = newScaling;
  19547. this._isDirty = true;
  19548. },
  19549. enumerable: true,
  19550. configurable: true
  19551. });
  19552. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  19553. /**
  19554. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  19555. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  19556. */
  19557. get: function () {
  19558. return this._rotationQuaternion;
  19559. },
  19560. set: function (quaternion) {
  19561. this._rotationQuaternion = quaternion;
  19562. //reset the rotation vector.
  19563. if (quaternion && this.rotation.length()) {
  19564. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  19565. }
  19566. },
  19567. enumerable: true,
  19568. configurable: true
  19569. });
  19570. Object.defineProperty(TransformNode.prototype, "forward", {
  19571. /**
  19572. * The forward direction of that transform in world space.
  19573. */
  19574. get: function () {
  19575. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  19576. },
  19577. enumerable: true,
  19578. configurable: true
  19579. });
  19580. Object.defineProperty(TransformNode.prototype, "up", {
  19581. /**
  19582. * The up direction of that transform in world space.
  19583. */
  19584. get: function () {
  19585. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  19586. },
  19587. enumerable: true,
  19588. configurable: true
  19589. });
  19590. Object.defineProperty(TransformNode.prototype, "right", {
  19591. /**
  19592. * The right direction of that transform in world space.
  19593. */
  19594. get: function () {
  19595. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  19596. },
  19597. enumerable: true,
  19598. configurable: true
  19599. });
  19600. /**
  19601. * Copies the parameter passed Matrix into the mesh Pose matrix.
  19602. * Returns the TransformNode.
  19603. */
  19604. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  19605. this._poseMatrix.copyFrom(matrix);
  19606. return this;
  19607. };
  19608. /**
  19609. * Returns the mesh Pose matrix.
  19610. * Returned object : Matrix
  19611. */
  19612. TransformNode.prototype.getPoseMatrix = function () {
  19613. return this._poseMatrix;
  19614. };
  19615. /** @hidden */
  19616. TransformNode.prototype._isSynchronized = function () {
  19617. if (this._isDirty) {
  19618. return false;
  19619. }
  19620. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  19621. return false;
  19622. if (this._cache.pivotMatrixUpdated) {
  19623. return false;
  19624. }
  19625. if (this.infiniteDistance) {
  19626. return false;
  19627. }
  19628. if (!this._cache.position.equals(this._position))
  19629. return false;
  19630. if (this._rotationQuaternion) {
  19631. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  19632. return false;
  19633. }
  19634. if (!this._cache.rotation.equals(this._rotation))
  19635. return false;
  19636. if (!this._cache.scaling.equals(this._scaling))
  19637. return false;
  19638. return true;
  19639. };
  19640. /** @hidden */
  19641. TransformNode.prototype._initCache = function () {
  19642. _super.prototype._initCache.call(this);
  19643. this._cache.localMatrixUpdated = false;
  19644. this._cache.position = BABYLON.Vector3.Zero();
  19645. this._cache.scaling = BABYLON.Vector3.Zero();
  19646. this._cache.rotation = BABYLON.Vector3.Zero();
  19647. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  19648. this._cache.billboardMode = -1;
  19649. };
  19650. TransformNode.prototype.markAsDirty = function (property) {
  19651. if (property === "rotation") {
  19652. this.rotationQuaternion = null;
  19653. }
  19654. this._currentRenderId = Number.MAX_VALUE;
  19655. this._isDirty = true;
  19656. return this;
  19657. };
  19658. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  19659. /**
  19660. * Returns the current mesh absolute position.
  19661. * Returns a Vector3.
  19662. */
  19663. get: function () {
  19664. return this._absolutePosition;
  19665. },
  19666. enumerable: true,
  19667. configurable: true
  19668. });
  19669. /**
  19670. * Sets a new matrix to apply before all other transformation
  19671. * @param matrix defines the transform matrix
  19672. * @returns the current TransformNode
  19673. */
  19674. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  19675. return this.setPivotMatrix(matrix, false);
  19676. };
  19677. /**
  19678. * Sets a new pivot matrix to the current node
  19679. * @param matrix defines the new pivot matrix to use
  19680. * @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
  19681. * @returns the current TransformNode
  19682. */
  19683. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  19684. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  19685. this._pivotMatrix = matrix.clone();
  19686. this._cache.pivotMatrixUpdated = true;
  19687. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  19688. if (this._postMultiplyPivotMatrix) {
  19689. if (!this._pivotMatrixInverse) {
  19690. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  19691. }
  19692. else {
  19693. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  19694. }
  19695. }
  19696. return this;
  19697. };
  19698. /**
  19699. * Returns the mesh pivot matrix.
  19700. * Default : Identity.
  19701. * A Matrix is returned.
  19702. */
  19703. TransformNode.prototype.getPivotMatrix = function () {
  19704. return this._pivotMatrix;
  19705. };
  19706. /**
  19707. * Prevents the World matrix to be computed any longer.
  19708. * Returns the TransformNode.
  19709. */
  19710. TransformNode.prototype.freezeWorldMatrix = function () {
  19711. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  19712. this.computeWorldMatrix(true);
  19713. this._isWorldMatrixFrozen = true;
  19714. return this;
  19715. };
  19716. /**
  19717. * Allows back the World matrix computation.
  19718. * Returns the TransformNode.
  19719. */
  19720. TransformNode.prototype.unfreezeWorldMatrix = function () {
  19721. this._isWorldMatrixFrozen = false;
  19722. this.computeWorldMatrix(true);
  19723. return this;
  19724. };
  19725. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19726. /**
  19727. * True if the World matrix has been frozen.
  19728. * Returns a boolean.
  19729. */
  19730. get: function () {
  19731. return this._isWorldMatrixFrozen;
  19732. },
  19733. enumerable: true,
  19734. configurable: true
  19735. });
  19736. /**
  19737. * Retuns the mesh absolute position in the World.
  19738. * Returns a Vector3.
  19739. */
  19740. TransformNode.prototype.getAbsolutePosition = function () {
  19741. this.computeWorldMatrix();
  19742. return this._absolutePosition;
  19743. };
  19744. /**
  19745. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  19746. * Returns the TransformNode.
  19747. */
  19748. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  19749. if (!absolutePosition) {
  19750. return this;
  19751. }
  19752. var absolutePositionX;
  19753. var absolutePositionY;
  19754. var absolutePositionZ;
  19755. if (absolutePosition.x === undefined) {
  19756. if (arguments.length < 3) {
  19757. return this;
  19758. }
  19759. absolutePositionX = arguments[0];
  19760. absolutePositionY = arguments[1];
  19761. absolutePositionZ = arguments[2];
  19762. }
  19763. else {
  19764. absolutePositionX = absolutePosition.x;
  19765. absolutePositionY = absolutePosition.y;
  19766. absolutePositionZ = absolutePosition.z;
  19767. }
  19768. if (this.parent) {
  19769. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19770. invertParentWorldMatrix.invert();
  19771. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  19772. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  19773. }
  19774. else {
  19775. this.position.x = absolutePositionX;
  19776. this.position.y = absolutePositionY;
  19777. this.position.z = absolutePositionZ;
  19778. }
  19779. return this;
  19780. };
  19781. /**
  19782. * Sets the mesh position in its local space.
  19783. * Returns the TransformNode.
  19784. */
  19785. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19786. this.computeWorldMatrix();
  19787. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19788. return this;
  19789. };
  19790. /**
  19791. * Returns the mesh position in the local space from the current World matrix values.
  19792. * Returns a new Vector3.
  19793. */
  19794. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19795. this.computeWorldMatrix();
  19796. var invLocalWorldMatrix = this._localWorld.clone();
  19797. invLocalWorldMatrix.invert();
  19798. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19799. };
  19800. /**
  19801. * Translates the mesh along the passed Vector3 in its local space.
  19802. * Returns the TransformNode.
  19803. */
  19804. TransformNode.prototype.locallyTranslate = function (vector3) {
  19805. this.computeWorldMatrix(true);
  19806. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19807. return this;
  19808. };
  19809. /**
  19810. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19811. * @param targetPoint the position (must be in same space as current mesh) to look at
  19812. * @param yawCor optional yaw (y-axis) correction in radians
  19813. * @param pitchCor optional pitch (x-axis) correction in radians
  19814. * @param rollCor optional roll (z-axis) correction in radians
  19815. * @param space the choosen space of the target
  19816. * @returns the TransformNode.
  19817. */
  19818. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19819. if (yawCor === void 0) { yawCor = 0; }
  19820. if (pitchCor === void 0) { pitchCor = 0; }
  19821. if (rollCor === void 0) { rollCor = 0; }
  19822. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19823. var dv = TransformNode._lookAtVectorCache;
  19824. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19825. targetPoint.subtractToRef(pos, dv);
  19826. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19827. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19828. var pitch = Math.atan2(dv.y, len);
  19829. if (this.rotationQuaternion) {
  19830. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19831. }
  19832. else {
  19833. this.rotation.x = pitch + pitchCor;
  19834. this.rotation.y = yaw + yawCor;
  19835. this.rotation.z = rollCor;
  19836. }
  19837. return this;
  19838. };
  19839. /**
  19840. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19841. * This Vector3 is expressed in the World space.
  19842. */
  19843. TransformNode.prototype.getDirection = function (localAxis) {
  19844. var result = BABYLON.Vector3.Zero();
  19845. this.getDirectionToRef(localAxis, result);
  19846. return result;
  19847. };
  19848. /**
  19849. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19850. * localAxis is expressed in the mesh local space.
  19851. * result is computed in the Wordl space from the mesh World matrix.
  19852. * Returns the TransformNode.
  19853. */
  19854. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19855. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19856. return this;
  19857. };
  19858. /**
  19859. * Sets a new pivot point to the current node
  19860. * @param point defines the new pivot point to use
  19861. * @param space defines if the point is in world or local space (local by default)
  19862. * @returns the current TransformNode
  19863. */
  19864. TransformNode.prototype.setPivotPoint = function (point, space) {
  19865. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19866. if (this.getScene().getRenderId() == 0) {
  19867. this.computeWorldMatrix(true);
  19868. }
  19869. var wm = this.getWorldMatrix();
  19870. if (space == BABYLON.Space.WORLD) {
  19871. var tmat = BABYLON.Tmp.Matrix[0];
  19872. wm.invertToRef(tmat);
  19873. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19874. }
  19875. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19876. };
  19877. /**
  19878. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19879. */
  19880. TransformNode.prototype.getPivotPoint = function () {
  19881. var point = BABYLON.Vector3.Zero();
  19882. this.getPivotPointToRef(point);
  19883. return point;
  19884. };
  19885. /**
  19886. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19887. * Returns the TransformNode.
  19888. */
  19889. TransformNode.prototype.getPivotPointToRef = function (result) {
  19890. result.x = -this._pivotMatrix.m[12];
  19891. result.y = -this._pivotMatrix.m[13];
  19892. result.z = -this._pivotMatrix.m[14];
  19893. return this;
  19894. };
  19895. /**
  19896. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19897. */
  19898. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19899. var point = BABYLON.Vector3.Zero();
  19900. this.getAbsolutePivotPointToRef(point);
  19901. return point;
  19902. };
  19903. /**
  19904. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19905. * Returns the TransformNode.
  19906. */
  19907. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19908. result.x = this._pivotMatrix.m[12];
  19909. result.y = this._pivotMatrix.m[13];
  19910. result.z = this._pivotMatrix.m[14];
  19911. this.getPivotPointToRef(result);
  19912. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19913. return this;
  19914. };
  19915. /**
  19916. * Defines the passed node as the parent of the current node.
  19917. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19918. * Returns the TransformNode.
  19919. */
  19920. TransformNode.prototype.setParent = function (node) {
  19921. if (!node && !this.parent) {
  19922. return this;
  19923. }
  19924. if (!node) {
  19925. var rotation = BABYLON.Tmp.Quaternion[0];
  19926. var position = BABYLON.Tmp.Vector3[0];
  19927. var scale = BABYLON.Tmp.Vector3[1];
  19928. if (this.parent && this.parent.computeWorldMatrix) {
  19929. this.parent.computeWorldMatrix(true);
  19930. }
  19931. this.computeWorldMatrix(true);
  19932. this.getWorldMatrix().decompose(scale, rotation, position);
  19933. if (this.rotationQuaternion) {
  19934. this.rotationQuaternion.copyFrom(rotation);
  19935. }
  19936. else {
  19937. rotation.toEulerAnglesToRef(this.rotation);
  19938. }
  19939. this.scaling.x = scale.x;
  19940. this.scaling.y = scale.y;
  19941. this.scaling.z = scale.z;
  19942. this.position.x = position.x;
  19943. this.position.y = position.y;
  19944. this.position.z = position.z;
  19945. }
  19946. else {
  19947. var rotation = BABYLON.Tmp.Quaternion[0];
  19948. var position = BABYLON.Tmp.Vector3[0];
  19949. var scale = BABYLON.Tmp.Vector3[1];
  19950. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19951. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19952. this.computeWorldMatrix(true);
  19953. node.computeWorldMatrix(true);
  19954. node.getWorldMatrix().invertToRef(invParentMatrix);
  19955. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19956. diffMatrix.decompose(scale, rotation, position);
  19957. if (this.rotationQuaternion) {
  19958. this.rotationQuaternion.copyFrom(rotation);
  19959. }
  19960. else {
  19961. rotation.toEulerAnglesToRef(this.rotation);
  19962. }
  19963. this.position.x = position.x;
  19964. this.position.y = position.y;
  19965. this.position.z = position.z;
  19966. this.scaling.x = scale.x;
  19967. this.scaling.y = scale.y;
  19968. this.scaling.z = scale.z;
  19969. }
  19970. this.parent = node;
  19971. return this;
  19972. };
  19973. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19974. get: function () {
  19975. return this._nonUniformScaling;
  19976. },
  19977. enumerable: true,
  19978. configurable: true
  19979. });
  19980. /** @hidden */
  19981. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19982. if (this._nonUniformScaling === value) {
  19983. return false;
  19984. }
  19985. this._nonUniformScaling = value;
  19986. return true;
  19987. };
  19988. /**
  19989. * Attach the current TransformNode to another TransformNode associated with a bone
  19990. * @param bone Bone affecting the TransformNode
  19991. * @param affectedTransformNode TransformNode associated with the bone
  19992. */
  19993. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19994. this._transformToBoneReferal = affectedTransformNode;
  19995. this.parent = bone;
  19996. if (bone.getWorldMatrix().determinant() < 0) {
  19997. this.scalingDeterminant *= -1;
  19998. }
  19999. return this;
  20000. };
  20001. TransformNode.prototype.detachFromBone = function () {
  20002. if (!this.parent) {
  20003. return this;
  20004. }
  20005. if (this.parent.getWorldMatrix().determinant() < 0) {
  20006. this.scalingDeterminant *= -1;
  20007. }
  20008. this._transformToBoneReferal = null;
  20009. this.parent = null;
  20010. return this;
  20011. };
  20012. /**
  20013. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  20014. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20015. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20016. * The passed axis is also normalized.
  20017. * Returns the TransformNode.
  20018. */
  20019. TransformNode.prototype.rotate = function (axis, amount, space) {
  20020. axis.normalize();
  20021. if (!this.rotationQuaternion) {
  20022. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20023. this.rotation = BABYLON.Vector3.Zero();
  20024. }
  20025. var rotationQuaternion;
  20026. if (!space || space === BABYLON.Space.LOCAL) {
  20027. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20028. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  20029. }
  20030. else {
  20031. if (this.parent) {
  20032. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  20033. invertParentWorldMatrix.invert();
  20034. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  20035. }
  20036. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20037. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20038. }
  20039. return this;
  20040. };
  20041. /**
  20042. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  20043. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20044. * The passed axis is also normalized.
  20045. * Returns the TransformNode.
  20046. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  20047. */
  20048. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  20049. axis.normalize();
  20050. if (!this.rotationQuaternion) {
  20051. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20052. this.rotation.copyFromFloats(0, 0, 0);
  20053. }
  20054. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  20055. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  20056. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  20057. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  20058. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  20059. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  20060. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  20061. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  20062. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20063. return this;
  20064. };
  20065. /**
  20066. * Translates the mesh along the axis vector for the passed distance in the given space.
  20067. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20068. * Returns the TransformNode.
  20069. */
  20070. TransformNode.prototype.translate = function (axis, distance, space) {
  20071. var displacementVector = axis.scale(distance);
  20072. if (!space || space === BABYLON.Space.LOCAL) {
  20073. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  20074. this.setPositionWithLocalVector(tempV3);
  20075. }
  20076. else {
  20077. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  20078. }
  20079. return this;
  20080. };
  20081. /**
  20082. * Adds a rotation step to the mesh current rotation.
  20083. * x, y, z are Euler angles expressed in radians.
  20084. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  20085. * This means this rotation is made in the mesh local space only.
  20086. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  20087. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  20088. * ```javascript
  20089. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  20090. * ```
  20091. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  20092. * 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.
  20093. * Returns the TransformNode.
  20094. */
  20095. TransformNode.prototype.addRotation = function (x, y, z) {
  20096. var rotationQuaternion;
  20097. if (this.rotationQuaternion) {
  20098. rotationQuaternion = this.rotationQuaternion;
  20099. }
  20100. else {
  20101. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  20102. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  20103. }
  20104. var accumulation = BABYLON.Tmp.Quaternion[0];
  20105. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  20106. rotationQuaternion.multiplyInPlace(accumulation);
  20107. if (!this.rotationQuaternion) {
  20108. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  20109. }
  20110. return this;
  20111. };
  20112. /**
  20113. * Computes the world matrix of the node
  20114. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  20115. * @returns the world matrix
  20116. */
  20117. TransformNode.prototype.computeWorldMatrix = function (force) {
  20118. if (this._isWorldMatrixFrozen) {
  20119. return this._worldMatrix;
  20120. }
  20121. if (!force && this.isSynchronized()) {
  20122. this._currentRenderId = this.getScene().getRenderId();
  20123. return this._worldMatrix;
  20124. }
  20125. this._updateCache();
  20126. this._cache.position.copyFrom(this.position);
  20127. this._cache.scaling.copyFrom(this.scaling);
  20128. this._cache.pivotMatrixUpdated = false;
  20129. this._cache.billboardMode = this.billboardMode;
  20130. this._currentRenderId = this.getScene().getRenderId();
  20131. this._childRenderId = this.getScene().getRenderId();
  20132. this._isDirty = false;
  20133. // Scaling
  20134. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  20135. // Rotation
  20136. //rotate, if quaternion is set and rotation was used
  20137. if (this.rotationQuaternion) {
  20138. var len = this.rotation.length();
  20139. if (len) {
  20140. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  20141. this.rotation.copyFromFloats(0, 0, 0);
  20142. }
  20143. }
  20144. if (this.rotationQuaternion) {
  20145. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  20146. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  20147. }
  20148. else {
  20149. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  20150. this._cache.rotation.copyFrom(this.rotation);
  20151. }
  20152. // Translation
  20153. var camera = this.getScene().activeCamera;
  20154. if (this.infiniteDistance && !this.parent && camera) {
  20155. var cameraWorldMatrix = camera.getWorldMatrix();
  20156. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  20157. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  20158. }
  20159. else {
  20160. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  20161. }
  20162. // Composing transformations
  20163. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  20164. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20165. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  20166. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  20167. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  20168. // Need to decompose each rotation here
  20169. var currentPosition = BABYLON.Tmp.Vector3[3];
  20170. if (this.parent && this.parent.getWorldMatrix) {
  20171. if (this._transformToBoneReferal) {
  20172. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20173. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  20174. }
  20175. else {
  20176. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  20177. }
  20178. }
  20179. else {
  20180. currentPosition.copyFrom(this.position);
  20181. }
  20182. currentPosition.subtractInPlace(camera.globalPosition);
  20183. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  20184. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  20185. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  20186. }
  20187. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  20188. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  20189. }
  20190. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  20191. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  20192. }
  20193. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  20194. }
  20195. else {
  20196. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  20197. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  20198. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  20199. }
  20200. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  20201. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20202. }
  20203. // Post multiply inverse of pivotMatrix
  20204. if (this._postMultiplyPivotMatrix) {
  20205. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  20206. }
  20207. // Local world
  20208. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  20209. // Parent
  20210. if (this.parent && this.parent.getWorldMatrix) {
  20211. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20212. if (this._transformToBoneReferal) {
  20213. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20214. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  20215. }
  20216. else {
  20217. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  20218. }
  20219. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  20220. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  20221. this._worldMatrix.copyFrom(this._localWorld);
  20222. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  20223. }
  20224. else {
  20225. if (this._transformToBoneReferal) {
  20226. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20227. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  20228. }
  20229. else {
  20230. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  20231. }
  20232. }
  20233. this._markSyncedWithParent();
  20234. }
  20235. else {
  20236. this._worldMatrix.copyFrom(this._localWorld);
  20237. }
  20238. // Normal matrix
  20239. if (!this.ignoreNonUniformScaling) {
  20240. if (this.scaling.isNonUniform) {
  20241. this._updateNonUniformScalingState(true);
  20242. }
  20243. else if (this.parent && this.parent._nonUniformScaling) {
  20244. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  20245. }
  20246. else {
  20247. this._updateNonUniformScalingState(false);
  20248. }
  20249. }
  20250. else {
  20251. this._updateNonUniformScalingState(false);
  20252. }
  20253. this._afterComputeWorldMatrix();
  20254. // Absolute position
  20255. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  20256. // Callbacks
  20257. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  20258. if (!this._poseMatrix) {
  20259. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  20260. }
  20261. // Cache the determinant
  20262. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  20263. return this._worldMatrix;
  20264. };
  20265. TransformNode.prototype._afterComputeWorldMatrix = function () {
  20266. };
  20267. /**
  20268. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  20269. * @param func: callback function to add
  20270. *
  20271. * Returns the TransformNode.
  20272. */
  20273. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  20274. this.onAfterWorldMatrixUpdateObservable.add(func);
  20275. return this;
  20276. };
  20277. /**
  20278. * Removes a registered callback function.
  20279. * Returns the TransformNode.
  20280. */
  20281. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  20282. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  20283. return this;
  20284. };
  20285. /**
  20286. * Clone the current transform node
  20287. * Returns the new transform node
  20288. * @param name Name of the new clone
  20289. * @param newParent New parent for the clone
  20290. * @param doNotCloneChildren Do not clone children hierarchy
  20291. */
  20292. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20293. var _this = this;
  20294. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  20295. result.name = name;
  20296. result.id = name;
  20297. if (newParent) {
  20298. result.parent = newParent;
  20299. }
  20300. if (!doNotCloneChildren) {
  20301. // Children
  20302. var directDescendants = this.getDescendants(true);
  20303. for (var index = 0; index < directDescendants.length; index++) {
  20304. var child = directDescendants[index];
  20305. if (child.clone) {
  20306. child.clone(name + "." + child.name, result);
  20307. }
  20308. }
  20309. }
  20310. return result;
  20311. };
  20312. TransformNode.prototype.serialize = function (currentSerializationObject) {
  20313. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  20314. serializationObject.type = this.getClassName();
  20315. // Parent
  20316. if (this.parent) {
  20317. serializationObject.parentId = this.parent.id;
  20318. }
  20319. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  20320. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20321. }
  20322. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20323. serializationObject.isEnabled = this.isEnabled();
  20324. // Parent
  20325. if (this.parent) {
  20326. serializationObject.parentId = this.parent.id;
  20327. }
  20328. return serializationObject;
  20329. };
  20330. // Statics
  20331. /**
  20332. * Returns a new TransformNode object parsed from the source provided.
  20333. * The parameter `parsedMesh` is the source.
  20334. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20335. */
  20336. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  20337. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  20338. if (BABYLON.Tags) {
  20339. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  20340. }
  20341. if (parsedTransformNode.localMatrix) {
  20342. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  20343. }
  20344. else if (parsedTransformNode.pivotMatrix) {
  20345. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  20346. }
  20347. transformNode.setEnabled(parsedTransformNode.isEnabled);
  20348. // Parent
  20349. if (parsedTransformNode.parentId) {
  20350. transformNode._waitingParentId = parsedTransformNode.parentId;
  20351. }
  20352. return transformNode;
  20353. };
  20354. /**
  20355. * Releases resources associated with this transform node.
  20356. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20357. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20358. */
  20359. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20360. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20361. // Animations
  20362. this.getScene().stopAnimation(this);
  20363. // Remove from scene
  20364. this.getScene().removeTransformNode(this);
  20365. this.onAfterWorldMatrixUpdateObservable.clear();
  20366. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20367. };
  20368. // Statics
  20369. TransformNode.BILLBOARDMODE_NONE = 0;
  20370. TransformNode.BILLBOARDMODE_X = 1;
  20371. TransformNode.BILLBOARDMODE_Y = 2;
  20372. TransformNode.BILLBOARDMODE_Z = 4;
  20373. TransformNode.BILLBOARDMODE_ALL = 7;
  20374. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  20375. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  20376. __decorate([
  20377. BABYLON.serializeAsVector3("position")
  20378. ], TransformNode.prototype, "_position", void 0);
  20379. __decorate([
  20380. BABYLON.serializeAsVector3("rotation")
  20381. ], TransformNode.prototype, "_rotation", void 0);
  20382. __decorate([
  20383. BABYLON.serializeAsQuaternion("rotationQuaternion")
  20384. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  20385. __decorate([
  20386. BABYLON.serializeAsVector3("scaling")
  20387. ], TransformNode.prototype, "_scaling", void 0);
  20388. __decorate([
  20389. BABYLON.serialize()
  20390. ], TransformNode.prototype, "billboardMode", void 0);
  20391. __decorate([
  20392. BABYLON.serialize()
  20393. ], TransformNode.prototype, "scalingDeterminant", void 0);
  20394. __decorate([
  20395. BABYLON.serialize()
  20396. ], TransformNode.prototype, "infiniteDistance", void 0);
  20397. __decorate([
  20398. BABYLON.serialize()
  20399. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  20400. return TransformNode;
  20401. }(BABYLON.Node));
  20402. BABYLON.TransformNode = TransformNode;
  20403. })(BABYLON || (BABYLON = {}));
  20404. //# sourceMappingURL=babylon.transformNode.js.map
  20405. var BABYLON;
  20406. (function (BABYLON) {
  20407. /** @hidden */
  20408. var _FacetDataStorage = /** @class */ (function () {
  20409. function _FacetDataStorage() {
  20410. this.facetNb = 0; // facet number
  20411. this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  20412. this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  20413. this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  20414. this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  20415. this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  20416. this.subDiv = {
  20417. max: 1,
  20418. X: 1,
  20419. Y: 1,
  20420. Z: 1
  20421. };
  20422. this.facetDepthSort = false; // is the facet depth sort to be computed
  20423. this.facetDepthSortEnabled = false; // is the facet depth sort initialized
  20424. }
  20425. return _FacetDataStorage;
  20426. }());
  20427. /**
  20428. * Class used to store all common mesh properties
  20429. */
  20430. var AbstractMesh = /** @class */ (function (_super) {
  20431. __extends(AbstractMesh, _super);
  20432. // Constructor
  20433. /**
  20434. * Creates a new AbstractMesh
  20435. * @param name defines the name of the mesh
  20436. * @param scene defines the hosting scene
  20437. */
  20438. function AbstractMesh(name, scene) {
  20439. if (scene === void 0) { scene = null; }
  20440. var _this = _super.call(this, name, scene, false) || this;
  20441. _this._facetData = new _FacetDataStorage();
  20442. /** Gets ot sets the culling strategy to use to find visible meshes */
  20443. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  20444. // Events
  20445. /**
  20446. * An event triggered when this mesh collides with another one
  20447. */
  20448. _this.onCollideObservable = new BABYLON.Observable();
  20449. /**
  20450. * An event triggered when the collision's position changes
  20451. */
  20452. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  20453. /**
  20454. * An event triggered when material is changed
  20455. */
  20456. _this.onMaterialChangedObservable = new BABYLON.Observable();
  20457. // Properties
  20458. /**
  20459. * Gets or sets the orientation for POV movement & rotation
  20460. */
  20461. _this.definedFacingForward = true;
  20462. _this._visibility = 1.0;
  20463. /** Gets or sets the alpha index used to sort transparent meshes
  20464. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  20465. */
  20466. _this.alphaIndex = Number.MAX_VALUE;
  20467. /**
  20468. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  20469. */
  20470. _this.isVisible = true;
  20471. /**
  20472. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  20473. */
  20474. _this.isPickable = true;
  20475. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  20476. _this.showSubMeshesBoundingBox = false;
  20477. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  20478. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  20479. */
  20480. _this.isBlocker = false;
  20481. /**
  20482. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  20483. */
  20484. _this.enablePointerMoveEvents = false;
  20485. /**
  20486. * Specifies the rendering group id for this mesh (0 by default)
  20487. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  20488. */
  20489. _this.renderingGroupId = 0;
  20490. _this._receiveShadows = false;
  20491. /** Defines color to use when rendering outline */
  20492. _this.outlineColor = BABYLON.Color3.Red();
  20493. /** Define width to use when rendering outline */
  20494. _this.outlineWidth = 0.02;
  20495. /** Defines color to use when rendering overlay */
  20496. _this.overlayColor = BABYLON.Color3.Red();
  20497. /** Defines alpha to use when rendering overlay */
  20498. _this.overlayAlpha = 0.5;
  20499. _this._hasVertexAlpha = false;
  20500. _this._useVertexColors = true;
  20501. _this._computeBonesUsingShaders = true;
  20502. _this._numBoneInfluencers = 4;
  20503. _this._applyFog = true;
  20504. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  20505. _this.useOctreeForRenderingSelection = true;
  20506. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  20507. _this.useOctreeForPicking = true;
  20508. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  20509. _this.useOctreeForCollisions = true;
  20510. _this._layerMask = 0x0FFFFFFF;
  20511. /**
  20512. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  20513. */
  20514. _this.alwaysSelectAsActiveMesh = false;
  20515. /**
  20516. * Gets or sets the current action manager
  20517. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  20518. */
  20519. _this.actionManager = null;
  20520. // Collisions
  20521. _this._checkCollisions = false;
  20522. _this._collisionMask = -1;
  20523. _this._collisionGroup = -1;
  20524. /**
  20525. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  20526. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20527. */
  20528. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  20529. /**
  20530. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  20531. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20532. */
  20533. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  20534. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20535. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20536. // Edges
  20537. /**
  20538. * Defines edge width used when edgesRenderer is enabled
  20539. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20540. */
  20541. _this.edgesWidth = 1;
  20542. /**
  20543. * Defines edge color used when edgesRenderer is enabled
  20544. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20545. */
  20546. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  20547. /** @hidden */
  20548. _this._renderId = 0;
  20549. /** @hidden */
  20550. _this._intersectionsInProgress = new Array();
  20551. /** @hidden */
  20552. _this._unIndexed = false;
  20553. /** @hidden */
  20554. _this._lightSources = new Array();
  20555. /**
  20556. * An event triggered when the mesh is rebuilt.
  20557. */
  20558. _this.onRebuildObservable = new BABYLON.Observable();
  20559. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  20560. if (collidedMesh === void 0) { collidedMesh = null; }
  20561. //TODO move this to the collision coordinator!
  20562. if (_this.getScene().workerCollisions)
  20563. newPosition.multiplyInPlace(_this._collider._radius);
  20564. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  20565. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  20566. _this.position.addInPlace(_this._diffPositionForCollisions);
  20567. }
  20568. if (collidedMesh) {
  20569. _this.onCollideObservable.notifyObservers(collidedMesh);
  20570. }
  20571. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  20572. };
  20573. _this.getScene().addMesh(_this);
  20574. _this._resyncLightSources();
  20575. return _this;
  20576. }
  20577. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  20578. /**
  20579. * No billboard
  20580. */
  20581. get: function () {
  20582. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  20583. },
  20584. enumerable: true,
  20585. configurable: true
  20586. });
  20587. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  20588. /** Billboard on X axis */
  20589. get: function () {
  20590. return BABYLON.TransformNode.BILLBOARDMODE_X;
  20591. },
  20592. enumerable: true,
  20593. configurable: true
  20594. });
  20595. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  20596. /** Billboard on Y axis */
  20597. get: function () {
  20598. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  20599. },
  20600. enumerable: true,
  20601. configurable: true
  20602. });
  20603. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  20604. /** Billboard on Z axis */
  20605. get: function () {
  20606. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  20607. },
  20608. enumerable: true,
  20609. configurable: true
  20610. });
  20611. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  20612. /** Billboard on all axes */
  20613. get: function () {
  20614. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  20615. },
  20616. enumerable: true,
  20617. configurable: true
  20618. });
  20619. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  20620. /**
  20621. * Gets the number of facets in the mesh
  20622. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20623. */
  20624. get: function () {
  20625. return this._facetData.facetNb;
  20626. },
  20627. enumerable: true,
  20628. configurable: true
  20629. });
  20630. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  20631. /**
  20632. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  20633. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20634. */
  20635. get: function () {
  20636. return this._facetData.partitioningSubdivisions;
  20637. },
  20638. set: function (nb) {
  20639. this._facetData.partitioningSubdivisions = nb;
  20640. },
  20641. enumerable: true,
  20642. configurable: true
  20643. });
  20644. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  20645. /**
  20646. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  20647. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  20648. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20649. */
  20650. get: function () {
  20651. return this._facetData.partitioningBBoxRatio;
  20652. },
  20653. set: function (ratio) {
  20654. this._facetData.partitioningBBoxRatio = ratio;
  20655. },
  20656. enumerable: true,
  20657. configurable: true
  20658. });
  20659. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  20660. /**
  20661. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  20662. * Works only for updatable meshes.
  20663. * Doesn't work with multi-materials
  20664. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20665. */
  20666. get: function () {
  20667. return this._facetData.facetDepthSort;
  20668. },
  20669. set: function (sort) {
  20670. this._facetData.facetDepthSort = sort;
  20671. },
  20672. enumerable: true,
  20673. configurable: true
  20674. });
  20675. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  20676. /**
  20677. * The location (Vector3) where the facet depth sort must be computed from.
  20678. * By default, the active camera position.
  20679. * Used only when facet depth sort is enabled
  20680. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20681. */
  20682. get: function () {
  20683. return this._facetData.facetDepthSortFrom;
  20684. },
  20685. set: function (location) {
  20686. this._facetData.facetDepthSortFrom = location;
  20687. },
  20688. enumerable: true,
  20689. configurable: true
  20690. });
  20691. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  20692. /**
  20693. * gets a boolean indicating if facetData is enabled
  20694. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20695. */
  20696. get: function () {
  20697. return this._facetData.facetDataEnabled;
  20698. },
  20699. enumerable: true,
  20700. configurable: true
  20701. });
  20702. /** @hidden */
  20703. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  20704. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  20705. return false;
  20706. }
  20707. this._markSubMeshesAsMiscDirty();
  20708. return true;
  20709. };
  20710. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  20711. /** Set a function to call when this mesh collides with another one */
  20712. set: function (callback) {
  20713. if (this._onCollideObserver) {
  20714. this.onCollideObservable.remove(this._onCollideObserver);
  20715. }
  20716. this._onCollideObserver = this.onCollideObservable.add(callback);
  20717. },
  20718. enumerable: true,
  20719. configurable: true
  20720. });
  20721. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  20722. /** Set a function to call when the collision's position changes */
  20723. set: function (callback) {
  20724. if (this._onCollisionPositionChangeObserver) {
  20725. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  20726. }
  20727. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  20728. },
  20729. enumerable: true,
  20730. configurable: true
  20731. });
  20732. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20733. /**
  20734. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20735. */
  20736. get: function () {
  20737. return this._visibility;
  20738. },
  20739. /**
  20740. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20741. */
  20742. set: function (value) {
  20743. if (this._visibility === value) {
  20744. return;
  20745. }
  20746. this._visibility = value;
  20747. this._markSubMeshesAsMiscDirty();
  20748. },
  20749. enumerable: true,
  20750. configurable: true
  20751. });
  20752. Object.defineProperty(AbstractMesh.prototype, "material", {
  20753. /** Gets or sets current material */
  20754. get: function () {
  20755. return this._material;
  20756. },
  20757. set: function (value) {
  20758. if (this._material === value) {
  20759. return;
  20760. }
  20761. this._material = value;
  20762. if (this.onMaterialChangedObservable.hasObservers) {
  20763. this.onMaterialChangedObservable.notifyObservers(this);
  20764. }
  20765. if (!this.subMeshes) {
  20766. return;
  20767. }
  20768. this._unBindEffect();
  20769. },
  20770. enumerable: true,
  20771. configurable: true
  20772. });
  20773. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20774. /**
  20775. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20776. * @see http://doc.babylonjs.com/babylon101/shadows
  20777. */
  20778. get: function () {
  20779. return this._receiveShadows;
  20780. },
  20781. set: function (value) {
  20782. if (this._receiveShadows === value) {
  20783. return;
  20784. }
  20785. this._receiveShadows = value;
  20786. this._markSubMeshesAsLightDirty();
  20787. },
  20788. enumerable: true,
  20789. configurable: true
  20790. });
  20791. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20792. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20793. get: function () {
  20794. return this._hasVertexAlpha;
  20795. },
  20796. set: function (value) {
  20797. if (this._hasVertexAlpha === value) {
  20798. return;
  20799. }
  20800. this._hasVertexAlpha = value;
  20801. this._markSubMeshesAsAttributesDirty();
  20802. this._markSubMeshesAsMiscDirty();
  20803. },
  20804. enumerable: true,
  20805. configurable: true
  20806. });
  20807. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20808. /** 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) */
  20809. get: function () {
  20810. return this._useVertexColors;
  20811. },
  20812. set: function (value) {
  20813. if (this._useVertexColors === value) {
  20814. return;
  20815. }
  20816. this._useVertexColors = value;
  20817. this._markSubMeshesAsAttributesDirty();
  20818. },
  20819. enumerable: true,
  20820. configurable: true
  20821. });
  20822. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20823. /**
  20824. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20825. */
  20826. get: function () {
  20827. return this._computeBonesUsingShaders;
  20828. },
  20829. set: function (value) {
  20830. if (this._computeBonesUsingShaders === value) {
  20831. return;
  20832. }
  20833. this._computeBonesUsingShaders = value;
  20834. this._markSubMeshesAsAttributesDirty();
  20835. },
  20836. enumerable: true,
  20837. configurable: true
  20838. });
  20839. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20840. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20841. get: function () {
  20842. return this._numBoneInfluencers;
  20843. },
  20844. set: function (value) {
  20845. if (this._numBoneInfluencers === value) {
  20846. return;
  20847. }
  20848. this._numBoneInfluencers = value;
  20849. this._markSubMeshesAsAttributesDirty();
  20850. },
  20851. enumerable: true,
  20852. configurable: true
  20853. });
  20854. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20855. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20856. get: function () {
  20857. return this._applyFog;
  20858. },
  20859. set: function (value) {
  20860. if (this._applyFog === value) {
  20861. return;
  20862. }
  20863. this._applyFog = value;
  20864. this._markSubMeshesAsMiscDirty();
  20865. },
  20866. enumerable: true,
  20867. configurable: true
  20868. });
  20869. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20870. /**
  20871. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20872. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20873. */
  20874. get: function () {
  20875. return this._layerMask;
  20876. },
  20877. set: function (value) {
  20878. if (value === this._layerMask) {
  20879. return;
  20880. }
  20881. this._layerMask = value;
  20882. this._resyncLightSources();
  20883. },
  20884. enumerable: true,
  20885. configurable: true
  20886. });
  20887. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20888. /**
  20889. * Gets or sets a collision mask used to mask collisions (default is -1).
  20890. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20891. */
  20892. get: function () {
  20893. return this._collisionMask;
  20894. },
  20895. set: function (mask) {
  20896. this._collisionMask = !isNaN(mask) ? mask : -1;
  20897. },
  20898. enumerable: true,
  20899. configurable: true
  20900. });
  20901. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20902. /**
  20903. * Gets or sets the current collision group mask (-1 by default).
  20904. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20905. */
  20906. get: function () {
  20907. return this._collisionGroup;
  20908. },
  20909. set: function (mask) {
  20910. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20911. },
  20912. enumerable: true,
  20913. configurable: true
  20914. });
  20915. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20916. /** @hidden */
  20917. get: function () {
  20918. return null;
  20919. },
  20920. enumerable: true,
  20921. configurable: true
  20922. });
  20923. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20924. get: function () {
  20925. return this._skeleton;
  20926. },
  20927. /**
  20928. * Gets or sets a skeleton to apply skining transformations
  20929. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20930. */
  20931. set: function (value) {
  20932. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20933. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20934. }
  20935. if (value && value.needInitialSkinMatrix) {
  20936. value._registerMeshWithPoseMatrix(this);
  20937. }
  20938. this._skeleton = value;
  20939. if (!this._skeleton) {
  20940. this._bonesTransformMatrices = null;
  20941. }
  20942. this._markSubMeshesAsAttributesDirty();
  20943. },
  20944. enumerable: true,
  20945. configurable: true
  20946. });
  20947. /**
  20948. * Returns the string "AbstractMesh"
  20949. * @returns "AbstractMesh"
  20950. */
  20951. AbstractMesh.prototype.getClassName = function () {
  20952. return "AbstractMesh";
  20953. };
  20954. /**
  20955. * Gets a string representation of the current mesh
  20956. * @param fullDetails defines a boolean indicating if full details must be included
  20957. * @returns a string representation of the current mesh
  20958. */
  20959. AbstractMesh.prototype.toString = function (fullDetails) {
  20960. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20961. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20962. if (this._skeleton) {
  20963. ret += ", skeleton: " + this._skeleton.name;
  20964. }
  20965. if (fullDetails) {
  20966. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20967. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20968. }
  20969. return ret;
  20970. };
  20971. /** @hidden */
  20972. AbstractMesh.prototype._rebuild = function () {
  20973. this.onRebuildObservable.notifyObservers(this);
  20974. if (this._occlusionQuery) {
  20975. this._occlusionQuery = null;
  20976. }
  20977. if (!this.subMeshes) {
  20978. return;
  20979. }
  20980. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20981. var subMesh = _a[_i];
  20982. subMesh._rebuild();
  20983. }
  20984. };
  20985. /** @hidden */
  20986. AbstractMesh.prototype._resyncLightSources = function () {
  20987. this._lightSources.length = 0;
  20988. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20989. var light = _a[_i];
  20990. if (!light.isEnabled()) {
  20991. continue;
  20992. }
  20993. if (light.canAffectMesh(this)) {
  20994. this._lightSources.push(light);
  20995. }
  20996. }
  20997. this._markSubMeshesAsLightDirty();
  20998. };
  20999. /** @hidden */
  21000. AbstractMesh.prototype._resyncLighSource = function (light) {
  21001. var isIn = light.isEnabled() && light.canAffectMesh(this);
  21002. var index = this._lightSources.indexOf(light);
  21003. if (index === -1) {
  21004. if (!isIn) {
  21005. return;
  21006. }
  21007. this._lightSources.push(light);
  21008. }
  21009. else {
  21010. if (isIn) {
  21011. return;
  21012. }
  21013. this._lightSources.splice(index, 1);
  21014. }
  21015. this._markSubMeshesAsLightDirty();
  21016. };
  21017. /** @hidden */
  21018. AbstractMesh.prototype._unBindEffect = function () {
  21019. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21020. var subMesh = _a[_i];
  21021. subMesh.setEffect(null);
  21022. }
  21023. };
  21024. /** @hidden */
  21025. AbstractMesh.prototype._removeLightSource = function (light) {
  21026. var index = this._lightSources.indexOf(light);
  21027. if (index === -1) {
  21028. return;
  21029. }
  21030. this._lightSources.splice(index, 1);
  21031. this._markSubMeshesAsLightDirty();
  21032. };
  21033. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  21034. if (!this.subMeshes) {
  21035. return;
  21036. }
  21037. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21038. var subMesh = _a[_i];
  21039. if (subMesh._materialDefines) {
  21040. func(subMesh._materialDefines);
  21041. }
  21042. }
  21043. };
  21044. /** @hidden */
  21045. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  21046. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  21047. };
  21048. /** @hidden */
  21049. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  21050. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  21051. };
  21052. /** @hidden */
  21053. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  21054. if (!this.subMeshes) {
  21055. return;
  21056. }
  21057. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21058. var subMesh = _a[_i];
  21059. var material = subMesh.getMaterial();
  21060. if (material) {
  21061. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  21062. }
  21063. }
  21064. };
  21065. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  21066. /**
  21067. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  21068. */
  21069. get: function () {
  21070. return this._scaling;
  21071. },
  21072. set: function (newScaling) {
  21073. this._scaling = newScaling;
  21074. if (this.physicsImpostor) {
  21075. this.physicsImpostor.forceUpdate();
  21076. }
  21077. },
  21078. enumerable: true,
  21079. configurable: true
  21080. });
  21081. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  21082. // Methods
  21083. /**
  21084. * Returns true if the mesh is blocked. Implemented by child classes
  21085. */
  21086. get: function () {
  21087. return false;
  21088. },
  21089. enumerable: true,
  21090. configurable: true
  21091. });
  21092. /**
  21093. * Returns the mesh itself by default. Implemented by child classes
  21094. * @param camera defines the camera to use to pick the right LOD level
  21095. * @returns the currentAbstractMesh
  21096. */
  21097. AbstractMesh.prototype.getLOD = function (camera) {
  21098. return this;
  21099. };
  21100. /**
  21101. * Returns 0 by default. Implemented by child classes
  21102. * @returns an integer
  21103. */
  21104. AbstractMesh.prototype.getTotalVertices = function () {
  21105. return 0;
  21106. };
  21107. /**
  21108. * Returns null by default. Implemented by child classes
  21109. * @returns null
  21110. */
  21111. AbstractMesh.prototype.getIndices = function () {
  21112. return null;
  21113. };
  21114. /**
  21115. * Returns the array of the requested vertex data kind. Implemented by child classes
  21116. * @param kind defines the vertex data kind to use
  21117. * @returns null
  21118. */
  21119. AbstractMesh.prototype.getVerticesData = function (kind) {
  21120. return null;
  21121. };
  21122. /**
  21123. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21124. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21125. * Note that a new underlying VertexBuffer object is created each call.
  21126. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21127. * @param kind defines vertex data kind:
  21128. * * BABYLON.VertexBuffer.PositionKind
  21129. * * BABYLON.VertexBuffer.UVKind
  21130. * * BABYLON.VertexBuffer.UV2Kind
  21131. * * BABYLON.VertexBuffer.UV3Kind
  21132. * * BABYLON.VertexBuffer.UV4Kind
  21133. * * BABYLON.VertexBuffer.UV5Kind
  21134. * * BABYLON.VertexBuffer.UV6Kind
  21135. * * BABYLON.VertexBuffer.ColorKind
  21136. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21137. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21138. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21139. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21140. * @param data defines the data source
  21141. * @param updatable defines if the data must be flagged as updatable (or static)
  21142. * @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
  21143. * @returns the current mesh
  21144. */
  21145. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21146. return this;
  21147. };
  21148. /**
  21149. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21150. * If the mesh has no geometry, it is simply returned as it is.
  21151. * @param kind defines vertex data kind:
  21152. * * BABYLON.VertexBuffer.PositionKind
  21153. * * BABYLON.VertexBuffer.UVKind
  21154. * * BABYLON.VertexBuffer.UV2Kind
  21155. * * BABYLON.VertexBuffer.UV3Kind
  21156. * * BABYLON.VertexBuffer.UV4Kind
  21157. * * BABYLON.VertexBuffer.UV5Kind
  21158. * * BABYLON.VertexBuffer.UV6Kind
  21159. * * BABYLON.VertexBuffer.ColorKind
  21160. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21161. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21162. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21163. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21164. * @param data defines the data source
  21165. * @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
  21166. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  21167. * @returns the current mesh
  21168. */
  21169. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21170. return this;
  21171. };
  21172. /**
  21173. * Sets the mesh indices,
  21174. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21175. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  21176. * @param totalVertices Defines the total number of vertices
  21177. * @returns the current mesh
  21178. */
  21179. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  21180. return this;
  21181. };
  21182. /**
  21183. * Gets a boolean indicating if specific vertex data is present
  21184. * @param kind defines the vertex data kind to use
  21185. * @returns true is data kind is present
  21186. */
  21187. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  21188. return false;
  21189. };
  21190. /**
  21191. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  21192. * @returns a BoundingInfo
  21193. */
  21194. AbstractMesh.prototype.getBoundingInfo = function () {
  21195. if (this._masterMesh) {
  21196. return this._masterMesh.getBoundingInfo();
  21197. }
  21198. if (!this._boundingInfo) {
  21199. // this._boundingInfo is being created here
  21200. this._updateBoundingInfo();
  21201. }
  21202. // cannot be null.
  21203. return this._boundingInfo;
  21204. };
  21205. /**
  21206. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  21207. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  21208. * @returns the current mesh
  21209. */
  21210. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  21211. if (includeDescendants === void 0) { includeDescendants = true; }
  21212. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  21213. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  21214. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  21215. if (maxDimension === 0) {
  21216. return this;
  21217. }
  21218. var scale = 1 / maxDimension;
  21219. this.scaling.scaleInPlace(scale);
  21220. return this;
  21221. };
  21222. /**
  21223. * Overwrite the current bounding info
  21224. * @param boundingInfo defines the new bounding info
  21225. * @returns the current mesh
  21226. */
  21227. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21228. this._boundingInfo = boundingInfo;
  21229. return this;
  21230. };
  21231. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  21232. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  21233. get: function () {
  21234. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  21235. },
  21236. enumerable: true,
  21237. configurable: true
  21238. });
  21239. /** @hidden */
  21240. AbstractMesh.prototype._preActivate = function () {
  21241. };
  21242. /** @hidden */
  21243. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21244. };
  21245. /** @hidden */
  21246. AbstractMesh.prototype._activate = function (renderId) {
  21247. this._renderId = renderId;
  21248. };
  21249. /**
  21250. * Gets the current world matrix
  21251. * @returns a Matrix
  21252. */
  21253. AbstractMesh.prototype.getWorldMatrix = function () {
  21254. if (this._masterMesh) {
  21255. return this._masterMesh.getWorldMatrix();
  21256. }
  21257. return _super.prototype.getWorldMatrix.call(this);
  21258. };
  21259. /** @hidden */
  21260. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  21261. if (this._masterMesh) {
  21262. return this._masterMesh._getWorldMatrixDeterminant();
  21263. }
  21264. return _super.prototype._getWorldMatrixDeterminant.call(this);
  21265. };
  21266. // ================================== Point of View Movement =================================
  21267. /**
  21268. * Perform relative position change from the point of view of behind the front of the mesh.
  21269. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21270. * Supports definition of mesh facing forward or backward
  21271. * @param amountRight defines the distance on the right axis
  21272. * @param amountUp defines the distance on the up axis
  21273. * @param amountForward defines the distance on the forward axis
  21274. * @returns the current mesh
  21275. */
  21276. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  21277. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  21278. return this;
  21279. };
  21280. /**
  21281. * Calculate relative position change from the point of view of behind the front of the mesh.
  21282. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21283. * Supports definition of mesh facing forward or backward
  21284. * @param amountRight defines the distance on the right axis
  21285. * @param amountUp defines the distance on the up axis
  21286. * @param amountForward defines the distance on the forward axis
  21287. * @returns the new displacement vector
  21288. */
  21289. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  21290. var rotMatrix = new BABYLON.Matrix();
  21291. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  21292. rotQuaternion.toRotationMatrix(rotMatrix);
  21293. var translationDelta = BABYLON.Vector3.Zero();
  21294. var defForwardMult = this.definedFacingForward ? -1 : 1;
  21295. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  21296. return translationDelta;
  21297. };
  21298. // ================================== Point of View Rotation =================================
  21299. /**
  21300. * Perform relative rotation change from the point of view of behind the front of the mesh.
  21301. * Supports definition of mesh facing forward or backward
  21302. * @param flipBack defines the flip
  21303. * @param twirlClockwise defines the twirl
  21304. * @param tiltRight defines the tilt
  21305. * @returns the current mesh
  21306. */
  21307. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21308. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  21309. return this;
  21310. };
  21311. /**
  21312. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  21313. * Supports definition of mesh facing forward or backward.
  21314. * @param flipBack defines the flip
  21315. * @param twirlClockwise defines the twirl
  21316. * @param tiltRight defines the tilt
  21317. * @returns the new rotation vector
  21318. */
  21319. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21320. var defForwardMult = this.definedFacingForward ? 1 : -1;
  21321. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  21322. };
  21323. /**
  21324. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  21325. * @param includeDescendants Include bounding info from descendants as well (true by default)
  21326. * @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
  21327. * @returns the new bounding vectors
  21328. */
  21329. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  21330. if (includeDescendants === void 0) { includeDescendants = true; }
  21331. if (predicate === void 0) { predicate = null; }
  21332. // Ensures that all world matrix will be recomputed.
  21333. this.getScene().incrementRenderId();
  21334. this.computeWorldMatrix(true);
  21335. var min;
  21336. var max;
  21337. var boundingInfo = this.getBoundingInfo();
  21338. if (!this.subMeshes) {
  21339. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21340. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21341. }
  21342. else {
  21343. min = boundingInfo.boundingBox.minimumWorld;
  21344. max = boundingInfo.boundingBox.maximumWorld;
  21345. }
  21346. if (includeDescendants) {
  21347. var descendants = this.getDescendants(false);
  21348. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  21349. var descendant = descendants_1[_i];
  21350. var childMesh = descendant;
  21351. childMesh.computeWorldMatrix(true);
  21352. // Filters meshes based on custom predicate function.
  21353. if (predicate && !predicate(childMesh)) {
  21354. continue;
  21355. }
  21356. //make sure we have the needed params to get mix and max
  21357. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  21358. continue;
  21359. }
  21360. var childBoundingInfo = childMesh.getBoundingInfo();
  21361. var boundingBox = childBoundingInfo.boundingBox;
  21362. var minBox = boundingBox.minimumWorld;
  21363. var maxBox = boundingBox.maximumWorld;
  21364. BABYLON.Tools.CheckExtends(minBox, min, max);
  21365. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21366. }
  21367. }
  21368. return {
  21369. min: min,
  21370. max: max
  21371. };
  21372. };
  21373. /** @hidden */
  21374. AbstractMesh.prototype._updateBoundingInfo = function () {
  21375. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  21376. this._boundingInfo.update(this.worldMatrixFromCache);
  21377. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21378. return this;
  21379. };
  21380. /** @hidden */
  21381. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  21382. if (!this.subMeshes) {
  21383. return this;
  21384. }
  21385. var count = this.subMeshes.length;
  21386. for (var subIndex = 0; subIndex < count; subIndex++) {
  21387. var subMesh = this.subMeshes[subIndex];
  21388. if (count > 1 || !subMesh.IsGlobal) {
  21389. subMesh.updateBoundingInfo(matrix);
  21390. }
  21391. }
  21392. return this;
  21393. };
  21394. /** @hidden */
  21395. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  21396. // Bounding info
  21397. this._updateBoundingInfo();
  21398. };
  21399. /**
  21400. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  21401. * A mesh is in the frustum if its bounding box intersects the frustum
  21402. * @param frustumPlanes defines the frustum to test
  21403. * @returns true if the mesh is in the frustum planes
  21404. */
  21405. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  21406. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  21407. };
  21408. /**
  21409. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  21410. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  21411. * @param frustumPlanes defines the frustum to test
  21412. * @returns true if the mesh is completely in the frustum planes
  21413. */
  21414. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21415. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  21416. };
  21417. /**
  21418. * True if the mesh intersects another mesh or a SolidParticle object
  21419. * @param mesh defines a target mesh or SolidParticle to test
  21420. * @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)
  21421. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  21422. * @returns true if there is an intersection
  21423. */
  21424. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  21425. if (precise === void 0) { precise = false; }
  21426. if (!this._boundingInfo || !mesh._boundingInfo) {
  21427. return false;
  21428. }
  21429. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  21430. return true;
  21431. }
  21432. if (includeDescendants) {
  21433. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  21434. var child = _a[_i];
  21435. if (child.intersectsMesh(mesh, precise, true)) {
  21436. return true;
  21437. }
  21438. }
  21439. }
  21440. return false;
  21441. };
  21442. /**
  21443. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  21444. * @param point defines the point to test
  21445. * @returns true if there is an intersection
  21446. */
  21447. AbstractMesh.prototype.intersectsPoint = function (point) {
  21448. if (!this._boundingInfo) {
  21449. return false;
  21450. }
  21451. return this._boundingInfo.intersectsPoint(point);
  21452. };
  21453. /**
  21454. * Gets the position of the current mesh in camera space
  21455. * @param camera defines the camera to use
  21456. * @returns a position
  21457. */
  21458. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  21459. if (camera === void 0) { camera = null; }
  21460. if (!camera) {
  21461. camera = this.getScene().activeCamera;
  21462. }
  21463. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  21464. };
  21465. /**
  21466. * Returns the distance from the mesh to the active camera
  21467. * @param camera defines the camera to use
  21468. * @returns the distance
  21469. */
  21470. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  21471. if (camera === void 0) { camera = null; }
  21472. if (!camera) {
  21473. camera = this.getScene().activeCamera;
  21474. }
  21475. return this.absolutePosition.subtract(camera.position).length();
  21476. };
  21477. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  21478. // Collisions
  21479. /**
  21480. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  21481. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21482. */
  21483. get: function () {
  21484. return this._checkCollisions;
  21485. },
  21486. set: function (collisionEnabled) {
  21487. this._checkCollisions = collisionEnabled;
  21488. if (this.getScene().workerCollisions) {
  21489. this.getScene().collisionCoordinator.onMeshUpdated(this);
  21490. }
  21491. },
  21492. enumerable: true,
  21493. configurable: true
  21494. });
  21495. Object.defineProperty(AbstractMesh.prototype, "collider", {
  21496. /**
  21497. * Gets Collider object used to compute collisions (not physics)
  21498. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21499. */
  21500. get: function () {
  21501. return this._collider;
  21502. },
  21503. enumerable: true,
  21504. configurable: true
  21505. });
  21506. /**
  21507. * Move the mesh using collision engine
  21508. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21509. * @param displacement defines the requested displacement vector
  21510. * @returns the current mesh
  21511. */
  21512. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  21513. var globalPosition = this.getAbsolutePosition();
  21514. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  21515. if (!this._collider) {
  21516. this._collider = new BABYLON.Collider();
  21517. }
  21518. this._collider._radius = this.ellipsoid;
  21519. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  21520. return this;
  21521. };
  21522. // Collisions
  21523. /** @hidden */
  21524. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  21525. this._generatePointsArray();
  21526. if (!this._positions) {
  21527. return this;
  21528. }
  21529. // Transformation
  21530. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  21531. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  21532. subMesh._lastColliderWorldVertices = [];
  21533. subMesh._trianglePlanes = [];
  21534. var start = subMesh.verticesStart;
  21535. var end = (subMesh.verticesStart + subMesh.verticesCount);
  21536. for (var i = start; i < end; i++) {
  21537. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  21538. }
  21539. }
  21540. // Collide
  21541. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  21542. if (collider.collisionFound) {
  21543. collider.collidedMesh = this;
  21544. }
  21545. return this;
  21546. };
  21547. /** @hidden */
  21548. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  21549. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  21550. var len = subMeshes.length;
  21551. for (var index = 0; index < len; index++) {
  21552. var subMesh = subMeshes.data[index];
  21553. // Bounding test
  21554. if (len > 1 && !subMesh._checkCollision(collider))
  21555. continue;
  21556. this._collideForSubMesh(subMesh, transformMatrix, collider);
  21557. }
  21558. return this;
  21559. };
  21560. /** @hidden */
  21561. AbstractMesh.prototype._checkCollision = function (collider) {
  21562. // Bounding box test
  21563. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  21564. return this;
  21565. // Transformation matrix
  21566. var collisionsScalingMatrix = BABYLON.Tmp.Matrix[0];
  21567. var collisionsTransformMatrix = BABYLON.Tmp.Matrix[1];
  21568. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix);
  21569. this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);
  21570. this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);
  21571. return this;
  21572. };
  21573. // Picking
  21574. /** @hidden */
  21575. AbstractMesh.prototype._generatePointsArray = function () {
  21576. return false;
  21577. };
  21578. /**
  21579. * Checks if the passed Ray intersects with the mesh
  21580. * @param ray defines the ray to use
  21581. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  21582. * @returns the picking info
  21583. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  21584. */
  21585. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  21586. var pickingInfo = new BABYLON.PickingInfo();
  21587. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  21588. return pickingInfo;
  21589. }
  21590. if (!this._generatePointsArray()) {
  21591. return pickingInfo;
  21592. }
  21593. var intersectInfo = null;
  21594. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  21595. var len = subMeshes.length;
  21596. for (var index = 0; index < len; index++) {
  21597. var subMesh = subMeshes.data[index];
  21598. // Bounding test
  21599. if (len > 1 && !subMesh.canIntersects(ray))
  21600. continue;
  21601. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21602. if (currentIntersectInfo) {
  21603. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21604. intersectInfo = currentIntersectInfo;
  21605. intersectInfo.subMeshId = index;
  21606. if (fastCheck) {
  21607. break;
  21608. }
  21609. }
  21610. }
  21611. }
  21612. if (intersectInfo) {
  21613. // Get picked point
  21614. var world = this.getWorldMatrix();
  21615. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21616. var direction = ray.direction.clone();
  21617. direction = direction.scale(intersectInfo.distance);
  21618. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21619. var pickedPoint = worldOrigin.add(worldDirection);
  21620. // Return result
  21621. pickingInfo.hit = true;
  21622. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21623. pickingInfo.pickedPoint = pickedPoint;
  21624. pickingInfo.pickedMesh = this;
  21625. pickingInfo.bu = intersectInfo.bu || 0;
  21626. pickingInfo.bv = intersectInfo.bv || 0;
  21627. pickingInfo.faceId = intersectInfo.faceId;
  21628. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21629. return pickingInfo;
  21630. }
  21631. return pickingInfo;
  21632. };
  21633. /**
  21634. * Clones the current mesh
  21635. * @param name defines the mesh name
  21636. * @param newParent defines the new mesh parent
  21637. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21638. * @returns the new mesh
  21639. */
  21640. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21641. return null;
  21642. };
  21643. /**
  21644. * Disposes all the submeshes of the current meshnp
  21645. * @returns the current mesh
  21646. */
  21647. AbstractMesh.prototype.releaseSubMeshes = function () {
  21648. if (this.subMeshes) {
  21649. while (this.subMeshes.length) {
  21650. this.subMeshes[0].dispose();
  21651. }
  21652. }
  21653. else {
  21654. this.subMeshes = new Array();
  21655. }
  21656. return this;
  21657. };
  21658. /**
  21659. * Releases resources associated with this abstract mesh.
  21660. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21661. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21662. */
  21663. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21664. var _this = this;
  21665. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21666. var index;
  21667. // Smart Array Retainers.
  21668. this.getScene().freeActiveMeshes();
  21669. this.getScene().freeRenderingGroups();
  21670. // Action manager
  21671. if (this.actionManager !== undefined && this.actionManager !== null) {
  21672. this.actionManager.dispose();
  21673. this.actionManager = null;
  21674. }
  21675. // Skeleton
  21676. this._skeleton = null;
  21677. // Intersections in progress
  21678. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21679. var other = this._intersectionsInProgress[index];
  21680. var pos = other._intersectionsInProgress.indexOf(this);
  21681. other._intersectionsInProgress.splice(pos, 1);
  21682. }
  21683. this._intersectionsInProgress = [];
  21684. // Lights
  21685. var lights = this.getScene().lights;
  21686. lights.forEach(function (light) {
  21687. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21688. if (meshIndex !== -1) {
  21689. light.includedOnlyMeshes.splice(meshIndex, 1);
  21690. }
  21691. meshIndex = light.excludedMeshes.indexOf(_this);
  21692. if (meshIndex !== -1) {
  21693. light.excludedMeshes.splice(meshIndex, 1);
  21694. }
  21695. // Shadow generators
  21696. var generator = light.getShadowGenerator();
  21697. if (generator) {
  21698. var shadowMap = generator.getShadowMap();
  21699. if (shadowMap && shadowMap.renderList) {
  21700. meshIndex = shadowMap.renderList.indexOf(_this);
  21701. if (meshIndex !== -1) {
  21702. shadowMap.renderList.splice(meshIndex, 1);
  21703. }
  21704. }
  21705. }
  21706. });
  21707. // SubMeshes
  21708. if (this.getClassName() !== "InstancedMesh") {
  21709. this.releaseSubMeshes();
  21710. }
  21711. // Query
  21712. var engine = this.getScene().getEngine();
  21713. if (this._occlusionQuery) {
  21714. this.isOcclusionQueryInProgress = false;
  21715. engine.deleteQuery(this._occlusionQuery);
  21716. this._occlusionQuery = null;
  21717. }
  21718. // Engine
  21719. engine.wipeCaches();
  21720. // Remove from scene
  21721. this.getScene().removeMesh(this);
  21722. if (disposeMaterialAndTextures) {
  21723. if (this.material) {
  21724. this.material.dispose(false, true);
  21725. }
  21726. }
  21727. if (!doNotRecurse) {
  21728. // Particles
  21729. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21730. if (this.getScene().particleSystems[index].emitter === this) {
  21731. this.getScene().particleSystems[index].dispose();
  21732. index--;
  21733. }
  21734. }
  21735. }
  21736. // facet data
  21737. if (this._facetData.facetDataEnabled) {
  21738. this.disableFacetData();
  21739. }
  21740. this.onAfterWorldMatrixUpdateObservable.clear();
  21741. this.onCollideObservable.clear();
  21742. this.onCollisionPositionChangeObservable.clear();
  21743. this.onRebuildObservable.clear();
  21744. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21745. };
  21746. /**
  21747. * Adds the passed mesh as a child to the current mesh
  21748. * @param mesh defines the child mesh
  21749. * @returns the current mesh
  21750. */
  21751. AbstractMesh.prototype.addChild = function (mesh) {
  21752. mesh.setParent(this);
  21753. return this;
  21754. };
  21755. /**
  21756. * Removes the passed mesh from the current mesh children list
  21757. * @param mesh defines the child mesh
  21758. * @returns the current mesh
  21759. */
  21760. AbstractMesh.prototype.removeChild = function (mesh) {
  21761. mesh.setParent(null);
  21762. return this;
  21763. };
  21764. // Facet data
  21765. /** @hidden */
  21766. AbstractMesh.prototype._initFacetData = function () {
  21767. var data = this._facetData;
  21768. if (!data.facetNormals) {
  21769. data.facetNormals = new Array();
  21770. }
  21771. if (!data.facetPositions) {
  21772. data.facetPositions = new Array();
  21773. }
  21774. if (!data.facetPartitioning) {
  21775. data.facetPartitioning = new Array();
  21776. }
  21777. data.facetNb = (this.getIndices().length / 3) | 0;
  21778. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21779. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21780. for (var f = 0; f < data.facetNb; f++) {
  21781. data.facetNormals[f] = BABYLON.Vector3.Zero();
  21782. data.facetPositions[f] = BABYLON.Vector3.Zero();
  21783. }
  21784. data.facetDataEnabled = true;
  21785. return this;
  21786. };
  21787. /**
  21788. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21789. * This method can be called within the render loop.
  21790. * 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
  21791. * @returns the current mesh
  21792. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21793. */
  21794. AbstractMesh.prototype.updateFacetData = function () {
  21795. var data = this._facetData;
  21796. if (!data.facetDataEnabled) {
  21797. this._initFacetData();
  21798. }
  21799. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21800. var indices = this.getIndices();
  21801. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21802. var bInfo = this.getBoundingInfo();
  21803. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  21804. // init arrays, matrix and sort function on first call
  21805. data.facetDepthSortEnabled = true;
  21806. if (indices instanceof Uint16Array) {
  21807. data.depthSortedIndices = new Uint16Array(indices);
  21808. }
  21809. else if (indices instanceof Uint32Array) {
  21810. data.depthSortedIndices = new Uint32Array(indices);
  21811. }
  21812. else {
  21813. var needs32bits = false;
  21814. for (var i = 0; i < indices.length; i++) {
  21815. if (indices[i] > 65535) {
  21816. needs32bits = true;
  21817. break;
  21818. }
  21819. }
  21820. if (needs32bits) {
  21821. data.depthSortedIndices = new Uint32Array(indices);
  21822. }
  21823. else {
  21824. data.depthSortedIndices = new Uint16Array(indices);
  21825. }
  21826. }
  21827. data.facetDepthSortFunction = function (f1, f2) {
  21828. return (f2.sqDistance - f1.sqDistance);
  21829. };
  21830. if (!data.facetDepthSortFrom) {
  21831. var camera = this.getScene().activeCamera;
  21832. data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21833. }
  21834. data.depthSortedFacets = [];
  21835. for (var f = 0; f < data.facetNb; f++) {
  21836. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21837. data.depthSortedFacets.push(depthSortedFacet);
  21838. }
  21839. data.invertedMatrix = BABYLON.Matrix.Identity();
  21840. data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21841. }
  21842. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21843. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21844. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21845. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  21846. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  21847. data.subDiv.max = data.partitioningSubdivisions;
  21848. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21849. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  21850. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  21851. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  21852. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  21853. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  21854. // set the parameters for ComputeNormals()
  21855. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  21856. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  21857. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21858. data.facetParameters.bInfo = bInfo;
  21859. data.facetParameters.bbSize = data.bbSize;
  21860. data.facetParameters.subDiv = data.subDiv;
  21861. data.facetParameters.ratio = this.partitioningBBoxRatio;
  21862. data.facetParameters.depthSort = data.facetDepthSort;
  21863. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  21864. this.computeWorldMatrix(true);
  21865. this._worldMatrix.invertToRef(data.invertedMatrix);
  21866. BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  21867. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  21868. }
  21869. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  21870. BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  21871. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  21872. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  21873. var l = (data.depthSortedIndices.length / 3) | 0;
  21874. for (var f = 0; f < l; f++) {
  21875. var sind = data.depthSortedFacets[f].ind;
  21876. data.depthSortedIndices[f * 3] = indices[sind];
  21877. data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21878. data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21879. }
  21880. this.updateIndices(data.depthSortedIndices);
  21881. }
  21882. return this;
  21883. };
  21884. /**
  21885. * Returns the facetLocalNormals array.
  21886. * The normals are expressed in the mesh local spac
  21887. * @returns an array of Vector3
  21888. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21889. */
  21890. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21891. if (!this._facetData.facetNormals) {
  21892. this.updateFacetData();
  21893. }
  21894. return this._facetData.facetNormals;
  21895. };
  21896. /**
  21897. * Returns the facetLocalPositions array.
  21898. * The facet positions are expressed in the mesh local space
  21899. * @returns an array of Vector3
  21900. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21901. */
  21902. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21903. if (!this._facetData.facetPositions) {
  21904. this.updateFacetData();
  21905. }
  21906. return this._facetData.facetPositions;
  21907. };
  21908. /**
  21909. * Returns the facetLocalPartioning array
  21910. * @returns an array of array of numbers
  21911. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21912. */
  21913. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21914. if (!this._facetData.facetPartitioning) {
  21915. this.updateFacetData();
  21916. }
  21917. return this._facetData.facetPartitioning;
  21918. };
  21919. /**
  21920. * Returns the i-th facet position in the world system.
  21921. * This method allocates a new Vector3 per call
  21922. * @param i defines the facet index
  21923. * @returns a new Vector3
  21924. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21925. */
  21926. AbstractMesh.prototype.getFacetPosition = function (i) {
  21927. var pos = BABYLON.Vector3.Zero();
  21928. this.getFacetPositionToRef(i, pos);
  21929. return pos;
  21930. };
  21931. /**
  21932. * Sets the reference Vector3 with the i-th facet position in the world system
  21933. * @param i defines the facet index
  21934. * @param ref defines the target vector
  21935. * @returns the current mesh
  21936. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21937. */
  21938. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21939. var localPos = (this.getFacetLocalPositions())[i];
  21940. var world = this.getWorldMatrix();
  21941. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21942. return this;
  21943. };
  21944. /**
  21945. * Returns the i-th facet normal in the world system.
  21946. * This method allocates a new Vector3 per call
  21947. * @param i defines the facet index
  21948. * @returns a new Vector3
  21949. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21950. */
  21951. AbstractMesh.prototype.getFacetNormal = function (i) {
  21952. var norm = BABYLON.Vector3.Zero();
  21953. this.getFacetNormalToRef(i, norm);
  21954. return norm;
  21955. };
  21956. /**
  21957. * Sets the reference Vector3 with the i-th facet normal in the world system
  21958. * @param i defines the facet index
  21959. * @param ref defines the target vector
  21960. * @returns the current mesh
  21961. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21962. */
  21963. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21964. var localNorm = (this.getFacetLocalNormals())[i];
  21965. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21966. return this;
  21967. };
  21968. /**
  21969. * 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)
  21970. * @param x defines x coordinate
  21971. * @param y defines y coordinate
  21972. * @param z defines z coordinate
  21973. * @returns the array of facet indexes
  21974. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21975. */
  21976. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21977. var bInfo = this.getBoundingInfo();
  21978. var data = this._facetData;
  21979. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  21980. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  21981. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  21982. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  21983. return null;
  21984. }
  21985. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  21986. };
  21987. /**
  21988. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21989. * @param projected sets as the (x,y,z) world projection on the facet
  21990. * @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
  21991. * @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
  21992. * @param x defines x coordinate
  21993. * @param y defines y coordinate
  21994. * @param z defines z coordinate
  21995. * @returns the face index if found (or null instead)
  21996. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21997. */
  21998. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21999. if (checkFace === void 0) { checkFace = false; }
  22000. if (facing === void 0) { facing = true; }
  22001. var world = this.getWorldMatrix();
  22002. var invMat = BABYLON.Tmp.Matrix[5];
  22003. world.invertToRef(invMat);
  22004. var invVect = BABYLON.Tmp.Vector3[8];
  22005. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  22006. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  22007. if (projected) {
  22008. // tranform the local computed projected vector to world coordinates
  22009. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  22010. }
  22011. return closest;
  22012. };
  22013. /**
  22014. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  22015. * @param projected sets as the (x,y,z) local projection on the facet
  22016. * @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
  22017. * @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
  22018. * @param x defines x coordinate
  22019. * @param y defines y coordinate
  22020. * @param z defines z coordinate
  22021. * @returns the face index if found (or null instead)
  22022. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22023. */
  22024. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  22025. if (checkFace === void 0) { checkFace = false; }
  22026. if (facing === void 0) { facing = true; }
  22027. var closest = null;
  22028. var tmpx = 0.0;
  22029. var tmpy = 0.0;
  22030. var tmpz = 0.0;
  22031. var d = 0.0; // tmp dot facet normal * facet position
  22032. var t0 = 0.0;
  22033. var projx = 0.0;
  22034. var projy = 0.0;
  22035. var projz = 0.0;
  22036. // Get all the facets in the same partitioning block than (x, y, z)
  22037. var facetPositions = this.getFacetLocalPositions();
  22038. var facetNormals = this.getFacetLocalNormals();
  22039. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  22040. if (!facetsInBlock) {
  22041. return null;
  22042. }
  22043. // Get the closest facet to (x, y, z)
  22044. var shortest = Number.MAX_VALUE; // init distance vars
  22045. var tmpDistance = shortest;
  22046. var fib; // current facet in the block
  22047. var norm; // current facet normal
  22048. var p0; // current facet barycenter position
  22049. // loop on all the facets in the current partitioning block
  22050. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  22051. fib = facetsInBlock[idx];
  22052. norm = facetNormals[fib];
  22053. p0 = facetPositions[fib];
  22054. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  22055. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  22056. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  22057. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  22058. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  22059. projx = x + norm.x * t0;
  22060. projy = y + norm.y * t0;
  22061. projz = z + norm.z * t0;
  22062. tmpx = projx - x;
  22063. tmpy = projy - y;
  22064. tmpz = projz - z;
  22065. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  22066. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  22067. shortest = tmpDistance;
  22068. closest = fib;
  22069. if (projected) {
  22070. projected.x = projx;
  22071. projected.y = projy;
  22072. projected.z = projz;
  22073. }
  22074. }
  22075. }
  22076. }
  22077. return closest;
  22078. };
  22079. /**
  22080. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  22081. * @returns the parameters
  22082. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22083. */
  22084. AbstractMesh.prototype.getFacetDataParameters = function () {
  22085. return this._facetData.facetParameters;
  22086. };
  22087. /**
  22088. * Disables the feature FacetData and frees the related memory
  22089. * @returns the current mesh
  22090. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22091. */
  22092. AbstractMesh.prototype.disableFacetData = function () {
  22093. if (this._facetData.facetDataEnabled) {
  22094. this._facetData.facetDataEnabled = false;
  22095. this._facetData.facetPositions = new Array();
  22096. this._facetData.facetNormals = new Array();
  22097. this._facetData.facetPartitioning = new Array();
  22098. this._facetData.facetParameters = null;
  22099. this._facetData.depthSortedIndices = new Uint32Array(0);
  22100. }
  22101. return this;
  22102. };
  22103. /**
  22104. * Updates the AbstractMesh indices array
  22105. * @param indices defines the data source
  22106. * @returns the current mesh
  22107. */
  22108. AbstractMesh.prototype.updateIndices = function (indices) {
  22109. return this;
  22110. };
  22111. /**
  22112. * Creates new normals data for the mesh
  22113. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  22114. * @returns the current mesh
  22115. */
  22116. AbstractMesh.prototype.createNormals = function (updatable) {
  22117. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22118. var indices = this.getIndices();
  22119. var normals;
  22120. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22121. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22122. }
  22123. else {
  22124. normals = [];
  22125. }
  22126. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  22127. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  22128. return this;
  22129. };
  22130. /**
  22131. * Align the mesh with a normal
  22132. * @param normal defines the normal to use
  22133. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  22134. * @returns the current mesh
  22135. */
  22136. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  22137. if (!upDirection) {
  22138. upDirection = BABYLON.Axis.Y;
  22139. }
  22140. var axisX = BABYLON.Tmp.Vector3[0];
  22141. var axisZ = BABYLON.Tmp.Vector3[1];
  22142. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  22143. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  22144. if (this.rotationQuaternion) {
  22145. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  22146. }
  22147. else {
  22148. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  22149. }
  22150. return this;
  22151. };
  22152. /** @hidden */
  22153. AbstractMesh.prototype._checkOcclusionQuery = function () {
  22154. return false;
  22155. };
  22156. /** No occlusion */
  22157. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  22158. /** Occlusion set to optimisitic */
  22159. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  22160. /** Occlusion set to strict */
  22161. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  22162. /** Use an accurante occlusion algorithm */
  22163. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  22164. /** Use a conservative occlusion algorithm */
  22165. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  22166. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  22167. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  22168. /** Culling strategy with bounding sphere only and then frustum culling */
  22169. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  22170. return AbstractMesh;
  22171. }(BABYLON.TransformNode));
  22172. BABYLON.AbstractMesh = AbstractMesh;
  22173. })(BABYLON || (BABYLON = {}));
  22174. //# sourceMappingURL=babylon.abstractMesh.js.map
  22175. var BABYLON;
  22176. (function (BABYLON) {
  22177. /**
  22178. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  22179. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  22180. * 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.
  22181. */
  22182. var Light = /** @class */ (function (_super) {
  22183. __extends(Light, _super);
  22184. /**
  22185. * Creates a Light object in the scene.
  22186. * Documentation : http://doc.babylonjs.com/tutorials/lights
  22187. * @param name The firendly name of the light
  22188. * @param scene The scene the light belongs too
  22189. */
  22190. function Light(name, scene) {
  22191. var _this = _super.call(this, name, scene) || this;
  22192. /**
  22193. * Diffuse gives the basic color to an object.
  22194. */
  22195. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  22196. /**
  22197. * Specular produces a highlight color on an object.
  22198. * Note: This is note affecting PBR materials.
  22199. */
  22200. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  22201. /**
  22202. * Defines the falloff type for this light. This lets overrriding how punctual light are
  22203. * falling off base on range or angle.
  22204. * This can be set to any values in Light.FALLOFF_x.
  22205. *
  22206. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  22207. * other types of materials.
  22208. */
  22209. _this.falloffType = Light.FALLOFF_DEFAULT;
  22210. /**
  22211. * Strength of the light.
  22212. * Note: By default it is define in the framework own unit.
  22213. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  22214. */
  22215. _this.intensity = 1.0;
  22216. _this._range = Number.MAX_VALUE;
  22217. _this._inverseSquaredRange = 0;
  22218. /**
  22219. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  22220. * of light.
  22221. */
  22222. _this._photometricScale = 1.0;
  22223. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  22224. _this._radius = 0.00001;
  22225. /**
  22226. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  22227. * exceeding the number allowed of the materials.
  22228. */
  22229. _this.renderPriority = 0;
  22230. _this._shadowEnabled = true;
  22231. _this._excludeWithLayerMask = 0;
  22232. _this._includeOnlyWithLayerMask = 0;
  22233. _this._lightmapMode = 0;
  22234. /**
  22235. * @hidden Internal use only.
  22236. */
  22237. _this._excludedMeshesIds = new Array();
  22238. /**
  22239. * @hidden Internal use only.
  22240. */
  22241. _this._includedOnlyMeshesIds = new Array();
  22242. _this.getScene().addLight(_this);
  22243. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  22244. _this._buildUniformLayout();
  22245. _this.includedOnlyMeshes = new Array();
  22246. _this.excludedMeshes = new Array();
  22247. _this._resyncMeshes();
  22248. return _this;
  22249. }
  22250. Object.defineProperty(Light.prototype, "range", {
  22251. /**
  22252. * Defines how far from the source the light is impacting in scene units.
  22253. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22254. */
  22255. get: function () {
  22256. return this._range;
  22257. },
  22258. /**
  22259. * Defines how far from the source the light is impacting in scene units.
  22260. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22261. */
  22262. set: function (value) {
  22263. this._range = value;
  22264. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  22265. },
  22266. enumerable: true,
  22267. configurable: true
  22268. });
  22269. Object.defineProperty(Light.prototype, "intensityMode", {
  22270. /**
  22271. * Gets the photometric scale used to interpret the intensity.
  22272. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22273. */
  22274. get: function () {
  22275. return this._intensityMode;
  22276. },
  22277. /**
  22278. * Sets the photometric scale used to interpret the intensity.
  22279. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22280. */
  22281. set: function (value) {
  22282. this._intensityMode = value;
  22283. this._computePhotometricScale();
  22284. },
  22285. enumerable: true,
  22286. configurable: true
  22287. });
  22288. ;
  22289. ;
  22290. Object.defineProperty(Light.prototype, "radius", {
  22291. /**
  22292. * Gets the light radius used by PBR Materials to simulate soft area lights.
  22293. */
  22294. get: function () {
  22295. return this._radius;
  22296. },
  22297. /**
  22298. * sets the light radius used by PBR Materials to simulate soft area lights.
  22299. */
  22300. set: function (value) {
  22301. this._radius = value;
  22302. this._computePhotometricScale();
  22303. },
  22304. enumerable: true,
  22305. configurable: true
  22306. });
  22307. ;
  22308. ;
  22309. Object.defineProperty(Light.prototype, "shadowEnabled", {
  22310. /**
  22311. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22312. * the current shadow generator.
  22313. */
  22314. get: function () {
  22315. return this._shadowEnabled;
  22316. },
  22317. /**
  22318. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22319. * the current shadow generator.
  22320. */
  22321. set: function (value) {
  22322. if (this._shadowEnabled === value) {
  22323. return;
  22324. }
  22325. this._shadowEnabled = value;
  22326. this._markMeshesAsLightDirty();
  22327. },
  22328. enumerable: true,
  22329. configurable: true
  22330. });
  22331. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  22332. /**
  22333. * Gets the only meshes impacted by this light.
  22334. */
  22335. get: function () {
  22336. return this._includedOnlyMeshes;
  22337. },
  22338. /**
  22339. * Sets the only meshes impacted by this light.
  22340. */
  22341. set: function (value) {
  22342. this._includedOnlyMeshes = value;
  22343. this._hookArrayForIncludedOnly(value);
  22344. },
  22345. enumerable: true,
  22346. configurable: true
  22347. });
  22348. Object.defineProperty(Light.prototype, "excludedMeshes", {
  22349. /**
  22350. * Gets the meshes not impacted by this light.
  22351. */
  22352. get: function () {
  22353. return this._excludedMeshes;
  22354. },
  22355. /**
  22356. * Sets the meshes not impacted by this light.
  22357. */
  22358. set: function (value) {
  22359. this._excludedMeshes = value;
  22360. this._hookArrayForExcluded(value);
  22361. },
  22362. enumerable: true,
  22363. configurable: true
  22364. });
  22365. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  22366. /**
  22367. * Gets the layer id use to find what meshes are not impacted by the light.
  22368. * Inactive if 0
  22369. */
  22370. get: function () {
  22371. return this._excludeWithLayerMask;
  22372. },
  22373. /**
  22374. * Sets the layer id use to find what meshes are not impacted by the light.
  22375. * Inactive if 0
  22376. */
  22377. set: function (value) {
  22378. this._excludeWithLayerMask = value;
  22379. this._resyncMeshes();
  22380. },
  22381. enumerable: true,
  22382. configurable: true
  22383. });
  22384. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  22385. /**
  22386. * Gets the layer id use to find what meshes are impacted by the light.
  22387. * Inactive if 0
  22388. */
  22389. get: function () {
  22390. return this._includeOnlyWithLayerMask;
  22391. },
  22392. /**
  22393. * Sets the layer id use to find what meshes are impacted by the light.
  22394. * Inactive if 0
  22395. */
  22396. set: function (value) {
  22397. this._includeOnlyWithLayerMask = value;
  22398. this._resyncMeshes();
  22399. },
  22400. enumerable: true,
  22401. configurable: true
  22402. });
  22403. Object.defineProperty(Light.prototype, "lightmapMode", {
  22404. /**
  22405. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22406. */
  22407. get: function () {
  22408. return this._lightmapMode;
  22409. },
  22410. /**
  22411. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22412. */
  22413. set: function (value) {
  22414. if (this._lightmapMode === value) {
  22415. return;
  22416. }
  22417. this._lightmapMode = value;
  22418. this._markMeshesAsLightDirty();
  22419. },
  22420. enumerable: true,
  22421. configurable: true
  22422. });
  22423. /**
  22424. * Returns the string "Light".
  22425. * @returns the class name
  22426. */
  22427. Light.prototype.getClassName = function () {
  22428. return "Light";
  22429. };
  22430. /**
  22431. * Converts the light information to a readable string for debug purpose.
  22432. * @param fullDetails Supports for multiple levels of logging within scene loading
  22433. * @returns the human readable light info
  22434. */
  22435. Light.prototype.toString = function (fullDetails) {
  22436. var ret = "Name: " + this.name;
  22437. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22438. if (this.animations) {
  22439. for (var i = 0; i < this.animations.length; i++) {
  22440. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22441. }
  22442. }
  22443. if (fullDetails) {
  22444. }
  22445. return ret;
  22446. };
  22447. /** @hidden */
  22448. Light.prototype._syncParentEnabledState = function () {
  22449. _super.prototype._syncParentEnabledState.call(this);
  22450. this._resyncMeshes();
  22451. };
  22452. /**
  22453. * Set the enabled state of this node.
  22454. * @param value - the new enabled state
  22455. */
  22456. Light.prototype.setEnabled = function (value) {
  22457. _super.prototype.setEnabled.call(this, value);
  22458. this._resyncMeshes();
  22459. };
  22460. /**
  22461. * Returns the Light associated shadow generator if any.
  22462. * @return the associated shadow generator.
  22463. */
  22464. Light.prototype.getShadowGenerator = function () {
  22465. return this._shadowGenerator;
  22466. };
  22467. /**
  22468. * Returns a Vector3, the absolute light position in the World.
  22469. * @returns the world space position of the light
  22470. */
  22471. Light.prototype.getAbsolutePosition = function () {
  22472. return BABYLON.Vector3.Zero();
  22473. };
  22474. /**
  22475. * Specifies if the light will affect the passed mesh.
  22476. * @param mesh The mesh to test against the light
  22477. * @return true the mesh is affected otherwise, false.
  22478. */
  22479. Light.prototype.canAffectMesh = function (mesh) {
  22480. if (!mesh) {
  22481. return true;
  22482. }
  22483. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22484. return false;
  22485. }
  22486. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22487. return false;
  22488. }
  22489. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22490. return false;
  22491. }
  22492. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22493. return false;
  22494. }
  22495. return true;
  22496. };
  22497. /**
  22498. * Sort function to order lights for rendering.
  22499. * @param a First Light object to compare to second.
  22500. * @param b Second Light object to compare first.
  22501. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22502. */
  22503. Light.CompareLightsPriority = function (a, b) {
  22504. //shadow-casting lights have priority over non-shadow-casting lights
  22505. //the renderPrioirty is a secondary sort criterion
  22506. if (a.shadowEnabled !== b.shadowEnabled) {
  22507. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22508. }
  22509. return b.renderPriority - a.renderPriority;
  22510. };
  22511. /**
  22512. * Releases resources associated with this node.
  22513. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22514. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22515. */
  22516. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22517. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22518. if (this._shadowGenerator) {
  22519. this._shadowGenerator.dispose();
  22520. this._shadowGenerator = null;
  22521. }
  22522. // Animations
  22523. this.getScene().stopAnimation(this);
  22524. // Remove from meshes
  22525. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22526. var mesh = _a[_i];
  22527. mesh._removeLightSource(this);
  22528. }
  22529. this._uniformBuffer.dispose();
  22530. // Remove from scene
  22531. this.getScene().removeLight(this);
  22532. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22533. };
  22534. /**
  22535. * Returns the light type ID (integer).
  22536. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22537. */
  22538. Light.prototype.getTypeID = function () {
  22539. return 0;
  22540. };
  22541. /**
  22542. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22543. * @returns the scaled intensity in intensity mode unit
  22544. */
  22545. Light.prototype.getScaledIntensity = function () {
  22546. return this._photometricScale * this.intensity;
  22547. };
  22548. /**
  22549. * Returns a new Light object, named "name", from the current one.
  22550. * @param name The name of the cloned light
  22551. * @returns the new created light
  22552. */
  22553. Light.prototype.clone = function (name) {
  22554. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22555. if (!constructor) {
  22556. return null;
  22557. }
  22558. return BABYLON.SerializationHelper.Clone(constructor, this);
  22559. };
  22560. /**
  22561. * Serializes the current light into a Serialization object.
  22562. * @returns the serialized object.
  22563. */
  22564. Light.prototype.serialize = function () {
  22565. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22566. // Type
  22567. serializationObject.type = this.getTypeID();
  22568. // Parent
  22569. if (this.parent) {
  22570. serializationObject.parentId = this.parent.id;
  22571. }
  22572. // Inclusion / exclusions
  22573. if (this.excludedMeshes.length > 0) {
  22574. serializationObject.excludedMeshesIds = [];
  22575. this.excludedMeshes.forEach(function (mesh) {
  22576. serializationObject.excludedMeshesIds.push(mesh.id);
  22577. });
  22578. }
  22579. if (this.includedOnlyMeshes.length > 0) {
  22580. serializationObject.includedOnlyMeshesIds = [];
  22581. this.includedOnlyMeshes.forEach(function (mesh) {
  22582. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22583. });
  22584. }
  22585. // Animations
  22586. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22587. serializationObject.ranges = this.serializeAnimationRanges();
  22588. return serializationObject;
  22589. };
  22590. /**
  22591. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22592. * This new light is named "name" and added to the passed scene.
  22593. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22594. * @param name The friendly name of the light
  22595. * @param scene The scene the new light will belong to
  22596. * @returns the constructor function
  22597. */
  22598. Light.GetConstructorFromName = function (type, name, scene) {
  22599. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  22600. if (constructorFunc) {
  22601. return constructorFunc;
  22602. }
  22603. // Default to no light for none present once.
  22604. return null;
  22605. };
  22606. /**
  22607. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22608. * @param parsedLight The JSON representation of the light
  22609. * @param scene The scene to create the parsed light in
  22610. * @returns the created light after parsing
  22611. */
  22612. Light.Parse = function (parsedLight, scene) {
  22613. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22614. if (!constructor) {
  22615. return null;
  22616. }
  22617. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22618. // Inclusion / exclusions
  22619. if (parsedLight.excludedMeshesIds) {
  22620. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22621. }
  22622. if (parsedLight.includedOnlyMeshesIds) {
  22623. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22624. }
  22625. // Parent
  22626. if (parsedLight.parentId) {
  22627. light._waitingParentId = parsedLight.parentId;
  22628. }
  22629. // Animations
  22630. if (parsedLight.animations) {
  22631. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22632. var parsedAnimation = parsedLight.animations[animationIndex];
  22633. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22634. }
  22635. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22636. }
  22637. if (parsedLight.autoAnimate) {
  22638. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22639. }
  22640. return light;
  22641. };
  22642. Light.prototype._hookArrayForExcluded = function (array) {
  22643. var _this = this;
  22644. var oldPush = array.push;
  22645. array.push = function () {
  22646. var items = [];
  22647. for (var _i = 0; _i < arguments.length; _i++) {
  22648. items[_i] = arguments[_i];
  22649. }
  22650. var result = oldPush.apply(array, items);
  22651. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22652. var item = items_1[_a];
  22653. item._resyncLighSource(_this);
  22654. }
  22655. return result;
  22656. };
  22657. var oldSplice = array.splice;
  22658. array.splice = function (index, deleteCount) {
  22659. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22660. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22661. var item = deleted_1[_i];
  22662. item._resyncLighSource(_this);
  22663. }
  22664. return deleted;
  22665. };
  22666. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22667. var item = array_1[_i];
  22668. item._resyncLighSource(this);
  22669. }
  22670. };
  22671. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22672. var _this = this;
  22673. var oldPush = array.push;
  22674. array.push = function () {
  22675. var items = [];
  22676. for (var _i = 0; _i < arguments.length; _i++) {
  22677. items[_i] = arguments[_i];
  22678. }
  22679. var result = oldPush.apply(array, items);
  22680. _this._resyncMeshes();
  22681. return result;
  22682. };
  22683. var oldSplice = array.splice;
  22684. array.splice = function (index, deleteCount) {
  22685. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22686. _this._resyncMeshes();
  22687. return deleted;
  22688. };
  22689. this._resyncMeshes();
  22690. };
  22691. Light.prototype._resyncMeshes = function () {
  22692. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22693. var mesh = _a[_i];
  22694. mesh._resyncLighSource(this);
  22695. }
  22696. };
  22697. /**
  22698. * Forces the meshes to update their light related information in their rendering used effects
  22699. * @hidden Internal Use Only
  22700. */
  22701. Light.prototype._markMeshesAsLightDirty = function () {
  22702. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22703. var mesh = _a[_i];
  22704. if (mesh._lightSources.indexOf(this) !== -1) {
  22705. mesh._markSubMeshesAsLightDirty();
  22706. }
  22707. }
  22708. };
  22709. /**
  22710. * Recomputes the cached photometric scale if needed.
  22711. */
  22712. Light.prototype._computePhotometricScale = function () {
  22713. this._photometricScale = this._getPhotometricScale();
  22714. this.getScene().resetCachedMaterial();
  22715. };
  22716. /**
  22717. * Returns the Photometric Scale according to the light type and intensity mode.
  22718. */
  22719. Light.prototype._getPhotometricScale = function () {
  22720. var photometricScale = 0.0;
  22721. var lightTypeID = this.getTypeID();
  22722. //get photometric mode
  22723. var photometricMode = this.intensityMode;
  22724. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22725. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22726. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22727. }
  22728. else {
  22729. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22730. }
  22731. }
  22732. //compute photometric scale
  22733. switch (lightTypeID) {
  22734. case Light.LIGHTTYPEID_POINTLIGHT:
  22735. case Light.LIGHTTYPEID_SPOTLIGHT:
  22736. switch (photometricMode) {
  22737. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22738. photometricScale = 1.0 / (4.0 * Math.PI);
  22739. break;
  22740. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22741. photometricScale = 1.0;
  22742. break;
  22743. case Light.INTENSITYMODE_LUMINANCE:
  22744. photometricScale = this.radius * this.radius;
  22745. break;
  22746. }
  22747. break;
  22748. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22749. switch (photometricMode) {
  22750. case Light.INTENSITYMODE_ILLUMINANCE:
  22751. photometricScale = 1.0;
  22752. break;
  22753. case Light.INTENSITYMODE_LUMINANCE:
  22754. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22755. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22756. var apexAngleRadians = this.radius;
  22757. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22758. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22759. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22760. photometricScale = solidAngle;
  22761. break;
  22762. }
  22763. break;
  22764. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22765. // No fall off in hemisperic light.
  22766. photometricScale = 1.0;
  22767. break;
  22768. }
  22769. return photometricScale;
  22770. };
  22771. /**
  22772. * Reorder the light in the scene according to their defined priority.
  22773. * @hidden Internal Use Only
  22774. */
  22775. Light.prototype._reorderLightsInScene = function () {
  22776. var scene = this.getScene();
  22777. if (this._renderPriority != 0) {
  22778. scene.requireLightSorting = true;
  22779. }
  22780. this.getScene().sortLightsByPriority();
  22781. };
  22782. /**
  22783. * Falloff Default: light is falling off following the material specification:
  22784. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22785. */
  22786. Light.FALLOFF_DEFAULT = 0;
  22787. /**
  22788. * Falloff Physical: light is falling off following the inverse squared distance law.
  22789. */
  22790. Light.FALLOFF_PHYSICAL = 1;
  22791. /**
  22792. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22793. * to enhance interoperability with other engines.
  22794. */
  22795. Light.FALLOFF_GLTF = 2;
  22796. /**
  22797. * Falloff Standard: light is falling off like in the standard material
  22798. * to enhance interoperability with other materials.
  22799. */
  22800. Light.FALLOFF_STANDARD = 3;
  22801. //lightmapMode Consts
  22802. /**
  22803. * If every light affecting the material is in this lightmapMode,
  22804. * material.lightmapTexture adds or multiplies
  22805. * (depends on material.useLightmapAsShadowmap)
  22806. * after every other light calculations.
  22807. */
  22808. Light.LIGHTMAP_DEFAULT = 0;
  22809. /**
  22810. * material.lightmapTexture as only diffuse lighting from this light
  22811. * adds only specular lighting from this light
  22812. * adds dynamic shadows
  22813. */
  22814. Light.LIGHTMAP_SPECULAR = 1;
  22815. /**
  22816. * material.lightmapTexture as only lighting
  22817. * no light calculation from this light
  22818. * only adds dynamic shadows from this light
  22819. */
  22820. Light.LIGHTMAP_SHADOWSONLY = 2;
  22821. // Intensity Mode Consts
  22822. /**
  22823. * Each light type uses the default quantity according to its type:
  22824. * point/spot lights use luminous intensity
  22825. * directional lights use illuminance
  22826. */
  22827. Light.INTENSITYMODE_AUTOMATIC = 0;
  22828. /**
  22829. * lumen (lm)
  22830. */
  22831. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22832. /**
  22833. * candela (lm/sr)
  22834. */
  22835. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22836. /**
  22837. * lux (lm/m^2)
  22838. */
  22839. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22840. /**
  22841. * nit (cd/m^2)
  22842. */
  22843. Light.INTENSITYMODE_LUMINANCE = 4;
  22844. // Light types ids const.
  22845. /**
  22846. * Light type const id of the point light.
  22847. */
  22848. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22849. /**
  22850. * Light type const id of the directional light.
  22851. */
  22852. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22853. /**
  22854. * Light type const id of the spot light.
  22855. */
  22856. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22857. /**
  22858. * Light type const id of the hemispheric light.
  22859. */
  22860. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22861. __decorate([
  22862. BABYLON.serializeAsColor3()
  22863. ], Light.prototype, "diffuse", void 0);
  22864. __decorate([
  22865. BABYLON.serializeAsColor3()
  22866. ], Light.prototype, "specular", void 0);
  22867. __decorate([
  22868. BABYLON.serialize()
  22869. ], Light.prototype, "falloffType", void 0);
  22870. __decorate([
  22871. BABYLON.serialize()
  22872. ], Light.prototype, "intensity", void 0);
  22873. __decorate([
  22874. BABYLON.serialize()
  22875. ], Light.prototype, "range", null);
  22876. __decorate([
  22877. BABYLON.serialize()
  22878. ], Light.prototype, "intensityMode", null);
  22879. __decorate([
  22880. BABYLON.serialize()
  22881. ], Light.prototype, "radius", null);
  22882. __decorate([
  22883. BABYLON.serialize()
  22884. ], Light.prototype, "_renderPriority", void 0);
  22885. __decorate([
  22886. BABYLON.expandToProperty("_reorderLightsInScene")
  22887. ], Light.prototype, "renderPriority", void 0);
  22888. __decorate([
  22889. BABYLON.serialize("shadowEnabled")
  22890. ], Light.prototype, "_shadowEnabled", void 0);
  22891. __decorate([
  22892. BABYLON.serialize("excludeWithLayerMask")
  22893. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22894. __decorate([
  22895. BABYLON.serialize("includeOnlyWithLayerMask")
  22896. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22897. __decorate([
  22898. BABYLON.serialize("lightmapMode")
  22899. ], Light.prototype, "_lightmapMode", void 0);
  22900. return Light;
  22901. }(BABYLON.Node));
  22902. BABYLON.Light = Light;
  22903. })(BABYLON || (BABYLON = {}));
  22904. //# sourceMappingURL=babylon.light.js.map
  22905. var BABYLON;
  22906. (function (BABYLON) {
  22907. /**
  22908. * This is the base class of all the camera used in the application.
  22909. * @see http://doc.babylonjs.com/features/cameras
  22910. */
  22911. var Camera = /** @class */ (function (_super) {
  22912. __extends(Camera, _super);
  22913. /**
  22914. * Instantiates a new camera object.
  22915. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  22916. * @see http://doc.babylonjs.com/features/cameras
  22917. * @param name Defines the name of the camera in the scene
  22918. * @param position Defines the position of the camera
  22919. * @param scene Defines the scene the camera belongs too
  22920. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  22921. */
  22922. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22923. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22924. var _this = _super.call(this, name, scene) || this;
  22925. /**
  22926. * The vector the camera should consider as up.
  22927. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22928. */
  22929. _this.upVector = BABYLON.Vector3.Up();
  22930. /**
  22931. * Define the current limit on the left side for an orthographic camera
  22932. * In scene unit
  22933. */
  22934. _this.orthoLeft = null;
  22935. /**
  22936. * Define the current limit on the right side for an orthographic camera
  22937. * In scene unit
  22938. */
  22939. _this.orthoRight = null;
  22940. /**
  22941. * Define the current limit on the bottom side for an orthographic camera
  22942. * In scene unit
  22943. */
  22944. _this.orthoBottom = null;
  22945. /**
  22946. * Define the current limit on the top side for an orthographic camera
  22947. * In scene unit
  22948. */
  22949. _this.orthoTop = null;
  22950. /**
  22951. * Field Of View is set in Radians. (default is 0.8)
  22952. */
  22953. _this.fov = 0.8;
  22954. /**
  22955. * Define the minimum distance the camera can see from.
  22956. * This is important to note that the depth buffer are not infinite and the closer it starts
  22957. * the more your scene might encounter depth fighting issue.
  22958. */
  22959. _this.minZ = 1;
  22960. /**
  22961. * Define the maximum distance the camera can see to.
  22962. * This is important to note that the depth buffer are not infinite and the further it end
  22963. * the more your scene might encounter depth fighting issue.
  22964. */
  22965. _this.maxZ = 10000.0;
  22966. /**
  22967. * Define the default inertia of the camera.
  22968. * This helps giving a smooth feeling to the camera movement.
  22969. */
  22970. _this.inertia = 0.9;
  22971. /**
  22972. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  22973. */
  22974. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22975. /**
  22976. * Define wether the camera is intermediate.
  22977. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  22978. */
  22979. _this.isIntermediate = false;
  22980. /**
  22981. * Define the viewport of the camera.
  22982. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  22983. */
  22984. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22985. /**
  22986. * Restricts the camera to viewing objects with the same layerMask.
  22987. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22988. */
  22989. _this.layerMask = 0x0FFFFFFF;
  22990. /**
  22991. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22992. */
  22993. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22994. /**
  22995. * Rig mode of the camera.
  22996. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  22997. * This is normally controlled byt the camera themselves as internal use.
  22998. */
  22999. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  23000. /**
  23001. * Defines the list of custom render target the camera should render to.
  23002. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  23003. * else in the scene.
  23004. */
  23005. _this.customRenderTargets = new Array();
  23006. /**
  23007. * Observable triggered when the camera view matrix has changed.
  23008. */
  23009. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  23010. /**
  23011. * Observable triggered when the camera Projection matrix has changed.
  23012. */
  23013. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  23014. /**
  23015. * Observable triggered when the inputs have been processed.
  23016. */
  23017. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  23018. /**
  23019. * Observable triggered when reset has been called and applied to the camera.
  23020. */
  23021. _this.onRestoreStateObservable = new BABYLON.Observable();
  23022. /** @hidden */
  23023. _this._rigCameras = new Array();
  23024. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  23025. /** @hidden */
  23026. _this._skipRendering = false;
  23027. /** @hidden */
  23028. _this._projectionMatrix = new BABYLON.Matrix();
  23029. /** @hidden */
  23030. _this._postProcesses = new Array();
  23031. /** @hidden */
  23032. _this._activeMeshes = new BABYLON.SmartArray(256);
  23033. _this._globalPosition = BABYLON.Vector3.Zero();
  23034. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  23035. _this._doNotComputeProjectionMatrix = false;
  23036. _this._transformMatrix = BABYLON.Matrix.Zero();
  23037. _this._refreshFrustumPlanes = true;
  23038. _this.getScene().addCamera(_this);
  23039. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  23040. _this.getScene().activeCamera = _this;
  23041. }
  23042. _this.position = position;
  23043. return _this;
  23044. }
  23045. /**
  23046. * Store current camera state (fov, position, etc..)
  23047. * @returns the camera
  23048. */
  23049. Camera.prototype.storeState = function () {
  23050. this._stateStored = true;
  23051. this._storedFov = this.fov;
  23052. return this;
  23053. };
  23054. /**
  23055. * Restores the camera state values if it has been stored. You must call storeState() first
  23056. */
  23057. Camera.prototype._restoreStateValues = function () {
  23058. if (!this._stateStored) {
  23059. return false;
  23060. }
  23061. this.fov = this._storedFov;
  23062. return true;
  23063. };
  23064. /**
  23065. * Restored camera state. You must call storeState() first.
  23066. * @returns true if restored and false otherwise
  23067. */
  23068. Camera.prototype.restoreState = function () {
  23069. if (this._restoreStateValues()) {
  23070. this.onRestoreStateObservable.notifyObservers(this);
  23071. return true;
  23072. }
  23073. return false;
  23074. };
  23075. /**
  23076. * Gets the class name of the camera.
  23077. * @returns the class name
  23078. */
  23079. Camera.prototype.getClassName = function () {
  23080. return "Camera";
  23081. };
  23082. /**
  23083. * Gets a string representation of the camera usefull for debug purpose.
  23084. * @param fullDetails Defines that a more verboe level of logging is required
  23085. * @returns the string representation
  23086. */
  23087. Camera.prototype.toString = function (fullDetails) {
  23088. var ret = "Name: " + this.name;
  23089. ret += ", type: " + this.getClassName();
  23090. if (this.animations) {
  23091. for (var i = 0; i < this.animations.length; i++) {
  23092. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23093. }
  23094. }
  23095. if (fullDetails) {
  23096. }
  23097. return ret;
  23098. };
  23099. Object.defineProperty(Camera.prototype, "globalPosition", {
  23100. /**
  23101. * Gets the current world space position of the camera.
  23102. */
  23103. get: function () {
  23104. return this._globalPosition;
  23105. },
  23106. enumerable: true,
  23107. configurable: true
  23108. });
  23109. /**
  23110. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  23111. * @returns the active meshe list
  23112. */
  23113. Camera.prototype.getActiveMeshes = function () {
  23114. return this._activeMeshes;
  23115. };
  23116. /**
  23117. * Check wether a mesh is part of the current active mesh list of the camera
  23118. * @param mesh Defines the mesh to check
  23119. * @returns true if active, false otherwise
  23120. */
  23121. Camera.prototype.isActiveMesh = function (mesh) {
  23122. return (this._activeMeshes.indexOf(mesh) !== -1);
  23123. };
  23124. /**
  23125. * Is this camera ready to be used/rendered
  23126. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  23127. * @return true if the camera is ready
  23128. */
  23129. Camera.prototype.isReady = function (completeCheck) {
  23130. if (completeCheck === void 0) { completeCheck = false; }
  23131. if (completeCheck) {
  23132. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  23133. var pp = _a[_i];
  23134. if (pp && !pp.isReady()) {
  23135. return false;
  23136. }
  23137. }
  23138. }
  23139. return _super.prototype.isReady.call(this, completeCheck);
  23140. };
  23141. /** @hidden */
  23142. Camera.prototype._initCache = function () {
  23143. _super.prototype._initCache.call(this);
  23144. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23145. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23146. this._cache.mode = undefined;
  23147. this._cache.minZ = undefined;
  23148. this._cache.maxZ = undefined;
  23149. this._cache.fov = undefined;
  23150. this._cache.fovMode = undefined;
  23151. this._cache.aspectRatio = undefined;
  23152. this._cache.orthoLeft = undefined;
  23153. this._cache.orthoRight = undefined;
  23154. this._cache.orthoBottom = undefined;
  23155. this._cache.orthoTop = undefined;
  23156. this._cache.renderWidth = undefined;
  23157. this._cache.renderHeight = undefined;
  23158. };
  23159. /** @hidden */
  23160. Camera.prototype._updateCache = function (ignoreParentClass) {
  23161. if (!ignoreParentClass) {
  23162. _super.prototype._updateCache.call(this);
  23163. }
  23164. this._cache.position.copyFrom(this.position);
  23165. this._cache.upVector.copyFrom(this.upVector);
  23166. };
  23167. /** @hidden */
  23168. Camera.prototype._isSynchronized = function () {
  23169. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  23170. };
  23171. /** @hidden */
  23172. Camera.prototype._isSynchronizedViewMatrix = function () {
  23173. if (!_super.prototype._isSynchronized.call(this))
  23174. return false;
  23175. return this._cache.position.equals(this.position)
  23176. && this._cache.upVector.equals(this.upVector)
  23177. && this.isSynchronizedWithParent();
  23178. };
  23179. /** @hidden */
  23180. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  23181. var check = this._cache.mode === this.mode
  23182. && this._cache.minZ === this.minZ
  23183. && this._cache.maxZ === this.maxZ;
  23184. if (!check) {
  23185. return false;
  23186. }
  23187. var engine = this.getEngine();
  23188. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23189. check = this._cache.fov === this.fov
  23190. && this._cache.fovMode === this.fovMode
  23191. && this._cache.aspectRatio === engine.getAspectRatio(this);
  23192. }
  23193. else {
  23194. check = this._cache.orthoLeft === this.orthoLeft
  23195. && this._cache.orthoRight === this.orthoRight
  23196. && this._cache.orthoBottom === this.orthoBottom
  23197. && this._cache.orthoTop === this.orthoTop
  23198. && this._cache.renderWidth === engine.getRenderWidth()
  23199. && this._cache.renderHeight === engine.getRenderHeight();
  23200. }
  23201. return check;
  23202. };
  23203. /**
  23204. * Attach the input controls to a specific dom element to get the input from.
  23205. * @param element Defines the element the controls should be listened from
  23206. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  23207. */
  23208. Camera.prototype.attachControl = function (element, noPreventDefault) {
  23209. };
  23210. /**
  23211. * Detach the current controls from the specified dom element.
  23212. * @param element Defines the element to stop listening the inputs from
  23213. */
  23214. Camera.prototype.detachControl = function (element) {
  23215. };
  23216. /**
  23217. * Update the camera state according to the different inputs gathered during the frame.
  23218. */
  23219. Camera.prototype.update = function () {
  23220. this._checkInputs();
  23221. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23222. this._updateRigCameras();
  23223. }
  23224. };
  23225. /** @hidden */
  23226. Camera.prototype._checkInputs = function () {
  23227. this.onAfterCheckInputsObservable.notifyObservers(this);
  23228. };
  23229. Object.defineProperty(Camera.prototype, "rigCameras", {
  23230. /** @hidden */
  23231. get: function () {
  23232. return this._rigCameras;
  23233. },
  23234. enumerable: true,
  23235. configurable: true
  23236. });
  23237. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  23238. /**
  23239. * Gets the post process used by the rig cameras
  23240. */
  23241. get: function () {
  23242. return this._rigPostProcess;
  23243. },
  23244. enumerable: true,
  23245. configurable: true
  23246. });
  23247. /**
  23248. * Internal, gets the first post proces.
  23249. * @returns the first post process to be run on this camera.
  23250. */
  23251. Camera.prototype._getFirstPostProcess = function () {
  23252. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  23253. if (this._postProcesses[ppIndex] !== null) {
  23254. return this._postProcesses[ppIndex];
  23255. }
  23256. }
  23257. return null;
  23258. };
  23259. Camera.prototype._cascadePostProcessesToRigCams = function () {
  23260. // invalidate framebuffer
  23261. var firstPostProcess = this._getFirstPostProcess();
  23262. if (firstPostProcess) {
  23263. firstPostProcess.markTextureDirty();
  23264. }
  23265. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  23266. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  23267. var cam = this._rigCameras[i];
  23268. var rigPostProcess = cam._rigPostProcess;
  23269. // for VR rig, there does not have to be a post process
  23270. if (rigPostProcess) {
  23271. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  23272. if (isPass) {
  23273. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  23274. cam.isIntermediate = this._postProcesses.length === 0;
  23275. }
  23276. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  23277. rigPostProcess.markTextureDirty();
  23278. }
  23279. else {
  23280. cam._postProcesses = this._postProcesses.slice(0);
  23281. }
  23282. }
  23283. };
  23284. /**
  23285. * Attach a post process to the camera.
  23286. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23287. * @param postProcess The post process to attach to the camera
  23288. * @param insertAt The position of the post process in case several of them are in use in the scene
  23289. * @returns the position the post process has been inserted at
  23290. */
  23291. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  23292. if (insertAt === void 0) { insertAt = null; }
  23293. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  23294. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  23295. return 0;
  23296. }
  23297. if (insertAt == null || insertAt < 0) {
  23298. this._postProcesses.push(postProcess);
  23299. }
  23300. else if (this._postProcesses[insertAt] === null) {
  23301. this._postProcesses[insertAt] = postProcess;
  23302. }
  23303. else {
  23304. this._postProcesses.splice(insertAt, 0, postProcess);
  23305. }
  23306. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23307. return this._postProcesses.indexOf(postProcess);
  23308. };
  23309. /**
  23310. * Detach a post process to the camera.
  23311. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23312. * @param postProcess The post process to detach from the camera
  23313. */
  23314. Camera.prototype.detachPostProcess = function (postProcess) {
  23315. var idx = this._postProcesses.indexOf(postProcess);
  23316. if (idx !== -1) {
  23317. this._postProcesses[idx] = null;
  23318. }
  23319. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23320. };
  23321. /**
  23322. * Gets the current world matrix of the camera
  23323. */
  23324. Camera.prototype.getWorldMatrix = function () {
  23325. if (this._isSynchronizedViewMatrix()) {
  23326. return this._worldMatrix;
  23327. }
  23328. // Getting the the view matrix will also compute the world matrix.
  23329. this.getViewMatrix();
  23330. return this._worldMatrix;
  23331. };
  23332. /** @hidden */
  23333. Camera.prototype._getViewMatrix = function () {
  23334. return BABYLON.Matrix.Identity();
  23335. };
  23336. /**
  23337. * Gets the current view matrix of the camera.
  23338. * @param force forces the camera to recompute the matrix without looking at the cached state
  23339. * @returns the view matrix
  23340. */
  23341. Camera.prototype.getViewMatrix = function (force) {
  23342. if (!force && this._isSynchronizedViewMatrix()) {
  23343. return this._computedViewMatrix;
  23344. }
  23345. this.updateCache();
  23346. this._computedViewMatrix = this._getViewMatrix();
  23347. this._currentRenderId = this.getScene().getRenderId();
  23348. this._childRenderId = this._currentRenderId;
  23349. this._refreshFrustumPlanes = true;
  23350. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  23351. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  23352. }
  23353. this.onViewMatrixChangedObservable.notifyObservers(this);
  23354. this._computedViewMatrix.invertToRef(this._worldMatrix);
  23355. return this._computedViewMatrix;
  23356. };
  23357. /**
  23358. * Freeze the projection matrix.
  23359. * It will prevent the cache check of the camera projection compute and can speed up perf
  23360. * if no parameter of the camera are meant to change
  23361. * @param projection Defines manually a projection if necessary
  23362. */
  23363. Camera.prototype.freezeProjectionMatrix = function (projection) {
  23364. this._doNotComputeProjectionMatrix = true;
  23365. if (projection !== undefined) {
  23366. this._projectionMatrix = projection;
  23367. }
  23368. };
  23369. ;
  23370. /**
  23371. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  23372. */
  23373. Camera.prototype.unfreezeProjectionMatrix = function () {
  23374. this._doNotComputeProjectionMatrix = false;
  23375. };
  23376. ;
  23377. /**
  23378. * Gets the current projection matrix of the camera.
  23379. * @param force forces the camera to recompute the matrix without looking at the cached state
  23380. * @returns the projection matrix
  23381. */
  23382. Camera.prototype.getProjectionMatrix = function (force) {
  23383. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  23384. return this._projectionMatrix;
  23385. }
  23386. // Cache
  23387. this._cache.mode = this.mode;
  23388. this._cache.minZ = this.minZ;
  23389. this._cache.maxZ = this.maxZ;
  23390. // Matrix
  23391. this._refreshFrustumPlanes = true;
  23392. var engine = this.getEngine();
  23393. var scene = this.getScene();
  23394. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23395. this._cache.fov = this.fov;
  23396. this._cache.fovMode = this.fovMode;
  23397. this._cache.aspectRatio = engine.getAspectRatio(this);
  23398. if (this.minZ <= 0) {
  23399. this.minZ = 0.1;
  23400. }
  23401. if (scene.useRightHandedSystem) {
  23402. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23403. }
  23404. else {
  23405. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23406. }
  23407. }
  23408. else {
  23409. var halfWidth = engine.getRenderWidth() / 2.0;
  23410. var halfHeight = engine.getRenderHeight() / 2.0;
  23411. if (scene.useRightHandedSystem) {
  23412. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23413. }
  23414. else {
  23415. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23416. }
  23417. this._cache.orthoLeft = this.orthoLeft;
  23418. this._cache.orthoRight = this.orthoRight;
  23419. this._cache.orthoBottom = this.orthoBottom;
  23420. this._cache.orthoTop = this.orthoTop;
  23421. this._cache.renderWidth = engine.getRenderWidth();
  23422. this._cache.renderHeight = engine.getRenderHeight();
  23423. }
  23424. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  23425. return this._projectionMatrix;
  23426. };
  23427. /**
  23428. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  23429. * @returns a Matrix
  23430. */
  23431. Camera.prototype.getTransformationMatrix = function () {
  23432. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23433. return this._transformMatrix;
  23434. };
  23435. Camera.prototype._updateFrustumPlanes = function () {
  23436. if (!this._refreshFrustumPlanes) {
  23437. return;
  23438. }
  23439. this.getTransformationMatrix();
  23440. if (!this._frustumPlanes) {
  23441. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23442. }
  23443. else {
  23444. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23445. }
  23446. this._refreshFrustumPlanes = false;
  23447. };
  23448. /**
  23449. * Checks if a cullable object (mesh...) is in the camera frustum
  23450. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  23451. * @param target The object to check
  23452. * @returns true if the object is in frustum otherwise false
  23453. */
  23454. Camera.prototype.isInFrustum = function (target) {
  23455. this._updateFrustumPlanes();
  23456. return target.isInFrustum(this._frustumPlanes);
  23457. };
  23458. /**
  23459. * Checks if a cullable object (mesh...) is in the camera frustum
  23460. * Unlike isInFrustum this cheks the full bounding box
  23461. * @param target The object to check
  23462. * @returns true if the object is in frustum otherwise false
  23463. */
  23464. Camera.prototype.isCompletelyInFrustum = function (target) {
  23465. this._updateFrustumPlanes();
  23466. return target.isCompletelyInFrustum(this._frustumPlanes);
  23467. };
  23468. /**
  23469. * Gets a ray in the forward direction from the camera.
  23470. * @param length Defines the length of the ray to create
  23471. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  23472. * @param origin Defines the start point of the ray which defaults to the camera position
  23473. * @returns the forward ray
  23474. */
  23475. Camera.prototype.getForwardRay = function (length, transform, origin) {
  23476. if (length === void 0) { length = 100; }
  23477. if (!transform) {
  23478. transform = this.getWorldMatrix();
  23479. }
  23480. if (!origin) {
  23481. origin = this.position;
  23482. }
  23483. var forward = new BABYLON.Vector3(0, 0, 1);
  23484. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  23485. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  23486. return new BABYLON.Ray(origin, direction, length);
  23487. };
  23488. /**
  23489. * Releases resources associated with this node.
  23490. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  23491. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  23492. */
  23493. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  23494. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  23495. // Observables
  23496. this.onViewMatrixChangedObservable.clear();
  23497. this.onProjectionMatrixChangedObservable.clear();
  23498. this.onAfterCheckInputsObservable.clear();
  23499. this.onRestoreStateObservable.clear();
  23500. // Inputs
  23501. if (this.inputs) {
  23502. this.inputs.clear();
  23503. }
  23504. // Animations
  23505. this.getScene().stopAnimation(this);
  23506. // Remove from scene
  23507. this.getScene().removeCamera(this);
  23508. while (this._rigCameras.length > 0) {
  23509. var camera = this._rigCameras.pop();
  23510. if (camera) {
  23511. camera.dispose();
  23512. }
  23513. }
  23514. // Postprocesses
  23515. if (this._rigPostProcess) {
  23516. this._rigPostProcess.dispose(this);
  23517. this._rigPostProcess = null;
  23518. this._postProcesses = [];
  23519. }
  23520. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23521. this._rigPostProcess = null;
  23522. this._postProcesses = [];
  23523. }
  23524. else {
  23525. var i = this._postProcesses.length;
  23526. while (--i >= 0) {
  23527. var postProcess = this._postProcesses[i];
  23528. if (postProcess) {
  23529. postProcess.dispose(this);
  23530. }
  23531. }
  23532. }
  23533. // Render targets
  23534. var i = this.customRenderTargets.length;
  23535. while (--i >= 0) {
  23536. this.customRenderTargets[i].dispose();
  23537. }
  23538. this.customRenderTargets = [];
  23539. // Active Meshes
  23540. this._activeMeshes.dispose();
  23541. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23542. };
  23543. Object.defineProperty(Camera.prototype, "leftCamera", {
  23544. /**
  23545. * Gets the left camera of a rig setup in case of Rigged Camera
  23546. */
  23547. get: function () {
  23548. if (this._rigCameras.length < 1) {
  23549. return null;
  23550. }
  23551. return this._rigCameras[0];
  23552. },
  23553. enumerable: true,
  23554. configurable: true
  23555. });
  23556. Object.defineProperty(Camera.prototype, "rightCamera", {
  23557. /**
  23558. * Gets the right camera of a rig setup in case of Rigged Camera
  23559. */
  23560. get: function () {
  23561. if (this._rigCameras.length < 2) {
  23562. return null;
  23563. }
  23564. return this._rigCameras[1];
  23565. },
  23566. enumerable: true,
  23567. configurable: true
  23568. });
  23569. /**
  23570. * Gets the left camera target of a rig setup in case of Rigged Camera
  23571. * @returns the target position
  23572. */
  23573. Camera.prototype.getLeftTarget = function () {
  23574. if (this._rigCameras.length < 1) {
  23575. return null;
  23576. }
  23577. return this._rigCameras[0].getTarget();
  23578. };
  23579. /**
  23580. * Gets the right camera target of a rig setup in case of Rigged Camera
  23581. * @returns the target position
  23582. */
  23583. Camera.prototype.getRightTarget = function () {
  23584. if (this._rigCameras.length < 2) {
  23585. return null;
  23586. }
  23587. return this._rigCameras[1].getTarget();
  23588. };
  23589. /**
  23590. * @hidden
  23591. */
  23592. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  23593. if (this.cameraRigMode === mode) {
  23594. return;
  23595. }
  23596. while (this._rigCameras.length > 0) {
  23597. var camera = this._rigCameras.pop();
  23598. if (camera) {
  23599. camera.dispose();
  23600. }
  23601. }
  23602. this.cameraRigMode = mode;
  23603. this._cameraRigParams = {};
  23604. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23605. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23606. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23607. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23608. // create the rig cameras, unless none
  23609. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23610. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23611. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23612. if (leftCamera && rightCamera) {
  23613. this._rigCameras.push(leftCamera);
  23614. this._rigCameras.push(rightCamera);
  23615. }
  23616. }
  23617. switch (this.cameraRigMode) {
  23618. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23619. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23620. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23621. break;
  23622. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23623. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23624. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23625. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23626. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23627. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23628. break;
  23629. case Camera.RIG_MODE_VR:
  23630. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23631. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23632. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23633. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23634. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23635. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23636. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23637. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23638. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23639. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23640. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23641. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23642. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23643. if (metrics.compensateDistortion) {
  23644. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23645. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23646. }
  23647. break;
  23648. case Camera.RIG_MODE_WEBVR:
  23649. if (rigParams.vrDisplay) {
  23650. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23651. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23652. //Left eye
  23653. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23654. this._rigCameras[0].setCameraRigParameter("left", true);
  23655. //leaving this for future reference
  23656. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23657. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23658. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23659. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23660. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23661. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23662. this._rigCameras[0].parent = this;
  23663. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23664. //Right eye
  23665. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23666. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23667. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23668. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23669. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23670. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23671. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23672. this._rigCameras[1].parent = this;
  23673. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23674. if (Camera.UseAlternateWebVRRendering) {
  23675. this._rigCameras[1]._skipRendering = true;
  23676. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23677. }
  23678. }
  23679. break;
  23680. }
  23681. this._cascadePostProcessesToRigCams();
  23682. this.update();
  23683. };
  23684. Camera.prototype._getVRProjectionMatrix = function () {
  23685. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23686. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23687. return this._projectionMatrix;
  23688. };
  23689. Camera.prototype._updateCameraRotationMatrix = function () {
  23690. //Here for WebVR
  23691. };
  23692. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23693. //Here for WebVR
  23694. };
  23695. /**
  23696. * This function MUST be overwritten by the different WebVR cameras available.
  23697. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23698. */
  23699. Camera.prototype._getWebVRProjectionMatrix = function () {
  23700. return BABYLON.Matrix.Identity();
  23701. };
  23702. /**
  23703. * This function MUST be overwritten by the different WebVR cameras available.
  23704. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23705. */
  23706. Camera.prototype._getWebVRViewMatrix = function () {
  23707. return BABYLON.Matrix.Identity();
  23708. };
  23709. /** @hidden */
  23710. Camera.prototype.setCameraRigParameter = function (name, value) {
  23711. if (!this._cameraRigParams) {
  23712. this._cameraRigParams = {};
  23713. }
  23714. this._cameraRigParams[name] = value;
  23715. //provisionnally:
  23716. if (name === "interaxialDistance") {
  23717. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23718. }
  23719. };
  23720. /**
  23721. * needs to be overridden by children so sub has required properties to be copied
  23722. * @hidden
  23723. */
  23724. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23725. return null;
  23726. };
  23727. /**
  23728. * May need to be overridden by children
  23729. * @hidden
  23730. */
  23731. Camera.prototype._updateRigCameras = function () {
  23732. for (var i = 0; i < this._rigCameras.length; i++) {
  23733. this._rigCameras[i].minZ = this.minZ;
  23734. this._rigCameras[i].maxZ = this.maxZ;
  23735. this._rigCameras[i].fov = this.fov;
  23736. }
  23737. // only update viewport when ANAGLYPH
  23738. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23739. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23740. }
  23741. };
  23742. /** @hidden */
  23743. Camera.prototype._setupInputs = function () {
  23744. };
  23745. /**
  23746. * Serialiaze the camera setup to a json represention
  23747. * @returns the JSON representation
  23748. */
  23749. Camera.prototype.serialize = function () {
  23750. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23751. // Type
  23752. serializationObject.type = this.getClassName();
  23753. // Parent
  23754. if (this.parent) {
  23755. serializationObject.parentId = this.parent.id;
  23756. }
  23757. if (this.inputs) {
  23758. this.inputs.serialize(serializationObject);
  23759. }
  23760. // Animations
  23761. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23762. serializationObject.ranges = this.serializeAnimationRanges();
  23763. return serializationObject;
  23764. };
  23765. /**
  23766. * Clones the current camera.
  23767. * @param name The cloned camera name
  23768. * @returns the cloned camera
  23769. */
  23770. Camera.prototype.clone = function (name) {
  23771. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23772. };
  23773. /**
  23774. * Gets the direction of the camera relative to a given local axis.
  23775. * @param localAxis Defines the reference axis to provide a relative direction.
  23776. * @return the direction
  23777. */
  23778. Camera.prototype.getDirection = function (localAxis) {
  23779. var result = BABYLON.Vector3.Zero();
  23780. this.getDirectionToRef(localAxis, result);
  23781. return result;
  23782. };
  23783. /**
  23784. * Gets the direction of the camera relative to a given local axis into a passed vector.
  23785. * @param localAxis Defines the reference axis to provide a relative direction.
  23786. * @param result Defines the vector to store the result in
  23787. */
  23788. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23789. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23790. };
  23791. /**
  23792. * Gets a camera constructor for a given camera type
  23793. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  23794. * @param name The name of the camera the result will be able to instantiate
  23795. * @param scene The scene the result will construct the camera in
  23796. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  23797. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  23798. * @returns a factory method to construc the camera
  23799. */
  23800. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23801. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23802. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23803. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  23804. interaxial_distance: interaxial_distance,
  23805. isStereoscopicSideBySide: isStereoscopicSideBySide
  23806. });
  23807. if (constructorFunc) {
  23808. return constructorFunc;
  23809. }
  23810. // Default to universal camera
  23811. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23812. };
  23813. /**
  23814. * Compute the world matrix of the camera.
  23815. * @returns the camera workd matrix
  23816. */
  23817. Camera.prototype.computeWorldMatrix = function () {
  23818. return this.getWorldMatrix();
  23819. };
  23820. /**
  23821. * Parse a JSON and creates the camera from the parsed information
  23822. * @param parsedCamera The JSON to parse
  23823. * @param scene The scene to instantiate the camera in
  23824. * @returns the newly constructed camera
  23825. */
  23826. Camera.Parse = function (parsedCamera, scene) {
  23827. var type = parsedCamera.type;
  23828. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23829. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23830. // Parent
  23831. if (parsedCamera.parentId) {
  23832. camera._waitingParentId = parsedCamera.parentId;
  23833. }
  23834. //If camera has an input manager, let it parse inputs settings
  23835. if (camera.inputs) {
  23836. camera.inputs.parse(parsedCamera);
  23837. camera._setupInputs();
  23838. }
  23839. if (camera.setPosition) { // need to force position
  23840. camera.position.copyFromFloats(0, 0, 0);
  23841. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23842. }
  23843. // Target
  23844. if (parsedCamera.target) {
  23845. if (camera.setTarget) {
  23846. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23847. }
  23848. }
  23849. // Apply 3d rig, when found
  23850. if (parsedCamera.cameraRigMode) {
  23851. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23852. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23853. }
  23854. // Animations
  23855. if (parsedCamera.animations) {
  23856. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23857. var parsedAnimation = parsedCamera.animations[animationIndex];
  23858. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23859. }
  23860. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23861. }
  23862. if (parsedCamera.autoAnimate) {
  23863. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23864. }
  23865. return camera;
  23866. };
  23867. /**
  23868. * This is the default projection mode used by the cameras.
  23869. * It helps recreating a feeling of perspective and better appreciate depth.
  23870. * This is the best way to simulate real life cameras.
  23871. */
  23872. Camera.PERSPECTIVE_CAMERA = 0;
  23873. /**
  23874. * This helps creating camera with an orthographic mode.
  23875. * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.
  23876. */
  23877. Camera.ORTHOGRAPHIC_CAMERA = 1;
  23878. /**
  23879. * This is the default FOV mode for perspective cameras.
  23880. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  23881. */
  23882. Camera.FOVMODE_VERTICAL_FIXED = 0;
  23883. /**
  23884. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  23885. */
  23886. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  23887. /**
  23888. * This specifies ther is no need for a camera rig.
  23889. * Basically only one eye is rendered corresponding to the camera.
  23890. */
  23891. Camera.RIG_MODE_NONE = 0;
  23892. /**
  23893. * Simulates a camera Rig with one blue eye and one red eye.
  23894. * This can be use with 3d blue and red glasses.
  23895. */
  23896. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23897. /**
  23898. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  23899. */
  23900. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23901. /**
  23902. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  23903. */
  23904. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23905. /**
  23906. * Defines that both eyes of the camera will be rendered over under each other.
  23907. */
  23908. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23909. /**
  23910. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  23911. */
  23912. Camera.RIG_MODE_VR = 20;
  23913. /**
  23914. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  23915. */
  23916. Camera.RIG_MODE_WEBVR = 21;
  23917. /**
  23918. * Defines if by default attaching controls should prevent the default javascript event to continue.
  23919. */
  23920. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23921. /**
  23922. * @hidden
  23923. * Might be removed once multiview will be a thing
  23924. */
  23925. Camera.UseAlternateWebVRRendering = false;
  23926. __decorate([
  23927. BABYLON.serializeAsVector3()
  23928. ], Camera.prototype, "position", void 0);
  23929. __decorate([
  23930. BABYLON.serializeAsVector3()
  23931. ], Camera.prototype, "upVector", void 0);
  23932. __decorate([
  23933. BABYLON.serialize()
  23934. ], Camera.prototype, "orthoLeft", void 0);
  23935. __decorate([
  23936. BABYLON.serialize()
  23937. ], Camera.prototype, "orthoRight", void 0);
  23938. __decorate([
  23939. BABYLON.serialize()
  23940. ], Camera.prototype, "orthoBottom", void 0);
  23941. __decorate([
  23942. BABYLON.serialize()
  23943. ], Camera.prototype, "orthoTop", void 0);
  23944. __decorate([
  23945. BABYLON.serialize()
  23946. ], Camera.prototype, "fov", void 0);
  23947. __decorate([
  23948. BABYLON.serialize()
  23949. ], Camera.prototype, "minZ", void 0);
  23950. __decorate([
  23951. BABYLON.serialize()
  23952. ], Camera.prototype, "maxZ", void 0);
  23953. __decorate([
  23954. BABYLON.serialize()
  23955. ], Camera.prototype, "inertia", void 0);
  23956. __decorate([
  23957. BABYLON.serialize()
  23958. ], Camera.prototype, "mode", void 0);
  23959. __decorate([
  23960. BABYLON.serialize()
  23961. ], Camera.prototype, "layerMask", void 0);
  23962. __decorate([
  23963. BABYLON.serialize()
  23964. ], Camera.prototype, "fovMode", void 0);
  23965. __decorate([
  23966. BABYLON.serialize()
  23967. ], Camera.prototype, "cameraRigMode", void 0);
  23968. __decorate([
  23969. BABYLON.serialize()
  23970. ], Camera.prototype, "interaxialDistance", void 0);
  23971. __decorate([
  23972. BABYLON.serialize()
  23973. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23974. return Camera;
  23975. }(BABYLON.Node));
  23976. BABYLON.Camera = Camera;
  23977. })(BABYLON || (BABYLON = {}));
  23978. //# sourceMappingURL=babylon.camera.js.map
  23979. var BABYLON;
  23980. (function (BABYLON) {
  23981. /**
  23982. * This is the manager responsible of all the rendering for meshes sprites and particles.
  23983. * It is enable to manage the different groups as well as the different necessary sort functions.
  23984. * This should not be used directly aside of the few static configurations
  23985. */
  23986. var RenderingManager = /** @class */ (function () {
  23987. /**
  23988. * Instantiates a new rendering group for a particular scene
  23989. * @param scene Defines the scene the groups belongs to
  23990. */
  23991. function RenderingManager(scene) {
  23992. /**
  23993. * @hidden
  23994. */
  23995. this._useSceneAutoClearSetup = false;
  23996. this._renderingGroups = new Array();
  23997. this._autoClearDepthStencil = {};
  23998. this._customOpaqueSortCompareFn = {};
  23999. this._customAlphaTestSortCompareFn = {};
  24000. this._customTransparentSortCompareFn = {};
  24001. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  24002. this._scene = scene;
  24003. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  24004. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  24005. }
  24006. }
  24007. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  24008. if (depth === void 0) { depth = true; }
  24009. if (stencil === void 0) { stencil = true; }
  24010. if (this._depthStencilBufferAlreadyCleaned) {
  24011. return;
  24012. }
  24013. this._scene.getEngine().clear(null, false, depth, stencil);
  24014. this._depthStencilBufferAlreadyCleaned = true;
  24015. };
  24016. /**
  24017. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  24018. * @hidden
  24019. */
  24020. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  24021. // Update the observable context (not null as it only goes away on dispose)
  24022. var info = this._renderingGroupInfo;
  24023. info.scene = this._scene;
  24024. info.camera = this._scene.activeCamera;
  24025. // Dispatch sprites
  24026. if (this._scene.spriteManagers && renderSprites) {
  24027. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  24028. var manager = this._scene.spriteManagers[index];
  24029. this.dispatchSprites(manager);
  24030. }
  24031. }
  24032. // Render
  24033. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24034. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  24035. var renderingGroup = this._renderingGroups[index];
  24036. if (!renderingGroup)
  24037. continue;
  24038. var renderingGroupMask = Math.pow(2, index);
  24039. info.renderingGroupId = index;
  24040. // Before Observable
  24041. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24042. // Clear depth/stencil if needed
  24043. if (RenderingManager.AUTOCLEAR) {
  24044. var autoClear = this._useSceneAutoClearSetup ?
  24045. this._scene.getAutoClearDepthStencilSetup(index) :
  24046. this._autoClearDepthStencil[index];
  24047. if (autoClear && autoClear.autoClear) {
  24048. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  24049. }
  24050. }
  24051. // Render
  24052. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  24053. var step = _a[_i];
  24054. step.action(index);
  24055. }
  24056. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  24057. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  24058. var step = _c[_b];
  24059. step.action(index);
  24060. }
  24061. // After Observable
  24062. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24063. }
  24064. };
  24065. /**
  24066. * Resets the different information of the group to prepare a new frame
  24067. * @hidden
  24068. */
  24069. RenderingManager.prototype.reset = function () {
  24070. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24071. var renderingGroup = this._renderingGroups[index];
  24072. if (renderingGroup) {
  24073. renderingGroup.prepare();
  24074. }
  24075. }
  24076. };
  24077. /**
  24078. * Dispose and release the group and its associated resources.
  24079. * @hidden
  24080. */
  24081. RenderingManager.prototype.dispose = function () {
  24082. this.freeRenderingGroups();
  24083. this._renderingGroups.length = 0;
  24084. this._renderingGroupInfo = null;
  24085. };
  24086. /**
  24087. * Clear the info related to rendering groups preventing retention points during dispose.
  24088. */
  24089. RenderingManager.prototype.freeRenderingGroups = function () {
  24090. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24091. var renderingGroup = this._renderingGroups[index];
  24092. if (renderingGroup) {
  24093. renderingGroup.dispose();
  24094. }
  24095. }
  24096. };
  24097. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  24098. if (this._renderingGroups[renderingGroupId] === undefined) {
  24099. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  24100. }
  24101. };
  24102. /**
  24103. * Add a sprite manager to the rendering manager in order to render it this frame.
  24104. * @param spriteManager Define the sprite manager to render
  24105. */
  24106. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  24107. var renderingGroupId = spriteManager.renderingGroupId || 0;
  24108. this._prepareRenderingGroup(renderingGroupId);
  24109. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  24110. };
  24111. /**
  24112. * Add a particle system to the rendering manager in order to render it this frame.
  24113. * @param particleSystem Define the particle system to render
  24114. */
  24115. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  24116. var renderingGroupId = particleSystem.renderingGroupId || 0;
  24117. this._prepareRenderingGroup(renderingGroupId);
  24118. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  24119. };
  24120. /**
  24121. * Add a submesh to the manager in order to render it this frame
  24122. * @param subMesh The submesh to dispatch
  24123. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24124. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24125. */
  24126. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  24127. if (mesh === undefined) {
  24128. mesh = subMesh.getMesh();
  24129. }
  24130. var renderingGroupId = mesh.renderingGroupId || 0;
  24131. this._prepareRenderingGroup(renderingGroupId);
  24132. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  24133. };
  24134. /**
  24135. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24136. * This allowed control for front to back rendering or reversly depending of the special needs.
  24137. *
  24138. * @param renderingGroupId The rendering group id corresponding to its index
  24139. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24140. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24141. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24142. */
  24143. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24144. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24145. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24146. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24147. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  24148. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  24149. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  24150. if (this._renderingGroups[renderingGroupId]) {
  24151. var group = this._renderingGroups[renderingGroupId];
  24152. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  24153. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  24154. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  24155. }
  24156. };
  24157. /**
  24158. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24159. *
  24160. * @param renderingGroupId The rendering group id corresponding to its index
  24161. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24162. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24163. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24164. */
  24165. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24166. if (depth === void 0) { depth = true; }
  24167. if (stencil === void 0) { stencil = true; }
  24168. this._autoClearDepthStencil[renderingGroupId] = {
  24169. autoClear: autoClearDepthStencil,
  24170. depth: depth,
  24171. stencil: stencil
  24172. };
  24173. };
  24174. /**
  24175. * Gets the current auto clear configuration for one rendering group of the rendering
  24176. * manager.
  24177. * @param index the rendering group index to get the information for
  24178. * @returns The auto clear setup for the requested rendering group
  24179. */
  24180. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  24181. return this._autoClearDepthStencil[index];
  24182. };
  24183. /**
  24184. * The max id used for rendering groups (not included)
  24185. */
  24186. RenderingManager.MAX_RENDERINGGROUPS = 4;
  24187. /**
  24188. * The min id used for rendering groups (included)
  24189. */
  24190. RenderingManager.MIN_RENDERINGGROUPS = 0;
  24191. /**
  24192. * Used to globally prevent autoclearing scenes.
  24193. */
  24194. RenderingManager.AUTOCLEAR = true;
  24195. return RenderingManager;
  24196. }());
  24197. BABYLON.RenderingManager = RenderingManager;
  24198. })(BABYLON || (BABYLON = {}));
  24199. //# sourceMappingURL=babylon.renderingManager.js.map
  24200. var BABYLON;
  24201. (function (BABYLON) {
  24202. /**
  24203. * This represents the object necessary to create a rendering group.
  24204. * This is exclusively used and created by the rendering manager.
  24205. * To modify the behavior, you use the available helpers in your scene or meshes.
  24206. * @hidden
  24207. */
  24208. var RenderingGroup = /** @class */ (function () {
  24209. /**
  24210. * Creates a new rendering group.
  24211. * @param index The rendering group index
  24212. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  24213. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  24214. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  24215. */
  24216. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24217. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24218. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24219. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24220. this.index = index;
  24221. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  24222. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  24223. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  24224. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  24225. this._particleSystems = new BABYLON.SmartArray(256);
  24226. this._spriteManagers = new BABYLON.SmartArray(256);
  24227. this._edgesRenderers = new BABYLON.SmartArray(16);
  24228. this._scene = scene;
  24229. this.opaqueSortCompareFn = opaqueSortCompareFn;
  24230. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  24231. this.transparentSortCompareFn = transparentSortCompareFn;
  24232. }
  24233. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  24234. /**
  24235. * Set the opaque sort comparison function.
  24236. * If null the sub meshes will be render in the order they were created
  24237. */
  24238. set: function (value) {
  24239. this._opaqueSortCompareFn = value;
  24240. if (value) {
  24241. this._renderOpaque = this.renderOpaqueSorted;
  24242. }
  24243. else {
  24244. this._renderOpaque = RenderingGroup.renderUnsorted;
  24245. }
  24246. },
  24247. enumerable: true,
  24248. configurable: true
  24249. });
  24250. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  24251. /**
  24252. * Set the alpha test sort comparison function.
  24253. * If null the sub meshes will be render in the order they were created
  24254. */
  24255. set: function (value) {
  24256. this._alphaTestSortCompareFn = value;
  24257. if (value) {
  24258. this._renderAlphaTest = this.renderAlphaTestSorted;
  24259. }
  24260. else {
  24261. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  24262. }
  24263. },
  24264. enumerable: true,
  24265. configurable: true
  24266. });
  24267. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  24268. /**
  24269. * Set the transparent sort comparison function.
  24270. * If null the sub meshes will be render in the order they were created
  24271. */
  24272. set: function (value) {
  24273. if (value) {
  24274. this._transparentSortCompareFn = value;
  24275. }
  24276. else {
  24277. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  24278. }
  24279. this._renderTransparent = this.renderTransparentSorted;
  24280. },
  24281. enumerable: true,
  24282. configurable: true
  24283. });
  24284. /**
  24285. * Render all the sub meshes contained in the group.
  24286. * @param customRenderFunction Used to override the default render behaviour of the group.
  24287. * @returns true if rendered some submeshes.
  24288. */
  24289. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  24290. if (customRenderFunction) {
  24291. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  24292. return;
  24293. }
  24294. var engine = this._scene.getEngine();
  24295. // Depth only
  24296. if (this._depthOnlySubMeshes.length !== 0) {
  24297. engine.setColorWrite(false);
  24298. this._renderAlphaTest(this._depthOnlySubMeshes);
  24299. engine.setColorWrite(true);
  24300. }
  24301. // Opaque
  24302. if (this._opaqueSubMeshes.length !== 0) {
  24303. this._renderOpaque(this._opaqueSubMeshes);
  24304. }
  24305. // Alpha test
  24306. if (this._alphaTestSubMeshes.length !== 0) {
  24307. this._renderAlphaTest(this._alphaTestSubMeshes);
  24308. }
  24309. var stencilState = engine.getStencilBuffer();
  24310. engine.setStencilBuffer(false);
  24311. // Sprites
  24312. if (renderSprites) {
  24313. this._renderSprites();
  24314. }
  24315. // Particles
  24316. if (renderParticles) {
  24317. this._renderParticles(activeMeshes);
  24318. }
  24319. if (this.onBeforeTransparentRendering) {
  24320. this.onBeforeTransparentRendering();
  24321. }
  24322. // Transparent
  24323. if (this._transparentSubMeshes.length !== 0) {
  24324. this._renderTransparent(this._transparentSubMeshes);
  24325. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24326. }
  24327. // Set back stencil to false in case it changes before the edge renderer.
  24328. engine.setStencilBuffer(false);
  24329. // Edges
  24330. if (this._edgesRenderers.length) {
  24331. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  24332. this._edgesRenderers.data[edgesRendererIndex].render();
  24333. }
  24334. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24335. }
  24336. // Restore Stencil state.
  24337. engine.setStencilBuffer(stencilState);
  24338. };
  24339. /**
  24340. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  24341. * @param subMeshes The submeshes to render
  24342. */
  24343. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  24344. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  24345. };
  24346. /**
  24347. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  24348. * @param subMeshes The submeshes to render
  24349. */
  24350. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  24351. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  24352. };
  24353. /**
  24354. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  24355. * @param subMeshes The submeshes to render
  24356. */
  24357. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  24358. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  24359. };
  24360. /**
  24361. * Renders the submeshes in a specified order.
  24362. * @param subMeshes The submeshes to sort before render
  24363. * @param sortCompareFn The comparison function use to sort
  24364. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  24365. * @param transparent Specifies to activate blending if true
  24366. */
  24367. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  24368. var subIndex = 0;
  24369. var subMesh;
  24370. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  24371. for (; subIndex < subMeshes.length; subIndex++) {
  24372. subMesh = subMeshes.data[subIndex];
  24373. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  24374. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  24375. }
  24376. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  24377. if (sortCompareFn) {
  24378. sortedArray.sort(sortCompareFn);
  24379. }
  24380. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  24381. subMesh = sortedArray[subIndex];
  24382. if (transparent) {
  24383. var material = subMesh.getMaterial();
  24384. if (material && material.needDepthPrePass) {
  24385. var engine = material.getScene().getEngine();
  24386. engine.setColorWrite(false);
  24387. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24388. subMesh.render(false);
  24389. engine.setColorWrite(true);
  24390. }
  24391. }
  24392. subMesh.render(transparent);
  24393. }
  24394. };
  24395. /**
  24396. * Renders the submeshes in the order they were dispatched (no sort applied).
  24397. * @param subMeshes The submeshes to render
  24398. */
  24399. RenderingGroup.renderUnsorted = function (subMeshes) {
  24400. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  24401. var submesh = subMeshes.data[subIndex];
  24402. submesh.render(false);
  24403. }
  24404. };
  24405. /**
  24406. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24407. * are rendered back to front if in the same alpha index.
  24408. *
  24409. * @param a The first submesh
  24410. * @param b The second submesh
  24411. * @returns The result of the comparison
  24412. */
  24413. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  24414. // Alpha index first
  24415. if (a._alphaIndex > b._alphaIndex) {
  24416. return 1;
  24417. }
  24418. if (a._alphaIndex < b._alphaIndex) {
  24419. return -1;
  24420. }
  24421. // Then distance to camera
  24422. return RenderingGroup.backToFrontSortCompare(a, b);
  24423. };
  24424. /**
  24425. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24426. * are rendered back to front.
  24427. *
  24428. * @param a The first submesh
  24429. * @param b The second submesh
  24430. * @returns The result of the comparison
  24431. */
  24432. RenderingGroup.backToFrontSortCompare = function (a, b) {
  24433. // Then distance to camera
  24434. if (a._distanceToCamera < b._distanceToCamera) {
  24435. return 1;
  24436. }
  24437. if (a._distanceToCamera > b._distanceToCamera) {
  24438. return -1;
  24439. }
  24440. return 0;
  24441. };
  24442. /**
  24443. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24444. * are rendered front to back (prevent overdraw).
  24445. *
  24446. * @param a The first submesh
  24447. * @param b The second submesh
  24448. * @returns The result of the comparison
  24449. */
  24450. RenderingGroup.frontToBackSortCompare = function (a, b) {
  24451. // Then distance to camera
  24452. if (a._distanceToCamera < b._distanceToCamera) {
  24453. return -1;
  24454. }
  24455. if (a._distanceToCamera > b._distanceToCamera) {
  24456. return 1;
  24457. }
  24458. return 0;
  24459. };
  24460. /**
  24461. * Resets the different lists of submeshes to prepare a new frame.
  24462. */
  24463. RenderingGroup.prototype.prepare = function () {
  24464. this._opaqueSubMeshes.reset();
  24465. this._transparentSubMeshes.reset();
  24466. this._alphaTestSubMeshes.reset();
  24467. this._depthOnlySubMeshes.reset();
  24468. this._particleSystems.reset();
  24469. this._spriteManagers.reset();
  24470. this._edgesRenderers.reset();
  24471. };
  24472. RenderingGroup.prototype.dispose = function () {
  24473. this._opaqueSubMeshes.dispose();
  24474. this._transparentSubMeshes.dispose();
  24475. this._alphaTestSubMeshes.dispose();
  24476. this._depthOnlySubMeshes.dispose();
  24477. this._particleSystems.dispose();
  24478. this._spriteManagers.dispose();
  24479. this._edgesRenderers.dispose();
  24480. };
  24481. /**
  24482. * Inserts the submesh in its correct queue depending on its material.
  24483. * @param subMesh The submesh to dispatch
  24484. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24485. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24486. */
  24487. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  24488. // Get mesh and materials if not provided
  24489. if (mesh === undefined) {
  24490. mesh = subMesh.getMesh();
  24491. }
  24492. if (material === undefined) {
  24493. material = subMesh.getMaterial();
  24494. }
  24495. if (material === null || material === undefined) {
  24496. return;
  24497. }
  24498. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  24499. this._transparentSubMeshes.push(subMesh);
  24500. }
  24501. else if (material.needAlphaTesting()) { // Alpha test
  24502. if (material.needDepthPrePass) {
  24503. this._depthOnlySubMeshes.push(subMesh);
  24504. }
  24505. this._alphaTestSubMeshes.push(subMesh);
  24506. }
  24507. else {
  24508. if (material.needDepthPrePass) {
  24509. this._depthOnlySubMeshes.push(subMesh);
  24510. }
  24511. this._opaqueSubMeshes.push(subMesh); // Opaque
  24512. }
  24513. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  24514. this._edgesRenderers.push(mesh._edgesRenderer);
  24515. }
  24516. };
  24517. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  24518. this._spriteManagers.push(spriteManager);
  24519. };
  24520. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  24521. this._particleSystems.push(particleSystem);
  24522. };
  24523. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  24524. if (this._particleSystems.length === 0) {
  24525. return;
  24526. }
  24527. // Particles
  24528. var activeCamera = this._scene.activeCamera;
  24529. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  24530. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  24531. var particleSystem = this._particleSystems.data[particleIndex];
  24532. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  24533. continue;
  24534. }
  24535. var emitter = particleSystem.emitter;
  24536. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  24537. this._scene._activeParticles.addCount(particleSystem.render(), false);
  24538. }
  24539. }
  24540. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  24541. };
  24542. RenderingGroup.prototype._renderSprites = function () {
  24543. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  24544. return;
  24545. }
  24546. // Sprites
  24547. var activeCamera = this._scene.activeCamera;
  24548. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  24549. for (var id = 0; id < this._spriteManagers.length; id++) {
  24550. var spriteManager = this._spriteManagers.data[id];
  24551. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  24552. spriteManager.render();
  24553. }
  24554. }
  24555. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  24556. };
  24557. return RenderingGroup;
  24558. }());
  24559. BABYLON.RenderingGroup = RenderingGroup;
  24560. })(BABYLON || (BABYLON = {}));
  24561. //# sourceMappingURL=babylon.renderingGroup.js.map
  24562. var BABYLON;
  24563. (function (BABYLON) {
  24564. /**
  24565. * Groups all the scene component constants in one place to ease maintenance.
  24566. * @hidden
  24567. */
  24568. var SceneComponentConstants = /** @class */ (function () {
  24569. function SceneComponentConstants() {
  24570. }
  24571. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  24572. SceneComponentConstants.NAME_LAYER = "Layer";
  24573. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  24574. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  24575. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  24576. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  24577. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  24578. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  24579. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  24580. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  24581. SceneComponentConstants.NAME_SPRITE = "Sprite";
  24582. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  24583. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  24584. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  24585. SceneComponentConstants.NAME_OCTREE = "Octree";
  24586. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  24587. SceneComponentConstants.NAME_AUDIO = "Audio";
  24588. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  24589. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24590. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  24591. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24592. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  24593. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  24594. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  24595. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  24596. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  24597. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  24598. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  24599. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  24600. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  24601. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  24602. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  24603. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  24604. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  24605. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  24606. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  24607. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  24608. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  24609. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  24610. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  24611. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  24612. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  24613. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  24614. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  24615. return SceneComponentConstants;
  24616. }());
  24617. BABYLON.SceneComponentConstants = SceneComponentConstants;
  24618. /**
  24619. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  24620. * @hidden
  24621. */
  24622. var Stage = /** @class */ (function (_super) {
  24623. __extends(Stage, _super);
  24624. /**
  24625. * Hide ctor from the rest of the world.
  24626. * @param items The items to add.
  24627. */
  24628. function Stage(items) {
  24629. return _super.apply(this, items) || this;
  24630. }
  24631. /**
  24632. * Creates a new Stage.
  24633. * @returns A new instance of a Stage
  24634. */
  24635. Stage.Create = function () {
  24636. return Object.create(Stage.prototype);
  24637. };
  24638. /**
  24639. * Registers a step in an ordered way in the targeted stage.
  24640. * @param index Defines the position to register the step in
  24641. * @param component Defines the component attached to the step
  24642. * @param action Defines the action to launch during the step
  24643. */
  24644. Stage.prototype.registerStep = function (index, component, action) {
  24645. var i = 0;
  24646. var maxIndex = Number.MAX_VALUE;
  24647. for (; i < this.length && i < maxIndex; i++) {
  24648. var step = this[i];
  24649. maxIndex = step.index;
  24650. }
  24651. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  24652. };
  24653. /**
  24654. * Clears all the steps from the stage.
  24655. */
  24656. Stage.prototype.clear = function () {
  24657. this.length = 0;
  24658. };
  24659. return Stage;
  24660. }(Array));
  24661. BABYLON.Stage = Stage;
  24662. })(BABYLON || (BABYLON = {}));
  24663. //# sourceMappingURL=babylon.sceneComponent.js.map
  24664. var BABYLON;
  24665. (function (BABYLON) {
  24666. /**
  24667. * Base class of the scene acting as a container for the different elements composing a scene.
  24668. * This class is dynamically extended by the different components of the scene increasing
  24669. * flexibility and reducing coupling
  24670. */
  24671. var AbstractScene = /** @class */ (function () {
  24672. function AbstractScene() {
  24673. /**
  24674. * Gets the list of root nodes (ie. nodes with no parent)
  24675. */
  24676. this.rootNodes = new Array();
  24677. /** All of the cameras added to this scene
  24678. * @see http://doc.babylonjs.com/babylon101/cameras
  24679. */
  24680. this.cameras = new Array();
  24681. /**
  24682. * All of the lights added to this scene
  24683. * @see http://doc.babylonjs.com/babylon101/lights
  24684. */
  24685. this.lights = new Array();
  24686. /**
  24687. * All of the (abstract) meshes added to this scene
  24688. */
  24689. this.meshes = new Array();
  24690. /**
  24691. * The list of skeletons added to the scene
  24692. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24693. */
  24694. this.skeletons = new Array();
  24695. /**
  24696. * All of the particle systems added to this scene
  24697. * @see http://doc.babylonjs.com/babylon101/particles
  24698. */
  24699. this.particleSystems = new Array();
  24700. /**
  24701. * Gets a list of Animations associated with the scene
  24702. */
  24703. this.animations = [];
  24704. /**
  24705. * All of the animation groups added to this scene
  24706. * @see http://doc.babylonjs.com/how_to/group
  24707. */
  24708. this.animationGroups = new Array();
  24709. /**
  24710. * All of the multi-materials added to this scene
  24711. * @see http://doc.babylonjs.com/how_to/multi_materials
  24712. */
  24713. this.multiMaterials = new Array();
  24714. /**
  24715. * All of the materials added to this scene
  24716. * @see http://doc.babylonjs.com/babylon101/materials
  24717. */
  24718. this.materials = new Array();
  24719. /**
  24720. * The list of morph target managers added to the scene
  24721. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24722. */
  24723. this.morphTargetManagers = new Array();
  24724. /**
  24725. * The list of geometries used in the scene.
  24726. */
  24727. this.geometries = new Array();
  24728. /**
  24729. * All of the tranform nodes added to this scene
  24730. * @see http://doc.babylonjs.com/how_to/transformnode
  24731. */
  24732. this.transformNodes = new Array();
  24733. /**
  24734. * ActionManagers available on the scene.
  24735. */
  24736. this.actionManagers = new Array();
  24737. /**
  24738. * Textures to keep.
  24739. */
  24740. this.textures = new Array();
  24741. }
  24742. /**
  24743. * Adds a parser in the list of available ones
  24744. * @param name Defines the name of the parser
  24745. * @param parser Defines the parser to add
  24746. */
  24747. AbstractScene.AddParser = function (name, parser) {
  24748. this._BabylonFileParsers[name] = parser;
  24749. };
  24750. /**
  24751. * Gets a general parser from the list of avaialble ones
  24752. * @param name Defines the name of the parser
  24753. * @returns the requested parser or null
  24754. */
  24755. AbstractScene.GetParser = function (name) {
  24756. if (this._BabylonFileParsers[name]) {
  24757. return this._BabylonFileParsers[name];
  24758. }
  24759. return null;
  24760. };
  24761. /**
  24762. * Adds n individual parser in the list of available ones
  24763. * @param name Defines the name of the parser
  24764. * @param parser Defines the parser to add
  24765. */
  24766. AbstractScene.AddIndividualParser = function (name, parser) {
  24767. this._IndividualBabylonFileParsers[name] = parser;
  24768. };
  24769. /**
  24770. * Gets an individual parser from the list of avaialble ones
  24771. * @param name Defines the name of the parser
  24772. * @returns the requested parser or null
  24773. */
  24774. AbstractScene.GetIndividualParser = function (name) {
  24775. if (this._IndividualBabylonFileParsers[name]) {
  24776. return this._IndividualBabylonFileParsers[name];
  24777. }
  24778. return null;
  24779. };
  24780. /**
  24781. * Parser json data and populate both a scene and its associated container object
  24782. * @param jsonData Defines the data to parse
  24783. * @param scene Defines the scene to parse the data for
  24784. * @param container Defines the container attached to the parsing sequence
  24785. * @param rootUrl Defines the root url of the data
  24786. */
  24787. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  24788. for (var parserName in this._BabylonFileParsers) {
  24789. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  24790. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  24791. }
  24792. }
  24793. };
  24794. /**
  24795. * Stores the list of available parsers in the application.
  24796. */
  24797. AbstractScene._BabylonFileParsers = {};
  24798. /**
  24799. * Stores the list of available individual parsers in the application.
  24800. */
  24801. AbstractScene._IndividualBabylonFileParsers = {};
  24802. return AbstractScene;
  24803. }());
  24804. BABYLON.AbstractScene = AbstractScene;
  24805. })(BABYLON || (BABYLON = {}));
  24806. //# sourceMappingURL=babylon.abstractScene.js.map
  24807. var BABYLON;
  24808. (function (BABYLON) {
  24809. /** @hidden */
  24810. var ClickInfo = /** @class */ (function () {
  24811. function ClickInfo() {
  24812. this._singleClick = false;
  24813. this._doubleClick = false;
  24814. this._hasSwiped = false;
  24815. this._ignore = false;
  24816. }
  24817. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24818. get: function () {
  24819. return this._singleClick;
  24820. },
  24821. set: function (b) {
  24822. this._singleClick = b;
  24823. },
  24824. enumerable: true,
  24825. configurable: true
  24826. });
  24827. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  24828. get: function () {
  24829. return this._doubleClick;
  24830. },
  24831. set: function (b) {
  24832. this._doubleClick = b;
  24833. },
  24834. enumerable: true,
  24835. configurable: true
  24836. });
  24837. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  24838. get: function () {
  24839. return this._hasSwiped;
  24840. },
  24841. set: function (b) {
  24842. this._hasSwiped = b;
  24843. },
  24844. enumerable: true,
  24845. configurable: true
  24846. });
  24847. Object.defineProperty(ClickInfo.prototype, "ignore", {
  24848. get: function () {
  24849. return this._ignore;
  24850. },
  24851. set: function (b) {
  24852. this._ignore = b;
  24853. },
  24854. enumerable: true,
  24855. configurable: true
  24856. });
  24857. return ClickInfo;
  24858. }());
  24859. /**
  24860. * This class is used by the onRenderingGroupObservable
  24861. */
  24862. var RenderingGroupInfo = /** @class */ (function () {
  24863. function RenderingGroupInfo() {
  24864. }
  24865. return RenderingGroupInfo;
  24866. }());
  24867. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24868. /**
  24869. * Represents a scene to be rendered by the engine.
  24870. * @see http://doc.babylonjs.com/features/scene
  24871. */
  24872. var Scene = /** @class */ (function (_super) {
  24873. __extends(Scene, _super);
  24874. /**
  24875. * Creates a new Scene
  24876. * @param engine defines the engine to use to render this scene
  24877. */
  24878. function Scene(engine) {
  24879. var _this = _super.call(this) || this;
  24880. // Members
  24881. /**
  24882. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24883. */
  24884. _this.autoClear = true;
  24885. /**
  24886. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24887. */
  24888. _this.autoClearDepthAndStencil = true;
  24889. /**
  24890. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24891. */
  24892. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24893. /**
  24894. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24895. */
  24896. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24897. _this._forceWireframe = false;
  24898. _this._forcePointsCloud = false;
  24899. /**
  24900. * Gets or sets a boolean indicating if animations are enabled
  24901. */
  24902. _this.animationsEnabled = true;
  24903. _this._animationPropertiesOverride = null;
  24904. /**
  24905. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24906. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24907. */
  24908. _this.useConstantAnimationDeltaTime = false;
  24909. /**
  24910. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24911. * Please note that it requires to run a ray cast through the scene on every frame
  24912. */
  24913. _this.constantlyUpdateMeshUnderPointer = false;
  24914. /**
  24915. * Defines the HTML cursor to use when hovering over interactive elements
  24916. */
  24917. _this.hoverCursor = "pointer";
  24918. /**
  24919. * Defines the HTML default cursor to use (empty by default)
  24920. */
  24921. _this.defaultCursor = "";
  24922. /**
  24923. * This is used to call preventDefault() on pointer down
  24924. * in order to block unwanted artifacts like system double clicks
  24925. */
  24926. _this.preventDefaultOnPointerDown = true;
  24927. // Metadata
  24928. /**
  24929. * Gets or sets user defined metadata
  24930. */
  24931. _this.metadata = null;
  24932. /**
  24933. * Use this array to add regular expressions used to disable offline support for specific urls
  24934. */
  24935. _this.disableOfflineSupportExceptionRules = new Array();
  24936. /**
  24937. * An event triggered when the scene is disposed.
  24938. */
  24939. _this.onDisposeObservable = new BABYLON.Observable();
  24940. _this._onDisposeObserver = null;
  24941. /**
  24942. * An event triggered before rendering the scene (right after animations and physics)
  24943. */
  24944. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24945. _this._onBeforeRenderObserver = null;
  24946. /**
  24947. * An event triggered after rendering the scene
  24948. */
  24949. _this.onAfterRenderObservable = new BABYLON.Observable();
  24950. _this._onAfterRenderObserver = null;
  24951. /**
  24952. * An event triggered before animating the scene
  24953. */
  24954. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24955. /**
  24956. * An event triggered after animations processing
  24957. */
  24958. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24959. /**
  24960. * An event triggered before draw calls are ready to be sent
  24961. */
  24962. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24963. /**
  24964. * An event triggered after draw calls have been sent
  24965. */
  24966. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24967. /**
  24968. * An event triggered when the scene is ready
  24969. */
  24970. _this.onReadyObservable = new BABYLON.Observable();
  24971. /**
  24972. * An event triggered before rendering a camera
  24973. */
  24974. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24975. _this._onBeforeCameraRenderObserver = null;
  24976. /**
  24977. * An event triggered after rendering a camera
  24978. */
  24979. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24980. _this._onAfterCameraRenderObserver = null;
  24981. /**
  24982. * An event triggered when active meshes evaluation is about to start
  24983. */
  24984. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24985. /**
  24986. * An event triggered when active meshes evaluation is done
  24987. */
  24988. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24989. /**
  24990. * An event triggered when particles rendering is about to start
  24991. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24992. */
  24993. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24994. /**
  24995. * An event triggered when particles rendering is done
  24996. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24997. */
  24998. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24999. /**
  25000. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  25001. */
  25002. _this.onDataLoadedObservable = new BABYLON.Observable();
  25003. /**
  25004. * An event triggered when a camera is created
  25005. */
  25006. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  25007. /**
  25008. * An event triggered when a camera is removed
  25009. */
  25010. _this.onCameraRemovedObservable = new BABYLON.Observable();
  25011. /**
  25012. * An event triggered when a light is created
  25013. */
  25014. _this.onNewLightAddedObservable = new BABYLON.Observable();
  25015. /**
  25016. * An event triggered when a light is removed
  25017. */
  25018. _this.onLightRemovedObservable = new BABYLON.Observable();
  25019. /**
  25020. * An event triggered when a geometry is created
  25021. */
  25022. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  25023. /**
  25024. * An event triggered when a geometry is removed
  25025. */
  25026. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  25027. /**
  25028. * An event triggered when a transform node is created
  25029. */
  25030. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  25031. /**
  25032. * An event triggered when a transform node is removed
  25033. */
  25034. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  25035. /**
  25036. * An event triggered when a mesh is created
  25037. */
  25038. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  25039. /**
  25040. * An event triggered when a mesh is removed
  25041. */
  25042. _this.onMeshRemovedObservable = new BABYLON.Observable();
  25043. /**
  25044. * An event triggered when a material is created
  25045. */
  25046. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  25047. /**
  25048. * An event triggered when a material is removed
  25049. */
  25050. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  25051. /**
  25052. * An event triggered when a texture is created
  25053. */
  25054. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  25055. /**
  25056. * An event triggered when a texture is removed
  25057. */
  25058. _this.onTextureRemovedObservable = new BABYLON.Observable();
  25059. /**
  25060. * An event triggered when render targets are about to be rendered
  25061. * Can happen multiple times per frame.
  25062. */
  25063. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  25064. /**
  25065. * An event triggered when render targets were rendered.
  25066. * Can happen multiple times per frame.
  25067. */
  25068. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  25069. /**
  25070. * An event triggered before calculating deterministic simulation step
  25071. */
  25072. _this.onBeforeStepObservable = new BABYLON.Observable();
  25073. /**
  25074. * An event triggered after calculating deterministic simulation step
  25075. */
  25076. _this.onAfterStepObservable = new BABYLON.Observable();
  25077. /**
  25078. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  25079. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25080. * 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)
  25081. */
  25082. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  25083. /**
  25084. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  25085. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25086. * 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)
  25087. */
  25088. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  25089. /**
  25090. * This Observable will when a mesh has been imported into the scene.
  25091. */
  25092. _this.onMeshImportedObservable = new BABYLON.Observable();
  25093. // Animations
  25094. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  25095. /**
  25096. * 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).
  25097. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  25098. */
  25099. _this.onPrePointerObservable = new BABYLON.Observable();
  25100. /**
  25101. * Observable event triggered each time an input event is received from the rendering canvas
  25102. */
  25103. _this.onPointerObservable = new BABYLON.Observable();
  25104. _this._meshPickProceed = false;
  25105. _this._currentPickResult = null;
  25106. _this._previousPickResult = null;
  25107. _this._totalPointersPressed = 0;
  25108. _this._doubleClickOccured = false;
  25109. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  25110. _this.cameraToUseForPointers = null;
  25111. _this._pointerX = 0;
  25112. _this._pointerY = 0;
  25113. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  25114. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  25115. _this._startingPointerTime = 0;
  25116. _this._previousStartingPointerTime = 0;
  25117. _this._pointerCaptures = {};
  25118. // Deterministic lockstep
  25119. _this._timeAccumulator = 0;
  25120. _this._currentStepId = 0;
  25121. _this._currentInternalStep = 0;
  25122. // Keyboard
  25123. /**
  25124. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  25125. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  25126. */
  25127. _this.onPreKeyboardObservable = new BABYLON.Observable();
  25128. /**
  25129. * Observable event triggered each time an keyboard event is received from the hosting window
  25130. */
  25131. _this.onKeyboardObservable = new BABYLON.Observable();
  25132. // Coordinates system
  25133. _this._useRightHandedSystem = false;
  25134. // Fog
  25135. _this._fogEnabled = true;
  25136. _this._fogMode = Scene.FOGMODE_NONE;
  25137. /**
  25138. * Gets or sets the fog color to use
  25139. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25140. * (Default is Color3(0.2, 0.2, 0.3))
  25141. */
  25142. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  25143. /**
  25144. * Gets or sets the fog density to use
  25145. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25146. * (Default is 0.1)
  25147. */
  25148. _this.fogDensity = 0.1;
  25149. /**
  25150. * Gets or sets the fog start distance to use
  25151. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25152. * (Default is 0)
  25153. */
  25154. _this.fogStart = 0;
  25155. /**
  25156. * Gets or sets the fog end distance to use
  25157. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25158. * (Default is 1000)
  25159. */
  25160. _this.fogEnd = 1000.0;
  25161. // Lights
  25162. _this._shadowsEnabled = true;
  25163. _this._lightsEnabled = true;
  25164. /** All of the active cameras added to this scene. */
  25165. _this.activeCameras = new Array();
  25166. // Textures
  25167. _this._texturesEnabled = true;
  25168. // Particles
  25169. /**
  25170. * Gets or sets a boolean indicating if particles are enabled on this scene
  25171. */
  25172. _this.particlesEnabled = true;
  25173. // Sprites
  25174. /**
  25175. * Gets or sets a boolean indicating if sprites are enabled on this scene
  25176. */
  25177. _this.spritesEnabled = true;
  25178. // Skeletons
  25179. _this._skeletonsEnabled = true;
  25180. // Lens flares
  25181. /**
  25182. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  25183. */
  25184. _this.lensFlaresEnabled = true;
  25185. // Collisions
  25186. /**
  25187. * Gets or sets a boolean indicating if collisions are enabled on this scene
  25188. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25189. */
  25190. _this.collisionsEnabled = true;
  25191. /**
  25192. * Defines the gravity applied to this scene (used only for collisions)
  25193. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25194. */
  25195. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  25196. // Postprocesses
  25197. /**
  25198. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  25199. */
  25200. _this.postProcessesEnabled = true;
  25201. /**
  25202. * The list of postprocesses added to the scene
  25203. */
  25204. _this.postProcesses = new Array();
  25205. // Customs render targets
  25206. /**
  25207. * Gets or sets a boolean indicating if render targets are enabled on this scene
  25208. */
  25209. _this.renderTargetsEnabled = true;
  25210. /**
  25211. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  25212. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  25213. */
  25214. _this.dumpNextRenderTargets = false;
  25215. /**
  25216. * The list of user defined render targets added to the scene
  25217. */
  25218. _this.customRenderTargets = new Array();
  25219. /**
  25220. * Gets the list of meshes imported to the scene through SceneLoader
  25221. */
  25222. _this.importedMeshesFiles = new Array();
  25223. // Probes
  25224. /**
  25225. * Gets or sets a boolean indicating if probes are enabled on this scene
  25226. */
  25227. _this.probesEnabled = true;
  25228. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  25229. // Procedural textures
  25230. /**
  25231. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  25232. */
  25233. _this.proceduralTexturesEnabled = true;
  25234. // Performance counters
  25235. _this._totalVertices = new BABYLON.PerfCounter();
  25236. /** @hidden */
  25237. _this._activeIndices = new BABYLON.PerfCounter();
  25238. /** @hidden */
  25239. _this._activeParticles = new BABYLON.PerfCounter();
  25240. /** @hidden */
  25241. _this._activeBones = new BABYLON.PerfCounter();
  25242. _this._animationTime = 0;
  25243. /**
  25244. * Gets or sets a general scale for animation speed
  25245. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  25246. */
  25247. _this.animationTimeScale = 1;
  25248. _this._renderId = 0;
  25249. _this._frameId = 0;
  25250. _this._executeWhenReadyTimeoutId = -1;
  25251. _this._intermediateRendering = false;
  25252. _this._viewUpdateFlag = -1;
  25253. _this._projectionUpdateFlag = -1;
  25254. _this._alternateViewUpdateFlag = -1;
  25255. _this._alternateProjectionUpdateFlag = -1;
  25256. /** @hidden */
  25257. _this._toBeDisposed = new Array(256);
  25258. _this._activeRequests = new Array();
  25259. _this._pendingData = new Array();
  25260. _this._isDisposed = false;
  25261. /**
  25262. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  25263. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  25264. */
  25265. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  25266. _this._activeMeshes = new BABYLON.SmartArray(256);
  25267. _this._processedMaterials = new BABYLON.SmartArray(256);
  25268. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  25269. /** @hidden */
  25270. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  25271. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  25272. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  25273. /** @hidden */
  25274. _this._activeAnimatables = new Array();
  25275. _this._transformMatrix = BABYLON.Matrix.Zero();
  25276. _this._useAlternateCameraConfiguration = false;
  25277. _this._alternateRendering = false;
  25278. /**
  25279. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  25280. * This is useful if there are more lights that the maximum simulteanous authorized
  25281. */
  25282. _this.requireLightSorting = false;
  25283. /**
  25284. * @hidden
  25285. * Backing store of defined scene components.
  25286. */
  25287. _this._components = [];
  25288. /**
  25289. * @hidden
  25290. * Backing store of defined scene components.
  25291. */
  25292. _this._serializableComponents = [];
  25293. /**
  25294. * List of components to register on the next registration step.
  25295. */
  25296. _this._transientComponents = [];
  25297. /**
  25298. * @hidden
  25299. * Defines the actions happening before camera updates.
  25300. */
  25301. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  25302. /**
  25303. * @hidden
  25304. * Defines the actions happening before clear the canvas.
  25305. */
  25306. _this._beforeClearStage = BABYLON.Stage.Create();
  25307. /**
  25308. * @hidden
  25309. * Defines the actions when collecting render targets for the frame.
  25310. */
  25311. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  25312. /**
  25313. * @hidden
  25314. * Defines the actions happening for one camera in the frame.
  25315. */
  25316. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  25317. /**
  25318. * @hidden
  25319. * Defines the actions happening during the per mesh ready checks.
  25320. */
  25321. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  25322. /**
  25323. * @hidden
  25324. * Defines the actions happening before evaluate active mesh checks.
  25325. */
  25326. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  25327. /**
  25328. * @hidden
  25329. * Defines the actions happening during the evaluate sub mesh checks.
  25330. */
  25331. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  25332. /**
  25333. * @hidden
  25334. * Defines the actions happening during the active mesh stage.
  25335. */
  25336. _this._activeMeshStage = BABYLON.Stage.Create();
  25337. /**
  25338. * @hidden
  25339. * Defines the actions happening during the per camera render target step.
  25340. */
  25341. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  25342. /**
  25343. * @hidden
  25344. * Defines the actions happening just before the active camera is drawing.
  25345. */
  25346. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  25347. /**
  25348. * @hidden
  25349. * Defines the actions happening just before a rendering group is drawing.
  25350. */
  25351. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  25352. /**
  25353. * @hidden
  25354. * Defines the actions happening just before a mesh is drawing.
  25355. */
  25356. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  25357. /**
  25358. * @hidden
  25359. * Defines the actions happening just after a mesh has been drawn.
  25360. */
  25361. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  25362. /**
  25363. * @hidden
  25364. * Defines the actions happening just after a rendering group has been drawn.
  25365. */
  25366. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  25367. /**
  25368. * @hidden
  25369. * Defines the actions happening just after the active camera has been drawn.
  25370. */
  25371. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  25372. /**
  25373. * @hidden
  25374. * Defines the actions happening just after rendering all cameras and computing intersections.
  25375. */
  25376. _this._afterRenderStage = BABYLON.Stage.Create();
  25377. /**
  25378. * @hidden
  25379. * Defines the actions happening when a pointer move event happens.
  25380. */
  25381. _this._pointerMoveStage = BABYLON.Stage.Create();
  25382. /**
  25383. * @hidden
  25384. * Defines the actions happening when a pointer down event happens.
  25385. */
  25386. _this._pointerDownStage = BABYLON.Stage.Create();
  25387. /**
  25388. * @hidden
  25389. * Defines the actions happening when a pointer up event happens.
  25390. */
  25391. _this._pointerUpStage = BABYLON.Stage.Create();
  25392. _this._defaultMeshCandidates = {
  25393. data: [],
  25394. length: 0
  25395. };
  25396. _this._defaultSubMeshCandidates = {
  25397. data: [],
  25398. length: 0
  25399. };
  25400. _this._activeMeshesFrozen = false;
  25401. /** @hidden */
  25402. _this._allowPostProcessClearColor = true;
  25403. /**
  25404. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  25405. */
  25406. _this.getDeterministicFrameTime = function () {
  25407. return 1000.0 / 60.0; // frame time in ms
  25408. };
  25409. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  25410. _this._blockMaterialDirtyMechanism = false;
  25411. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  25412. _this._engine.scenes.push(_this);
  25413. _this._uid = null;
  25414. _this._renderingManager = new BABYLON.RenderingManager(_this);
  25415. if (BABYLON.PostProcessManager) {
  25416. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  25417. }
  25418. if (BABYLON.Tools.IsWindowObjectExist()) {
  25419. _this.attachControl();
  25420. }
  25421. //collision coordinator initialization. For now legacy per default.
  25422. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  25423. // Uniform Buffer
  25424. _this._createUbo();
  25425. // Default Image processing definition
  25426. if (BABYLON.ImageProcessingConfiguration) {
  25427. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  25428. }
  25429. _this.setDefaultCandidateProviders();
  25430. return _this;
  25431. }
  25432. Object.defineProperty(Scene.prototype, "environmentTexture", {
  25433. /**
  25434. * Texture used in all pbr material as the reflection texture.
  25435. * As in the majority of the scene they are the same (exception for multi room and so on),
  25436. * this is easier to reference from here than from all the materials.
  25437. */
  25438. get: function () {
  25439. return this._environmentTexture;
  25440. },
  25441. /**
  25442. * Texture used in all pbr material as the reflection texture.
  25443. * As in the majority of the scene they are the same (exception for multi room and so on),
  25444. * this is easier to set here than in all the materials.
  25445. */
  25446. set: function (value) {
  25447. if (this._environmentTexture === value) {
  25448. return;
  25449. }
  25450. this._environmentTexture = value;
  25451. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25452. },
  25453. enumerable: true,
  25454. configurable: true
  25455. });
  25456. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  25457. /**
  25458. * Default image processing configuration used either in the rendering
  25459. * Forward main pass or through the imageProcessingPostProcess if present.
  25460. * As in the majority of the scene they are the same (exception for multi camera),
  25461. * this is easier to reference from here than from all the materials and post process.
  25462. *
  25463. * No setter as we it is a shared configuration, you can set the values instead.
  25464. */
  25465. get: function () {
  25466. return this._imageProcessingConfiguration;
  25467. },
  25468. enumerable: true,
  25469. configurable: true
  25470. });
  25471. Object.defineProperty(Scene.prototype, "forceWireframe", {
  25472. get: function () {
  25473. return this._forceWireframe;
  25474. },
  25475. /**
  25476. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  25477. */
  25478. set: function (value) {
  25479. if (this._forceWireframe === value) {
  25480. return;
  25481. }
  25482. this._forceWireframe = value;
  25483. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25484. },
  25485. enumerable: true,
  25486. configurable: true
  25487. });
  25488. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  25489. get: function () {
  25490. return this._forcePointsCloud;
  25491. },
  25492. /**
  25493. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  25494. */
  25495. set: function (value) {
  25496. if (this._forcePointsCloud === value) {
  25497. return;
  25498. }
  25499. this._forcePointsCloud = value;
  25500. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25501. },
  25502. enumerable: true,
  25503. configurable: true
  25504. });
  25505. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  25506. /**
  25507. * Gets or sets the animation properties override
  25508. */
  25509. get: function () {
  25510. return this._animationPropertiesOverride;
  25511. },
  25512. set: function (value) {
  25513. this._animationPropertiesOverride = value;
  25514. },
  25515. enumerable: true,
  25516. configurable: true
  25517. });
  25518. Object.defineProperty(Scene.prototype, "onDispose", {
  25519. /** Sets a function to be executed when this scene is disposed. */
  25520. set: function (callback) {
  25521. if (this._onDisposeObserver) {
  25522. this.onDisposeObservable.remove(this._onDisposeObserver);
  25523. }
  25524. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25525. },
  25526. enumerable: true,
  25527. configurable: true
  25528. });
  25529. Object.defineProperty(Scene.prototype, "beforeRender", {
  25530. /** Sets a function to be executed before rendering this scene */
  25531. set: function (callback) {
  25532. if (this._onBeforeRenderObserver) {
  25533. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25534. }
  25535. if (callback) {
  25536. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25537. }
  25538. },
  25539. enumerable: true,
  25540. configurable: true
  25541. });
  25542. Object.defineProperty(Scene.prototype, "afterRender", {
  25543. /** Sets a function to be executed after rendering this scene */
  25544. set: function (callback) {
  25545. if (this._onAfterRenderObserver) {
  25546. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25547. }
  25548. if (callback) {
  25549. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25550. }
  25551. },
  25552. enumerable: true,
  25553. configurable: true
  25554. });
  25555. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  25556. /** Sets a function to be executed before rendering a camera*/
  25557. set: function (callback) {
  25558. if (this._onBeforeCameraRenderObserver) {
  25559. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  25560. }
  25561. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  25562. },
  25563. enumerable: true,
  25564. configurable: true
  25565. });
  25566. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  25567. /** Sets a function to be executed after rendering a camera*/
  25568. set: function (callback) {
  25569. if (this._onAfterCameraRenderObserver) {
  25570. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  25571. }
  25572. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  25573. },
  25574. enumerable: true,
  25575. configurable: true
  25576. });
  25577. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  25578. /**
  25579. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  25580. */
  25581. get: function () {
  25582. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  25583. },
  25584. enumerable: true,
  25585. configurable: true
  25586. });
  25587. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  25588. get: function () {
  25589. return this._useRightHandedSystem;
  25590. },
  25591. /**
  25592. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  25593. */
  25594. set: function (value) {
  25595. if (this._useRightHandedSystem === value) {
  25596. return;
  25597. }
  25598. this._useRightHandedSystem = value;
  25599. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25600. },
  25601. enumerable: true,
  25602. configurable: true
  25603. });
  25604. /**
  25605. * Sets the step Id used by deterministic lock step
  25606. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25607. * @param newStepId defines the step Id
  25608. */
  25609. Scene.prototype.setStepId = function (newStepId) {
  25610. this._currentStepId = newStepId;
  25611. };
  25612. ;
  25613. /**
  25614. * Gets the step Id used by deterministic lock step
  25615. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25616. * @returns the step Id
  25617. */
  25618. Scene.prototype.getStepId = function () {
  25619. return this._currentStepId;
  25620. };
  25621. ;
  25622. /**
  25623. * Gets the internal step used by deterministic lock step
  25624. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25625. * @returns the internal step
  25626. */
  25627. Scene.prototype.getInternalStep = function () {
  25628. return this._currentInternalStep;
  25629. };
  25630. ;
  25631. Object.defineProperty(Scene.prototype, "fogEnabled", {
  25632. get: function () {
  25633. return this._fogEnabled;
  25634. },
  25635. /**
  25636. * Gets or sets a boolean indicating if fog is enabled on this scene
  25637. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25638. * (Default is true)
  25639. */
  25640. set: function (value) {
  25641. if (this._fogEnabled === value) {
  25642. return;
  25643. }
  25644. this._fogEnabled = value;
  25645. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25646. },
  25647. enumerable: true,
  25648. configurable: true
  25649. });
  25650. Object.defineProperty(Scene.prototype, "fogMode", {
  25651. get: function () {
  25652. return this._fogMode;
  25653. },
  25654. /**
  25655. * Gets or sets the fog mode to use
  25656. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25657. * | mode | value |
  25658. * | --- | --- |
  25659. * | FOGMODE_NONE | 0 |
  25660. * | FOGMODE_EXP | 1 |
  25661. * | FOGMODE_EXP2 | 2 |
  25662. * | FOGMODE_LINEAR | 3 |
  25663. */
  25664. set: function (value) {
  25665. if (this._fogMode === value) {
  25666. return;
  25667. }
  25668. this._fogMode = value;
  25669. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25670. },
  25671. enumerable: true,
  25672. configurable: true
  25673. });
  25674. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  25675. get: function () {
  25676. return this._shadowsEnabled;
  25677. },
  25678. /**
  25679. * Gets or sets a boolean indicating if shadows are enabled on this scene
  25680. */
  25681. set: function (value) {
  25682. if (this._shadowsEnabled === value) {
  25683. return;
  25684. }
  25685. this._shadowsEnabled = value;
  25686. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25687. },
  25688. enumerable: true,
  25689. configurable: true
  25690. });
  25691. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  25692. get: function () {
  25693. return this._lightsEnabled;
  25694. },
  25695. /**
  25696. * Gets or sets a boolean indicating if lights are enabled on this scene
  25697. */
  25698. set: function (value) {
  25699. if (this._lightsEnabled === value) {
  25700. return;
  25701. }
  25702. this._lightsEnabled = value;
  25703. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25704. },
  25705. enumerable: true,
  25706. configurable: true
  25707. });
  25708. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  25709. /** The default material used on meshes when no material is affected */
  25710. get: function () {
  25711. if (!this._defaultMaterial) {
  25712. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  25713. }
  25714. return this._defaultMaterial;
  25715. },
  25716. /** The default material used on meshes when no material is affected */
  25717. set: function (value) {
  25718. this._defaultMaterial = value;
  25719. },
  25720. enumerable: true,
  25721. configurable: true
  25722. });
  25723. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  25724. get: function () {
  25725. return this._texturesEnabled;
  25726. },
  25727. /**
  25728. * Gets or sets a boolean indicating if textures are enabled on this scene
  25729. */
  25730. set: function (value) {
  25731. if (this._texturesEnabled === value) {
  25732. return;
  25733. }
  25734. this._texturesEnabled = value;
  25735. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25736. },
  25737. enumerable: true,
  25738. configurable: true
  25739. });
  25740. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  25741. get: function () {
  25742. return this._skeletonsEnabled;
  25743. },
  25744. /**
  25745. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  25746. */
  25747. set: function (value) {
  25748. if (this._skeletonsEnabled === value) {
  25749. return;
  25750. }
  25751. this._skeletonsEnabled = value;
  25752. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  25753. },
  25754. enumerable: true,
  25755. configurable: true
  25756. });
  25757. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  25758. /** @hidden */
  25759. get: function () {
  25760. return this._alternateRendering;
  25761. },
  25762. enumerable: true,
  25763. configurable: true
  25764. });
  25765. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  25766. /**
  25767. * Gets the list of frustum planes (built from the active camera)
  25768. */
  25769. get: function () {
  25770. return this._frustumPlanes;
  25771. },
  25772. enumerable: true,
  25773. configurable: true
  25774. });
  25775. /**
  25776. * Registers the transient components if needed.
  25777. */
  25778. Scene.prototype._registerTransientComponents = function () {
  25779. // Register components that have been associated lately to the scene.
  25780. if (this._transientComponents.length > 0) {
  25781. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25782. var component = _a[_i];
  25783. component.register();
  25784. }
  25785. this._transientComponents = [];
  25786. }
  25787. };
  25788. /**
  25789. * @hidden
  25790. * Add a component to the scene.
  25791. * Note that the ccomponent could be registered on th next frame if this is called after
  25792. * the register component stage.
  25793. * @param component Defines the component to add to the scene
  25794. */
  25795. Scene.prototype._addComponent = function (component) {
  25796. this._components.push(component);
  25797. this._transientComponents.push(component);
  25798. var serializableComponent = component;
  25799. if (serializableComponent.addFromContainer) {
  25800. this._serializableComponents.push(serializableComponent);
  25801. }
  25802. };
  25803. /**
  25804. * @hidden
  25805. * Gets a component from the scene.
  25806. * @param name defines the name of the component to retrieve
  25807. * @returns the component or null if not present
  25808. */
  25809. Scene.prototype._getComponent = function (name) {
  25810. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25811. var component = _a[_i];
  25812. if (component.name === name) {
  25813. return component;
  25814. }
  25815. }
  25816. return null;
  25817. };
  25818. /**
  25819. * @hidden
  25820. */
  25821. Scene.prototype._getDefaultMeshCandidates = function () {
  25822. this._defaultMeshCandidates.data = this.meshes;
  25823. this._defaultMeshCandidates.length = this.meshes.length;
  25824. return this._defaultMeshCandidates;
  25825. };
  25826. /**
  25827. * @hidden
  25828. */
  25829. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  25830. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  25831. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  25832. return this._defaultSubMeshCandidates;
  25833. };
  25834. /**
  25835. * Sets the default candidate providers for the scene.
  25836. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  25837. * and getCollidingSubMeshCandidates to their default function
  25838. */
  25839. Scene.prototype.setDefaultCandidateProviders = function () {
  25840. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  25841. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25842. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25843. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25844. };
  25845. Object.defineProperty(Scene.prototype, "workerCollisions", {
  25846. /**
  25847. * Gets a boolean indicating if collisions are processed on a web worker
  25848. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  25849. */
  25850. get: function () {
  25851. return this._workerCollisions;
  25852. },
  25853. set: function (enabled) {
  25854. if (!BABYLON.CollisionCoordinatorLegacy) {
  25855. return;
  25856. }
  25857. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  25858. this._workerCollisions = enabled;
  25859. if (this.collisionCoordinator) {
  25860. this.collisionCoordinator.destroy();
  25861. }
  25862. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25863. this.collisionCoordinator.init(this);
  25864. },
  25865. enumerable: true,
  25866. configurable: true
  25867. });
  25868. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25869. /**
  25870. * Gets the mesh that is currently under the pointer
  25871. */
  25872. get: function () {
  25873. return this._pointerOverMesh;
  25874. },
  25875. enumerable: true,
  25876. configurable: true
  25877. });
  25878. Object.defineProperty(Scene.prototype, "pointerX", {
  25879. /**
  25880. * Gets the current on-screen X position of the pointer
  25881. */
  25882. get: function () {
  25883. return this._pointerX;
  25884. },
  25885. enumerable: true,
  25886. configurable: true
  25887. });
  25888. Object.defineProperty(Scene.prototype, "pointerY", {
  25889. /**
  25890. * Gets the current on-screen Y position of the pointer
  25891. */
  25892. get: function () {
  25893. return this._pointerY;
  25894. },
  25895. enumerable: true,
  25896. configurable: true
  25897. });
  25898. /**
  25899. * Gets the cached material (ie. the latest rendered one)
  25900. * @returns the cached material
  25901. */
  25902. Scene.prototype.getCachedMaterial = function () {
  25903. return this._cachedMaterial;
  25904. };
  25905. /**
  25906. * Gets the cached effect (ie. the latest rendered one)
  25907. * @returns the cached effect
  25908. */
  25909. Scene.prototype.getCachedEffect = function () {
  25910. return this._cachedEffect;
  25911. };
  25912. /**
  25913. * Gets the cached visibility state (ie. the latest rendered one)
  25914. * @returns the cached visibility state
  25915. */
  25916. Scene.prototype.getCachedVisibility = function () {
  25917. return this._cachedVisibility;
  25918. };
  25919. /**
  25920. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25921. * @param material defines the current material
  25922. * @param effect defines the current effect
  25923. * @param visibility defines the current visibility state
  25924. * @returns true if one parameter is not cached
  25925. */
  25926. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25927. if (visibility === void 0) { visibility = 1; }
  25928. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25929. };
  25930. /**
  25931. * Gets the engine associated with the scene
  25932. * @returns an Engine
  25933. */
  25934. Scene.prototype.getEngine = function () {
  25935. return this._engine;
  25936. };
  25937. /**
  25938. * Gets the total number of vertices rendered per frame
  25939. * @returns the total number of vertices rendered per frame
  25940. */
  25941. Scene.prototype.getTotalVertices = function () {
  25942. return this._totalVertices.current;
  25943. };
  25944. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25945. /**
  25946. * Gets the performance counter for total vertices
  25947. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25948. */
  25949. get: function () {
  25950. return this._totalVertices;
  25951. },
  25952. enumerable: true,
  25953. configurable: true
  25954. });
  25955. /**
  25956. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25957. * @returns the total number of active indices rendered per frame
  25958. */
  25959. Scene.prototype.getActiveIndices = function () {
  25960. return this._activeIndices.current;
  25961. };
  25962. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25963. /**
  25964. * Gets the performance counter for active indices
  25965. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25966. */
  25967. get: function () {
  25968. return this._activeIndices;
  25969. },
  25970. enumerable: true,
  25971. configurable: true
  25972. });
  25973. /**
  25974. * Gets the total number of active particles rendered per frame
  25975. * @returns the total number of active particles rendered per frame
  25976. */
  25977. Scene.prototype.getActiveParticles = function () {
  25978. return this._activeParticles.current;
  25979. };
  25980. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25981. /**
  25982. * Gets the performance counter for active particles
  25983. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25984. */
  25985. get: function () {
  25986. return this._activeParticles;
  25987. },
  25988. enumerable: true,
  25989. configurable: true
  25990. });
  25991. /**
  25992. * Gets the total number of active bones rendered per frame
  25993. * @returns the total number of active bones rendered per frame
  25994. */
  25995. Scene.prototype.getActiveBones = function () {
  25996. return this._activeBones.current;
  25997. };
  25998. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25999. /**
  26000. * Gets the performance counter for active bones
  26001. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26002. */
  26003. get: function () {
  26004. return this._activeBones;
  26005. },
  26006. enumerable: true,
  26007. configurable: true
  26008. });
  26009. /** @hidden */
  26010. Scene.prototype.getInterFramePerfCounter = function () {
  26011. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26012. return 0;
  26013. };
  26014. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  26015. /** @hidden */
  26016. get: function () {
  26017. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26018. return null;
  26019. },
  26020. enumerable: true,
  26021. configurable: true
  26022. });
  26023. /** @hidden */
  26024. Scene.prototype.getLastFrameDuration = function () {
  26025. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  26026. return 0;
  26027. };
  26028. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  26029. /** @hidden */
  26030. get: function () {
  26031. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26032. return null;
  26033. },
  26034. enumerable: true,
  26035. configurable: true
  26036. });
  26037. /** @hidden */
  26038. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  26039. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  26040. return 0;
  26041. };
  26042. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  26043. /** @hidden */
  26044. get: function () {
  26045. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26046. return null;
  26047. },
  26048. enumerable: true,
  26049. configurable: true
  26050. });
  26051. /**
  26052. * Gets the array of active meshes
  26053. * @returns an array of AbstractMesh
  26054. */
  26055. Scene.prototype.getActiveMeshes = function () {
  26056. return this._activeMeshes;
  26057. };
  26058. /** @hidden */
  26059. Scene.prototype.getRenderTargetsDuration = function () {
  26060. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  26061. return 0;
  26062. };
  26063. /** @hidden */
  26064. Scene.prototype.getRenderDuration = function () {
  26065. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  26066. return 0;
  26067. };
  26068. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  26069. /** @hidden */
  26070. get: function () {
  26071. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26072. return null;
  26073. },
  26074. enumerable: true,
  26075. configurable: true
  26076. });
  26077. /** @hidden */
  26078. Scene.prototype.getParticlesDuration = function () {
  26079. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  26080. return 0;
  26081. };
  26082. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  26083. /** @hidden */
  26084. get: function () {
  26085. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26086. return null;
  26087. },
  26088. enumerable: true,
  26089. configurable: true
  26090. });
  26091. /** @hidden */
  26092. Scene.prototype.getSpritesDuration = function () {
  26093. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  26094. return 0;
  26095. };
  26096. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  26097. /** @hidden */
  26098. get: function () {
  26099. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  26100. return null;
  26101. },
  26102. enumerable: true,
  26103. configurable: true
  26104. });
  26105. /**
  26106. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  26107. * @returns a number
  26108. */
  26109. Scene.prototype.getAnimationRatio = function () {
  26110. return this._animationRatio !== undefined ? this._animationRatio : 1;
  26111. };
  26112. /**
  26113. * Gets an unique Id for the current render phase
  26114. * @returns a number
  26115. */
  26116. Scene.prototype.getRenderId = function () {
  26117. return this._renderId;
  26118. };
  26119. /**
  26120. * Gets an unique Id for the current frame
  26121. * @returns a number
  26122. */
  26123. Scene.prototype.getFrameId = function () {
  26124. return this._frameId;
  26125. };
  26126. /** Call this function if you want to manually increment the render Id*/
  26127. Scene.prototype.incrementRenderId = function () {
  26128. this._renderId++;
  26129. };
  26130. Scene.prototype._updatePointerPosition = function (evt) {
  26131. var canvasRect = this._engine.getRenderingCanvasClientRect();
  26132. if (!canvasRect) {
  26133. return;
  26134. }
  26135. this._pointerX = evt.clientX - canvasRect.left;
  26136. this._pointerY = evt.clientY - canvasRect.top;
  26137. this._unTranslatedPointerX = this._pointerX;
  26138. this._unTranslatedPointerY = this._pointerY;
  26139. };
  26140. Scene.prototype._createUbo = function () {
  26141. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26142. this._sceneUbo.addUniform("viewProjection", 16);
  26143. this._sceneUbo.addUniform("view", 16);
  26144. };
  26145. Scene.prototype._createAlternateUbo = function () {
  26146. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26147. this._alternateSceneUbo.addUniform("viewProjection", 16);
  26148. this._alternateSceneUbo.addUniform("view", 16);
  26149. };
  26150. // Pointers handling
  26151. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  26152. if (pointerInfo.pickInfo) {
  26153. if (!pointerInfo.pickInfo.ray) {
  26154. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  26155. }
  26156. }
  26157. };
  26158. /**
  26159. * Use this method to simulate a pointer move on a mesh
  26160. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26161. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26162. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26163. * @returns the current scene
  26164. */
  26165. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  26166. var evt = new PointerEvent("pointermove", pointerEventInit);
  26167. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  26168. return this;
  26169. }
  26170. return this._processPointerMove(pickResult, evt);
  26171. };
  26172. Scene.prototype._processPointerMove = function (pickResult, evt) {
  26173. var canvas = this._engine.getRenderingCanvas();
  26174. if (!canvas) {
  26175. return this;
  26176. }
  26177. // Restore pointer
  26178. canvas.style.cursor = this.defaultCursor;
  26179. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  26180. if (isMeshPicked) {
  26181. this.setPointerOverMesh(pickResult.pickedMesh);
  26182. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  26183. if (this._pointerOverMesh.actionManager.hoverCursor) {
  26184. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  26185. }
  26186. else {
  26187. canvas.style.cursor = this.hoverCursor;
  26188. }
  26189. }
  26190. }
  26191. else {
  26192. this.setPointerOverMesh(null);
  26193. }
  26194. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  26195. var step = _a[_i];
  26196. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  26197. }
  26198. if (pickResult) {
  26199. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  26200. if (this.onPointerMove) {
  26201. this.onPointerMove(evt, pickResult, type);
  26202. }
  26203. if (this.onPointerObservable.hasObservers()) {
  26204. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26205. this._setRayOnPointerInfo(pi);
  26206. this.onPointerObservable.notifyObservers(pi, type);
  26207. }
  26208. }
  26209. return this;
  26210. };
  26211. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  26212. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  26213. if (pickResult) {
  26214. pi.ray = pickResult.ray;
  26215. }
  26216. this.onPrePointerObservable.notifyObservers(pi, type);
  26217. if (pi.skipOnPointerObservable) {
  26218. return true;
  26219. }
  26220. else {
  26221. return false;
  26222. }
  26223. };
  26224. /**
  26225. * Use this method to simulate a pointer down on a mesh
  26226. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26227. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26228. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26229. * @returns the current scene
  26230. */
  26231. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  26232. var evt = new PointerEvent("pointerdown", pointerEventInit);
  26233. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26234. return this;
  26235. }
  26236. return this._processPointerDown(pickResult, evt);
  26237. };
  26238. Scene.prototype._processPointerDown = function (pickResult, evt) {
  26239. var _this = this;
  26240. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  26241. this._pickedDownMesh = pickResult.pickedMesh;
  26242. var actionManager = pickResult.pickedMesh.actionManager;
  26243. if (actionManager) {
  26244. if (actionManager.hasPickTriggers) {
  26245. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26246. switch (evt.button) {
  26247. case 0:
  26248. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26249. break;
  26250. case 1:
  26251. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26252. break;
  26253. case 2:
  26254. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26255. break;
  26256. }
  26257. }
  26258. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  26259. window.setTimeout(function () {
  26260. 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);
  26261. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  26262. if (_this._totalPointersPressed !== 0 &&
  26263. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  26264. !_this._isPointerSwiping()) {
  26265. _this._startingPointerTime = 0;
  26266. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26267. }
  26268. }
  26269. }, Scene.LongPressDelay);
  26270. }
  26271. }
  26272. }
  26273. else {
  26274. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  26275. var step = _a[_i];
  26276. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26277. }
  26278. }
  26279. if (pickResult) {
  26280. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  26281. if (this.onPointerDown) {
  26282. this.onPointerDown(evt, pickResult, type);
  26283. }
  26284. if (this.onPointerObservable.hasObservers()) {
  26285. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26286. this._setRayOnPointerInfo(pi);
  26287. this.onPointerObservable.notifyObservers(pi, type);
  26288. }
  26289. }
  26290. return this;
  26291. };
  26292. /**
  26293. * Use this method to simulate a pointer up on a mesh
  26294. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26295. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26296. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26297. * @returns the current scene
  26298. */
  26299. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  26300. var evt = new PointerEvent("pointerup", pointerEventInit);
  26301. var clickInfo = new ClickInfo();
  26302. clickInfo.singleClick = true;
  26303. clickInfo.ignore = true;
  26304. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26305. return this;
  26306. }
  26307. return this._processPointerUp(pickResult, evt, clickInfo);
  26308. };
  26309. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  26310. if (pickResult && pickResult && pickResult.pickedMesh) {
  26311. this._pickedUpMesh = pickResult.pickedMesh;
  26312. if (this._pickedDownMesh === this._pickedUpMesh) {
  26313. if (this.onPointerPick) {
  26314. this.onPointerPick(evt, pickResult);
  26315. }
  26316. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  26317. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  26318. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  26319. this._setRayOnPointerInfo(pi);
  26320. this.onPointerObservable.notifyObservers(pi, type_1);
  26321. }
  26322. }
  26323. if (pickResult.pickedMesh.actionManager) {
  26324. if (clickInfo.ignore) {
  26325. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26326. }
  26327. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  26328. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26329. }
  26330. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26331. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26332. }
  26333. }
  26334. }
  26335. else {
  26336. if (!clickInfo.ignore) {
  26337. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  26338. var step = _a[_i];
  26339. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26340. }
  26341. }
  26342. }
  26343. if (this._pickedDownMesh &&
  26344. this._pickedDownMesh.actionManager &&
  26345. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  26346. this._pickedDownMesh !== this._pickedUpMesh) {
  26347. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  26348. }
  26349. var type = BABYLON.PointerEventTypes.POINTERUP;
  26350. if (this.onPointerObservable.hasObservers()) {
  26351. if (!clickInfo.ignore) {
  26352. if (!clickInfo.hasSwiped) {
  26353. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26354. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  26355. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  26356. this._setRayOnPointerInfo(pi);
  26357. this.onPointerObservable.notifyObservers(pi, type_2);
  26358. }
  26359. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26360. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  26361. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  26362. this._setRayOnPointerInfo(pi);
  26363. this.onPointerObservable.notifyObservers(pi, type_3);
  26364. }
  26365. }
  26366. }
  26367. else {
  26368. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26369. this._setRayOnPointerInfo(pi);
  26370. this.onPointerObservable.notifyObservers(pi, type);
  26371. }
  26372. }
  26373. if (this.onPointerUp) {
  26374. this.onPointerUp(evt, pickResult, type);
  26375. }
  26376. return this;
  26377. };
  26378. /**
  26379. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  26380. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  26381. * @returns true if the pointer was captured
  26382. */
  26383. Scene.prototype.isPointerCaptured = function (pointerId) {
  26384. if (pointerId === void 0) { pointerId = 0; }
  26385. return this._pointerCaptures[pointerId];
  26386. };
  26387. /** @hidden */
  26388. Scene.prototype._isPointerSwiping = function () {
  26389. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  26390. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  26391. };
  26392. /**
  26393. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  26394. * @param attachUp defines if you want to attach events to pointerup
  26395. * @param attachDown defines if you want to attach events to pointerdown
  26396. * @param attachMove defines if you want to attach events to pointermove
  26397. */
  26398. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  26399. var _this = this;
  26400. if (attachUp === void 0) { attachUp = true; }
  26401. if (attachDown === void 0) { attachDown = true; }
  26402. if (attachMove === void 0) { attachMove = true; }
  26403. this._initActionManager = function (act, clickInfo) {
  26404. if (!_this._meshPickProceed) {
  26405. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26406. _this._currentPickResult = pickResult;
  26407. if (pickResult) {
  26408. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  26409. }
  26410. _this._meshPickProceed = true;
  26411. }
  26412. return act;
  26413. };
  26414. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  26415. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  26416. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  26417. btn !== _this._previousButtonPressed) {
  26418. _this._doubleClickOccured = false;
  26419. clickInfo.singleClick = true;
  26420. clickInfo.ignore = false;
  26421. cb(clickInfo, _this._currentPickResult);
  26422. }
  26423. };
  26424. this._initClickEvent = function (obs1, obs2, evt, cb) {
  26425. var clickInfo = new ClickInfo();
  26426. _this._currentPickResult = null;
  26427. var act = null;
  26428. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  26429. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  26430. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26431. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  26432. act = _this._initActionManager(act, clickInfo);
  26433. if (act)
  26434. checkPicking = act.hasPickTriggers;
  26435. }
  26436. if (checkPicking) {
  26437. var btn = evt.button;
  26438. clickInfo.hasSwiped = _this._isPointerSwiping();
  26439. if (!clickInfo.hasSwiped) {
  26440. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  26441. if (!checkSingleClickImmediately) {
  26442. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  26443. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26444. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26445. act = _this._initActionManager(act, clickInfo);
  26446. if (act)
  26447. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26448. }
  26449. }
  26450. if (checkSingleClickImmediately) {
  26451. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  26452. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  26453. btn !== _this._previousButtonPressed) {
  26454. clickInfo.singleClick = true;
  26455. cb(clickInfo, _this._currentPickResult);
  26456. }
  26457. }
  26458. // at least one double click is required to be check and exclusive double click is enabled
  26459. else {
  26460. // wait that no double click has been raised during the double click delay
  26461. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26462. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  26463. }
  26464. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  26465. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26466. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26467. act = _this._initActionManager(act, clickInfo);
  26468. if (act)
  26469. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26470. }
  26471. if (checkDoubleClick) {
  26472. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  26473. if (btn === _this._previousButtonPressed &&
  26474. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  26475. !_this._doubleClickOccured) {
  26476. // pointer has not moved for 2 clicks, it's a double click
  26477. if (!clickInfo.hasSwiped &&
  26478. !_this._isPointerSwiping()) {
  26479. _this._previousStartingPointerTime = 0;
  26480. _this._doubleClickOccured = true;
  26481. clickInfo.doubleClick = true;
  26482. clickInfo.ignore = false;
  26483. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  26484. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26485. }
  26486. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26487. cb(clickInfo, _this._currentPickResult);
  26488. }
  26489. // if the two successive clicks are too far, it's just two simple clicks
  26490. else {
  26491. _this._doubleClickOccured = false;
  26492. _this._previousStartingPointerTime = _this._startingPointerTime;
  26493. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26494. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26495. _this._previousButtonPressed = btn;
  26496. if (Scene.ExclusiveDoubleClickMode) {
  26497. if (_this._previousDelayedSimpleClickTimeout) {
  26498. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26499. }
  26500. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26501. cb(clickInfo, _this._previousPickResult);
  26502. }
  26503. else {
  26504. cb(clickInfo, _this._currentPickResult);
  26505. }
  26506. }
  26507. }
  26508. // just the first click of the double has been raised
  26509. else {
  26510. _this._doubleClickOccured = false;
  26511. _this._previousStartingPointerTime = _this._startingPointerTime;
  26512. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26513. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26514. _this._previousButtonPressed = btn;
  26515. }
  26516. }
  26517. }
  26518. }
  26519. clickInfo.ignore = true;
  26520. cb(clickInfo, _this._currentPickResult);
  26521. };
  26522. this._onPointerMove = function (evt) {
  26523. _this._updatePointerPosition(evt);
  26524. // PreObservable support
  26525. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  26526. return;
  26527. }
  26528. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26529. return;
  26530. }
  26531. if (!_this.pointerMovePredicate) {
  26532. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  26533. }
  26534. // Meshes
  26535. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  26536. _this._processPointerMove(pickResult, evt);
  26537. };
  26538. this._onPointerDown = function (evt) {
  26539. _this._totalPointersPressed++;
  26540. _this._pickedDownMesh = null;
  26541. _this._meshPickProceed = false;
  26542. _this._updatePointerPosition(evt);
  26543. if (_this.preventDefaultOnPointerDown && canvas) {
  26544. evt.preventDefault();
  26545. canvas.focus();
  26546. }
  26547. // PreObservable support
  26548. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26549. return;
  26550. }
  26551. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26552. return;
  26553. }
  26554. _this._pointerCaptures[evt.pointerId] = true;
  26555. _this._startingPointerPosition.x = _this._pointerX;
  26556. _this._startingPointerPosition.y = _this._pointerY;
  26557. _this._startingPointerTime = Date.now();
  26558. if (!_this.pointerDownPredicate) {
  26559. _this.pointerDownPredicate = function (mesh) {
  26560. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26561. };
  26562. }
  26563. // Meshes
  26564. _this._pickedDownMesh = null;
  26565. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26566. _this._processPointerDown(pickResult, evt);
  26567. };
  26568. this._onPointerUp = function (evt) {
  26569. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  26570. return; // So we need to test it the pointer down was pressed before.
  26571. }
  26572. _this._totalPointersPressed--;
  26573. _this._pickedUpMesh = null;
  26574. _this._meshPickProceed = false;
  26575. _this._updatePointerPosition(evt);
  26576. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  26577. // PreObservable support
  26578. if (_this.onPrePointerObservable.hasObservers()) {
  26579. if (!clickInfo.ignore) {
  26580. if (!clickInfo.hasSwiped) {
  26581. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26582. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  26583. return;
  26584. }
  26585. }
  26586. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26587. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26588. return;
  26589. }
  26590. }
  26591. }
  26592. }
  26593. else {
  26594. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26595. return;
  26596. }
  26597. }
  26598. }
  26599. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26600. return;
  26601. }
  26602. _this._pointerCaptures[evt.pointerId] = false;
  26603. if (!_this.pointerUpPredicate) {
  26604. _this.pointerUpPredicate = function (mesh) {
  26605. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26606. };
  26607. }
  26608. // Meshes
  26609. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  26610. _this._initActionManager(null, clickInfo);
  26611. }
  26612. if (!pickResult) {
  26613. pickResult = _this._currentPickResult;
  26614. }
  26615. _this._processPointerUp(pickResult, evt, clickInfo);
  26616. _this._previousPickResult = _this._currentPickResult;
  26617. });
  26618. };
  26619. this._onKeyDown = function (evt) {
  26620. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  26621. if (_this.onPreKeyboardObservable.hasObservers()) {
  26622. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26623. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26624. if (pi.skipOnPointerObservable) {
  26625. return;
  26626. }
  26627. }
  26628. if (_this.onKeyboardObservable.hasObservers()) {
  26629. var pi = new BABYLON.KeyboardInfo(type, evt);
  26630. _this.onKeyboardObservable.notifyObservers(pi, type);
  26631. }
  26632. if (_this.actionManager) {
  26633. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26634. }
  26635. };
  26636. this._onKeyUp = function (evt) {
  26637. var type = BABYLON.KeyboardEventTypes.KEYUP;
  26638. if (_this.onPreKeyboardObservable.hasObservers()) {
  26639. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26640. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26641. if (pi.skipOnPointerObservable) {
  26642. return;
  26643. }
  26644. }
  26645. if (_this.onKeyboardObservable.hasObservers()) {
  26646. var pi = new BABYLON.KeyboardInfo(type, evt);
  26647. _this.onKeyboardObservable.notifyObservers(pi, type);
  26648. }
  26649. if (_this.actionManager) {
  26650. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26651. }
  26652. };
  26653. var engine = this.getEngine();
  26654. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  26655. if (!canvas) {
  26656. return;
  26657. }
  26658. canvas.addEventListener("keydown", _this._onKeyDown, false);
  26659. canvas.addEventListener("keyup", _this._onKeyUp, false);
  26660. });
  26661. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  26662. if (!canvas) {
  26663. return;
  26664. }
  26665. canvas.removeEventListener("keydown", _this._onKeyDown);
  26666. canvas.removeEventListener("keyup", _this._onKeyUp);
  26667. });
  26668. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26669. var canvas = this._engine.getRenderingCanvas();
  26670. if (!canvas) {
  26671. return;
  26672. }
  26673. if (attachMove) {
  26674. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  26675. // Wheel
  26676. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  26677. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  26678. }
  26679. if (attachDown) {
  26680. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  26681. }
  26682. if (attachUp) {
  26683. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  26684. }
  26685. canvas.tabIndex = 1;
  26686. };
  26687. /** Detaches all event handlers*/
  26688. Scene.prototype.detachControl = function () {
  26689. var engine = this.getEngine();
  26690. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26691. var canvas = engine.getRenderingCanvas();
  26692. if (!canvas) {
  26693. return;
  26694. }
  26695. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  26696. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  26697. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  26698. if (this._onCanvasBlurObserver) {
  26699. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  26700. }
  26701. if (this._onCanvasFocusObserver) {
  26702. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  26703. }
  26704. // Wheel
  26705. canvas.removeEventListener('mousewheel', this._onPointerMove);
  26706. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  26707. // Keyboard
  26708. canvas.removeEventListener("keydown", this._onKeyDown);
  26709. canvas.removeEventListener("keyup", this._onKeyUp);
  26710. // Observables
  26711. this.onKeyboardObservable.clear();
  26712. this.onPreKeyboardObservable.clear();
  26713. this.onPointerObservable.clear();
  26714. this.onPrePointerObservable.clear();
  26715. };
  26716. /**
  26717. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  26718. * Delay loaded resources are not taking in account
  26719. * @return true if all required resources are ready
  26720. */
  26721. Scene.prototype.isReady = function () {
  26722. if (this._isDisposed) {
  26723. return false;
  26724. }
  26725. if (this._pendingData.length > 0) {
  26726. return false;
  26727. }
  26728. var index;
  26729. var engine = this.getEngine();
  26730. // Geometries
  26731. for (index = 0; index < this.geometries.length; index++) {
  26732. var geometry = this.geometries[index];
  26733. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26734. return false;
  26735. }
  26736. }
  26737. // Meshes
  26738. for (index = 0; index < this.meshes.length; index++) {
  26739. var mesh = this.meshes[index];
  26740. if (!mesh.isEnabled()) {
  26741. continue;
  26742. }
  26743. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26744. continue;
  26745. }
  26746. if (!mesh.isReady(true)) {
  26747. return false;
  26748. }
  26749. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26750. // Is Ready For Mesh
  26751. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26752. var step = _a[_i];
  26753. if (!step.action(mesh, hardwareInstancedRendering)) {
  26754. return false;
  26755. }
  26756. }
  26757. }
  26758. // Post-processes
  26759. if (this.activeCameras && this.activeCameras.length > 0) {
  26760. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26761. var camera = _c[_b];
  26762. if (!camera.isReady(true)) {
  26763. return false;
  26764. }
  26765. }
  26766. }
  26767. else if (this.activeCamera) {
  26768. if (!this.activeCamera.isReady(true)) {
  26769. return false;
  26770. }
  26771. }
  26772. // Particles
  26773. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26774. var particleSystem = _e[_d];
  26775. if (!particleSystem.isReady()) {
  26776. return false;
  26777. }
  26778. }
  26779. return true;
  26780. };
  26781. /** Resets all cached information relative to material (including effect and visibility) */
  26782. Scene.prototype.resetCachedMaterial = function () {
  26783. this._cachedMaterial = null;
  26784. this._cachedEffect = null;
  26785. this._cachedVisibility = null;
  26786. };
  26787. /**
  26788. * Registers a function to be called before every frame render
  26789. * @param func defines the function to register
  26790. */
  26791. Scene.prototype.registerBeforeRender = function (func) {
  26792. this.onBeforeRenderObservable.add(func);
  26793. };
  26794. /**
  26795. * Unregisters a function called before every frame render
  26796. * @param func defines the function to unregister
  26797. */
  26798. Scene.prototype.unregisterBeforeRender = function (func) {
  26799. this.onBeforeRenderObservable.removeCallback(func);
  26800. };
  26801. /**
  26802. * Registers a function to be called after every frame render
  26803. * @param func defines the function to register
  26804. */
  26805. Scene.prototype.registerAfterRender = function (func) {
  26806. this.onAfterRenderObservable.add(func);
  26807. };
  26808. /**
  26809. * Unregisters a function called after every frame render
  26810. * @param func defines the function to unregister
  26811. */
  26812. Scene.prototype.unregisterAfterRender = function (func) {
  26813. this.onAfterRenderObservable.removeCallback(func);
  26814. };
  26815. Scene.prototype._executeOnceBeforeRender = function (func) {
  26816. var _this = this;
  26817. var execFunc = function () {
  26818. func();
  26819. setTimeout(function () {
  26820. _this.unregisterBeforeRender(execFunc);
  26821. });
  26822. };
  26823. this.registerBeforeRender(execFunc);
  26824. };
  26825. /**
  26826. * The provided function will run before render once and will be disposed afterwards.
  26827. * A timeout delay can be provided so that the function will be executed in N ms.
  26828. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26829. * @param func The function to be executed.
  26830. * @param timeout optional delay in ms
  26831. */
  26832. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26833. var _this = this;
  26834. if (timeout !== undefined) {
  26835. setTimeout(function () {
  26836. _this._executeOnceBeforeRender(func);
  26837. }, timeout);
  26838. }
  26839. else {
  26840. this._executeOnceBeforeRender(func);
  26841. }
  26842. };
  26843. /** @hidden */
  26844. Scene.prototype._addPendingData = function (data) {
  26845. this._pendingData.push(data);
  26846. };
  26847. /** @hidden */
  26848. Scene.prototype._removePendingData = function (data) {
  26849. var wasLoading = this.isLoading;
  26850. var index = this._pendingData.indexOf(data);
  26851. if (index !== -1) {
  26852. this._pendingData.splice(index, 1);
  26853. }
  26854. if (wasLoading && !this.isLoading) {
  26855. this.onDataLoadedObservable.notifyObservers(this);
  26856. }
  26857. };
  26858. /**
  26859. * Returns the number of items waiting to be loaded
  26860. * @returns the number of items waiting to be loaded
  26861. */
  26862. Scene.prototype.getWaitingItemsCount = function () {
  26863. return this._pendingData.length;
  26864. };
  26865. Object.defineProperty(Scene.prototype, "isLoading", {
  26866. /**
  26867. * Returns a boolean indicating if the scene is still loading data
  26868. */
  26869. get: function () {
  26870. return this._pendingData.length > 0;
  26871. },
  26872. enumerable: true,
  26873. configurable: true
  26874. });
  26875. /**
  26876. * Registers a function to be executed when the scene is ready
  26877. * @param {Function} func - the function to be executed
  26878. */
  26879. Scene.prototype.executeWhenReady = function (func) {
  26880. var _this = this;
  26881. this.onReadyObservable.add(func);
  26882. if (this._executeWhenReadyTimeoutId !== -1) {
  26883. return;
  26884. }
  26885. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26886. _this._checkIsReady();
  26887. }, 150);
  26888. };
  26889. /**
  26890. * Returns a promise that resolves when the scene is ready
  26891. * @returns A promise that resolves when the scene is ready
  26892. */
  26893. Scene.prototype.whenReadyAsync = function () {
  26894. var _this = this;
  26895. return new Promise(function (resolve) {
  26896. _this.executeWhenReady(function () {
  26897. resolve();
  26898. });
  26899. });
  26900. };
  26901. /** @hidden */
  26902. Scene.prototype._checkIsReady = function () {
  26903. var _this = this;
  26904. this._registerTransientComponents();
  26905. if (this.isReady()) {
  26906. this.onReadyObservable.notifyObservers(this);
  26907. this.onReadyObservable.clear();
  26908. this._executeWhenReadyTimeoutId = -1;
  26909. return;
  26910. }
  26911. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26912. _this._checkIsReady();
  26913. }, 150);
  26914. };
  26915. // Animations
  26916. /**
  26917. * Will start the animation sequence of a given target
  26918. * @param target defines the target
  26919. * @param from defines from which frame should animation start
  26920. * @param to defines until which frame should animation run.
  26921. * @param weight defines the weight to apply to the animation (1.0 by default)
  26922. * @param loop defines if the animation loops
  26923. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26924. * @param onAnimationEnd defines the function to be executed when the animation ends
  26925. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26926. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26927. * @returns the animatable object created for this animation
  26928. */
  26929. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  26930. if (weight === void 0) { weight = 1.0; }
  26931. if (speedRatio === void 0) { speedRatio = 1.0; }
  26932. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  26933. returnedAnimatable.weight = weight;
  26934. return returnedAnimatable;
  26935. };
  26936. /**
  26937. * Will start the animation sequence of a given target
  26938. * @param target defines the target
  26939. * @param from defines from which frame should animation start
  26940. * @param to defines until which frame should animation run.
  26941. * @param loop defines if the animation loops
  26942. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26943. * @param onAnimationEnd defines the function to be executed when the animation ends
  26944. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26945. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26946. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26947. * @returns the animatable object created for this animation
  26948. */
  26949. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26950. if (speedRatio === void 0) { speedRatio = 1.0; }
  26951. if (stopCurrent === void 0) { stopCurrent = true; }
  26952. if (from > to && speedRatio > 0) {
  26953. speedRatio *= -1;
  26954. }
  26955. if (stopCurrent) {
  26956. this.stopAnimation(target, undefined, targetMask);
  26957. }
  26958. if (!animatable) {
  26959. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26960. }
  26961. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26962. // Local animations
  26963. if (target.animations && shouldRunTargetAnimations) {
  26964. animatable.appendAnimations(target, target.animations);
  26965. }
  26966. // Children animations
  26967. if (target.getAnimatables) {
  26968. var animatables = target.getAnimatables();
  26969. for (var index = 0; index < animatables.length; index++) {
  26970. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26971. }
  26972. }
  26973. animatable.reset();
  26974. return animatable;
  26975. };
  26976. /**
  26977. * Begin a new animation on a given node
  26978. * @param target defines the target where the animation will take place
  26979. * @param animations defines the list of animations to start
  26980. * @param from defines the initial value
  26981. * @param to defines the final value
  26982. * @param loop defines if you want animation to loop (off by default)
  26983. * @param speedRatio defines the speed ratio to apply to all animations
  26984. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26985. * @returns the list of created animatables
  26986. */
  26987. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26988. if (speedRatio === undefined) {
  26989. speedRatio = 1.0;
  26990. }
  26991. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26992. return animatable;
  26993. };
  26994. /**
  26995. * Begin a new animation on a given node and its hierarchy
  26996. * @param target defines the root node where the animation will take place
  26997. * @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.
  26998. * @param animations defines the list of animations to start
  26999. * @param from defines the initial value
  27000. * @param to defines the final value
  27001. * @param loop defines if you want animation to loop (off by default)
  27002. * @param speedRatio defines the speed ratio to apply to all animations
  27003. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27004. * @returns the list of animatables created for all nodes
  27005. */
  27006. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27007. var children = target.getDescendants(directDescendantsOnly);
  27008. var result = [];
  27009. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  27010. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  27011. var child = children_1[_i];
  27012. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  27013. }
  27014. return result;
  27015. };
  27016. /**
  27017. * Gets the animatable associated with a specific target
  27018. * @param target defines the target of the animatable
  27019. * @returns the required animatable if found
  27020. */
  27021. Scene.prototype.getAnimatableByTarget = function (target) {
  27022. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27023. if (this._activeAnimatables[index].target === target) {
  27024. return this._activeAnimatables[index];
  27025. }
  27026. }
  27027. return null;
  27028. };
  27029. /**
  27030. * Gets all animatables associated with a given target
  27031. * @param target defines the target to look animatables for
  27032. * @returns an array of Animatables
  27033. */
  27034. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  27035. var result = [];
  27036. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27037. if (this._activeAnimatables[index].target === target) {
  27038. result.push(this._activeAnimatables[index]);
  27039. }
  27040. }
  27041. return result;
  27042. };
  27043. Object.defineProperty(Scene.prototype, "animatables", {
  27044. /**
  27045. * Gets all animatable attached to the scene
  27046. */
  27047. get: function () {
  27048. return this._activeAnimatables;
  27049. },
  27050. enumerable: true,
  27051. configurable: true
  27052. });
  27053. /**
  27054. * Will stop the animation of the given target
  27055. * @param target - the target
  27056. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  27057. * @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)
  27058. */
  27059. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  27060. var animatables = this.getAllAnimatablesByTarget(target);
  27061. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  27062. var animatable = animatables_1[_i];
  27063. animatable.stop(animationName, targetMask);
  27064. }
  27065. };
  27066. /**
  27067. * Stops and removes all animations that have been applied to the scene
  27068. */
  27069. Scene.prototype.stopAllAnimations = function () {
  27070. if (this._activeAnimatables) {
  27071. for (var i = 0; i < this._activeAnimatables.length; i++) {
  27072. this._activeAnimatables[i].stop();
  27073. }
  27074. this._activeAnimatables = [];
  27075. }
  27076. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  27077. var group = _a[_i];
  27078. group.stop();
  27079. }
  27080. };
  27081. Scene.prototype._animate = function () {
  27082. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  27083. return;
  27084. }
  27085. // Getting time
  27086. var now = BABYLON.Tools.Now;
  27087. if (!this._animationTimeLast) {
  27088. if (this._pendingData.length > 0) {
  27089. return;
  27090. }
  27091. this._animationTimeLast = now;
  27092. }
  27093. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  27094. this._animationTime += deltaTime;
  27095. this._animationTimeLast = now;
  27096. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27097. this._activeAnimatables[index]._animate(this._animationTime);
  27098. }
  27099. // Late animation bindings
  27100. this._processLateAnimationBindings();
  27101. };
  27102. /** @hidden */
  27103. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  27104. var target = runtimeAnimation.target;
  27105. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  27106. if (!target._lateAnimationHolders) {
  27107. target._lateAnimationHolders = {};
  27108. }
  27109. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  27110. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  27111. totalWeight: 0,
  27112. animations: [],
  27113. originalValue: originalValue
  27114. };
  27115. }
  27116. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  27117. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  27118. };
  27119. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  27120. var normalizer = 1.0;
  27121. var finalPosition = BABYLON.Tmp.Vector3[0];
  27122. var finalScaling = BABYLON.Tmp.Vector3[1];
  27123. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  27124. var startIndex = 0;
  27125. var originalAnimation = holder.animations[0];
  27126. var originalValue = holder.originalValue;
  27127. var scale = 1;
  27128. if (holder.totalWeight < 1.0) {
  27129. // We need to mix the original value in
  27130. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27131. scale = 1.0 - holder.totalWeight;
  27132. }
  27133. else {
  27134. startIndex = 1;
  27135. // We need to normalize the weights
  27136. normalizer = holder.totalWeight;
  27137. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27138. scale = originalAnimation.weight / normalizer;
  27139. if (scale == 1) {
  27140. return originalAnimation.currentValue;
  27141. }
  27142. }
  27143. finalScaling.scaleInPlace(scale);
  27144. finalPosition.scaleInPlace(scale);
  27145. finalQuaternion.scaleInPlace(scale);
  27146. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27147. var runtimeAnimation = holder.animations[animIndex];
  27148. var scale = runtimeAnimation.weight / normalizer;
  27149. var currentPosition = BABYLON.Tmp.Vector3[2];
  27150. var currentScaling = BABYLON.Tmp.Vector3[3];
  27151. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  27152. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  27153. currentScaling.scaleAndAddToRef(scale, finalScaling);
  27154. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  27155. currentPosition.scaleAndAddToRef(scale, finalPosition);
  27156. }
  27157. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  27158. return originalAnimation._workValue;
  27159. };
  27160. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  27161. var originalAnimation = holder.animations[0];
  27162. var originalValue = holder.originalValue;
  27163. if (holder.animations.length === 1) {
  27164. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  27165. return refQuaternion;
  27166. }
  27167. var normalizer = 1.0;
  27168. var quaternions;
  27169. var weights;
  27170. if (holder.totalWeight < 1.0) {
  27171. var scale = 1.0 - holder.totalWeight;
  27172. quaternions = [];
  27173. weights = [];
  27174. quaternions.push(originalValue);
  27175. weights.push(scale);
  27176. }
  27177. else {
  27178. if (holder.animations.length === 2) { // Slerp as soon as we can
  27179. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  27180. return refQuaternion;
  27181. }
  27182. quaternions = [];
  27183. weights = [];
  27184. normalizer = holder.totalWeight;
  27185. }
  27186. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  27187. var runtimeAnimation = holder.animations[animIndex];
  27188. quaternions.push(runtimeAnimation.currentValue);
  27189. weights.push(runtimeAnimation.weight / normalizer);
  27190. }
  27191. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  27192. var cumulativeAmount = 0;
  27193. var cumulativeQuaternion = null;
  27194. for (var index = 0; index < quaternions.length;) {
  27195. if (!cumulativeQuaternion) {
  27196. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  27197. cumulativeQuaternion = refQuaternion;
  27198. cumulativeAmount = weights[index] + weights[index + 1];
  27199. index += 2;
  27200. continue;
  27201. }
  27202. cumulativeAmount += weights[index];
  27203. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  27204. index++;
  27205. }
  27206. return cumulativeQuaternion;
  27207. };
  27208. Scene.prototype._processLateAnimationBindings = function () {
  27209. if (!this._registeredForLateAnimationBindings.length) {
  27210. return;
  27211. }
  27212. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  27213. var target = this._registeredForLateAnimationBindings.data[index];
  27214. for (var path in target._lateAnimationHolders) {
  27215. var holder = target._lateAnimationHolders[path];
  27216. var originalAnimation = holder.animations[0];
  27217. var originalValue = holder.originalValue;
  27218. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  27219. var finalValue = target[path];
  27220. if (matrixDecomposeMode) {
  27221. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  27222. }
  27223. else {
  27224. var quaternionMode = originalValue.w !== undefined;
  27225. if (quaternionMode) {
  27226. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  27227. }
  27228. else {
  27229. var startIndex = 0;
  27230. var normalizer = 1.0;
  27231. if (holder.totalWeight < 1.0) {
  27232. // We need to mix the original value in
  27233. if (originalValue.scale) {
  27234. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  27235. }
  27236. else {
  27237. finalValue = originalValue * (1.0 - holder.totalWeight);
  27238. }
  27239. }
  27240. else {
  27241. // We need to normalize the weights
  27242. normalizer = holder.totalWeight;
  27243. var scale_1 = originalAnimation.weight / normalizer;
  27244. if (scale_1 !== 1) {
  27245. if (originalAnimation.currentValue.scale) {
  27246. finalValue = originalAnimation.currentValue.scale(scale_1);
  27247. }
  27248. else {
  27249. finalValue = originalAnimation.currentValue * scale_1;
  27250. }
  27251. }
  27252. else {
  27253. finalValue = originalAnimation.currentValue;
  27254. }
  27255. startIndex = 1;
  27256. }
  27257. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27258. var runtimeAnimation = holder.animations[animIndex];
  27259. var scale = runtimeAnimation.weight / normalizer;
  27260. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  27261. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  27262. }
  27263. else {
  27264. finalValue += runtimeAnimation.currentValue * scale;
  27265. }
  27266. }
  27267. }
  27268. }
  27269. target[path] = finalValue;
  27270. }
  27271. target._lateAnimationHolders = {};
  27272. }
  27273. this._registeredForLateAnimationBindings.reset();
  27274. };
  27275. // Matrix
  27276. /** @hidden */
  27277. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  27278. this._useAlternateCameraConfiguration = active;
  27279. };
  27280. /**
  27281. * Gets the current view matrix
  27282. * @returns a Matrix
  27283. */
  27284. Scene.prototype.getViewMatrix = function () {
  27285. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  27286. };
  27287. /**
  27288. * Gets the current projection matrix
  27289. * @returns a Matrix
  27290. */
  27291. Scene.prototype.getProjectionMatrix = function () {
  27292. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  27293. };
  27294. /**
  27295. * Gets the current transform matrix
  27296. * @returns a Matrix made of View * Projection
  27297. */
  27298. Scene.prototype.getTransformMatrix = function () {
  27299. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  27300. };
  27301. /**
  27302. * Sets the current transform matrix
  27303. * @param view defines the View matrix to use
  27304. * @param projection defines the Projection matrix to use
  27305. */
  27306. Scene.prototype.setTransformMatrix = function (view, projection) {
  27307. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  27308. return;
  27309. }
  27310. this._viewUpdateFlag = view.updateFlag;
  27311. this._projectionUpdateFlag = projection.updateFlag;
  27312. this._viewMatrix = view;
  27313. this._projectionMatrix = projection;
  27314. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  27315. // Update frustum
  27316. if (!this._frustumPlanes) {
  27317. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  27318. }
  27319. else {
  27320. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  27321. }
  27322. if (this.activeCamera && this.activeCamera._alternateCamera) {
  27323. var otherCamera = this.activeCamera._alternateCamera;
  27324. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  27325. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  27326. }
  27327. if (this._sceneUbo.useUbo) {
  27328. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  27329. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  27330. this._sceneUbo.update();
  27331. }
  27332. };
  27333. /** @hidden */
  27334. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  27335. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  27336. return;
  27337. }
  27338. this._alternateViewUpdateFlag = view.updateFlag;
  27339. this._alternateProjectionUpdateFlag = projection.updateFlag;
  27340. this._alternateViewMatrix = view;
  27341. this._alternateProjectionMatrix = projection;
  27342. if (!this._alternateTransformMatrix) {
  27343. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  27344. }
  27345. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  27346. if (!this._alternateSceneUbo) {
  27347. this._createAlternateUbo();
  27348. }
  27349. if (this._alternateSceneUbo.useUbo) {
  27350. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  27351. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  27352. this._alternateSceneUbo.update();
  27353. }
  27354. };
  27355. /**
  27356. * Gets the uniform buffer used to store scene data
  27357. * @returns a UniformBuffer
  27358. */
  27359. Scene.prototype.getSceneUniformBuffer = function () {
  27360. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  27361. };
  27362. /**
  27363. * Gets an unique (relatively to the current scene) Id
  27364. * @returns an unique number for the scene
  27365. */
  27366. Scene.prototype.getUniqueId = function () {
  27367. var result = Scene._uniqueIdCounter;
  27368. Scene._uniqueIdCounter++;
  27369. return result;
  27370. };
  27371. /**
  27372. * Add a mesh to the list of scene's meshes
  27373. * @param newMesh defines the mesh to add
  27374. * @param recursive if all child meshes should also be added to the scene
  27375. */
  27376. Scene.prototype.addMesh = function (newMesh, recursive) {
  27377. var _this = this;
  27378. if (recursive === void 0) { recursive = false; }
  27379. this.meshes.push(newMesh);
  27380. //notify the collision coordinator
  27381. if (this.collisionCoordinator) {
  27382. this.collisionCoordinator.onMeshAdded(newMesh);
  27383. }
  27384. newMesh._resyncLightSources();
  27385. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  27386. if (recursive) {
  27387. newMesh.getChildMeshes().forEach(function (m) {
  27388. _this.addMesh(m);
  27389. });
  27390. }
  27391. };
  27392. /**
  27393. * Remove a mesh for the list of scene's meshes
  27394. * @param toRemove defines the mesh to remove
  27395. * @param recursive if all child meshes should also be removed from the scene
  27396. * @returns the index where the mesh was in the mesh list
  27397. */
  27398. Scene.prototype.removeMesh = function (toRemove, recursive) {
  27399. var _this = this;
  27400. if (recursive === void 0) { recursive = false; }
  27401. var index = this.meshes.indexOf(toRemove);
  27402. if (index !== -1) {
  27403. // Remove from the scene if mesh found
  27404. this.meshes.splice(index, 1);
  27405. }
  27406. this.onMeshRemovedObservable.notifyObservers(toRemove);
  27407. if (recursive) {
  27408. toRemove.getChildMeshes().forEach(function (m) {
  27409. _this.removeMesh(m);
  27410. });
  27411. }
  27412. return index;
  27413. };
  27414. /**
  27415. * Add a transform node to the list of scene's transform nodes
  27416. * @param newTransformNode defines the transform node to add
  27417. */
  27418. Scene.prototype.addTransformNode = function (newTransformNode) {
  27419. this.transformNodes.push(newTransformNode);
  27420. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  27421. };
  27422. /**
  27423. * Remove a transform node for the list of scene's transform nodes
  27424. * @param toRemove defines the transform node to remove
  27425. * @returns the index where the transform node was in the transform node list
  27426. */
  27427. Scene.prototype.removeTransformNode = function (toRemove) {
  27428. var index = this.transformNodes.indexOf(toRemove);
  27429. if (index !== -1) {
  27430. // Remove from the scene if found
  27431. this.transformNodes.splice(index, 1);
  27432. }
  27433. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  27434. return index;
  27435. };
  27436. /**
  27437. * Remove a skeleton for the list of scene's skeletons
  27438. * @param toRemove defines the skeleton to remove
  27439. * @returns the index where the skeleton was in the skeleton list
  27440. */
  27441. Scene.prototype.removeSkeleton = function (toRemove) {
  27442. var index = this.skeletons.indexOf(toRemove);
  27443. if (index !== -1) {
  27444. // Remove from the scene if found
  27445. this.skeletons.splice(index, 1);
  27446. }
  27447. return index;
  27448. };
  27449. /**
  27450. * Remove a morph target for the list of scene's morph targets
  27451. * @param toRemove defines the morph target to remove
  27452. * @returns the index where the morph target was in the morph target list
  27453. */
  27454. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  27455. var index = this.morphTargetManagers.indexOf(toRemove);
  27456. if (index !== -1) {
  27457. // Remove from the scene if found
  27458. this.morphTargetManagers.splice(index, 1);
  27459. }
  27460. return index;
  27461. };
  27462. /**
  27463. * Remove a light for the list of scene's lights
  27464. * @param toRemove defines the light to remove
  27465. * @returns the index where the light was in the light list
  27466. */
  27467. Scene.prototype.removeLight = function (toRemove) {
  27468. var index = this.lights.indexOf(toRemove);
  27469. if (index !== -1) {
  27470. // Remove from meshes
  27471. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27472. var mesh = _a[_i];
  27473. mesh._removeLightSource(toRemove);
  27474. }
  27475. // Remove from the scene if mesh found
  27476. this.lights.splice(index, 1);
  27477. this.sortLightsByPriority();
  27478. }
  27479. this.onLightRemovedObservable.notifyObservers(toRemove);
  27480. return index;
  27481. };
  27482. /**
  27483. * Remove a camera for the list of scene's cameras
  27484. * @param toRemove defines the camera to remove
  27485. * @returns the index where the camera was in the camera list
  27486. */
  27487. Scene.prototype.removeCamera = function (toRemove) {
  27488. var index = this.cameras.indexOf(toRemove);
  27489. if (index !== -1) {
  27490. // Remove from the scene if mesh found
  27491. this.cameras.splice(index, 1);
  27492. }
  27493. // Remove from activeCameras
  27494. var index2 = this.activeCameras.indexOf(toRemove);
  27495. if (index2 !== -1) {
  27496. // Remove from the scene if mesh found
  27497. this.activeCameras.splice(index2, 1);
  27498. }
  27499. // Reset the activeCamera
  27500. if (this.activeCamera === toRemove) {
  27501. if (this.cameras.length > 0) {
  27502. this.activeCamera = this.cameras[0];
  27503. }
  27504. else {
  27505. this.activeCamera = null;
  27506. }
  27507. }
  27508. this.onCameraRemovedObservable.notifyObservers(toRemove);
  27509. return index;
  27510. };
  27511. /**
  27512. * Remove a particle system for the list of scene's particle systems
  27513. * @param toRemove defines the particle system to remove
  27514. * @returns the index where the particle system was in the particle system list
  27515. */
  27516. Scene.prototype.removeParticleSystem = function (toRemove) {
  27517. var index = this.particleSystems.indexOf(toRemove);
  27518. if (index !== -1) {
  27519. this.particleSystems.splice(index, 1);
  27520. }
  27521. return index;
  27522. };
  27523. /**
  27524. * Remove a animation for the list of scene's animations
  27525. * @param toRemove defines the animation to remove
  27526. * @returns the index where the animation was in the animation list
  27527. */
  27528. Scene.prototype.removeAnimation = function (toRemove) {
  27529. var index = this.animations.indexOf(toRemove);
  27530. if (index !== -1) {
  27531. this.animations.splice(index, 1);
  27532. }
  27533. return index;
  27534. };
  27535. /**
  27536. * Removes the given animation group from this scene.
  27537. * @param toRemove The animation group to remove
  27538. * @returns The index of the removed animation group
  27539. */
  27540. Scene.prototype.removeAnimationGroup = function (toRemove) {
  27541. var index = this.animationGroups.indexOf(toRemove);
  27542. if (index !== -1) {
  27543. this.animationGroups.splice(index, 1);
  27544. }
  27545. return index;
  27546. };
  27547. /**
  27548. * Removes the given multi-material from this scene.
  27549. * @param toRemove The multi-material to remove
  27550. * @returns The index of the removed multi-material
  27551. */
  27552. Scene.prototype.removeMultiMaterial = function (toRemove) {
  27553. var index = this.multiMaterials.indexOf(toRemove);
  27554. if (index !== -1) {
  27555. this.multiMaterials.splice(index, 1);
  27556. }
  27557. return index;
  27558. };
  27559. /**
  27560. * Removes the given material from this scene.
  27561. * @param toRemove The material to remove
  27562. * @returns The index of the removed material
  27563. */
  27564. Scene.prototype.removeMaterial = function (toRemove) {
  27565. var index = this.materials.indexOf(toRemove);
  27566. if (index !== -1) {
  27567. this.materials.splice(index, 1);
  27568. }
  27569. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  27570. return index;
  27571. };
  27572. /**
  27573. * Removes the given action manager from this scene.
  27574. * @param toRemove The action manager to remove
  27575. * @returns The index of the removed action manager
  27576. */
  27577. Scene.prototype.removeActionManager = function (toRemove) {
  27578. var index = this.actionManagers.indexOf(toRemove);
  27579. if (index !== -1) {
  27580. this.actionManagers.splice(index, 1);
  27581. }
  27582. return index;
  27583. };
  27584. /**
  27585. * Removes the given texture from this scene.
  27586. * @param toRemove The texture to remove
  27587. * @returns The index of the removed texture
  27588. */
  27589. Scene.prototype.removeTexture = function (toRemove) {
  27590. var index = this.textures.indexOf(toRemove);
  27591. if (index !== -1) {
  27592. this.textures.splice(index, 1);
  27593. }
  27594. this.onTextureRemovedObservable.notifyObservers(toRemove);
  27595. return index;
  27596. };
  27597. /**
  27598. * Adds the given light to this scene
  27599. * @param newLight The light to add
  27600. */
  27601. Scene.prototype.addLight = function (newLight) {
  27602. this.lights.push(newLight);
  27603. this.sortLightsByPriority();
  27604. // Add light to all meshes (To support if the light is removed and then readded)
  27605. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27606. var mesh = _a[_i];
  27607. if (mesh._lightSources.indexOf(newLight) === -1) {
  27608. mesh._lightSources.push(newLight);
  27609. mesh._resyncLightSources();
  27610. }
  27611. }
  27612. this.onNewLightAddedObservable.notifyObservers(newLight);
  27613. };
  27614. /**
  27615. * Sorts the list list based on light priorities
  27616. */
  27617. Scene.prototype.sortLightsByPriority = function () {
  27618. if (this.requireLightSorting) {
  27619. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  27620. }
  27621. };
  27622. /**
  27623. * Adds the given camera to this scene
  27624. * @param newCamera The camera to add
  27625. */
  27626. Scene.prototype.addCamera = function (newCamera) {
  27627. this.cameras.push(newCamera);
  27628. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  27629. };
  27630. /**
  27631. * Adds the given skeleton to this scene
  27632. * @param newSkeleton The skeleton to add
  27633. */
  27634. Scene.prototype.addSkeleton = function (newSkeleton) {
  27635. this.skeletons.push(newSkeleton);
  27636. };
  27637. /**
  27638. * Adds the given particle system to this scene
  27639. * @param newParticleSystem The particle system to add
  27640. */
  27641. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  27642. this.particleSystems.push(newParticleSystem);
  27643. };
  27644. /**
  27645. * Adds the given animation to this scene
  27646. * @param newAnimation The animation to add
  27647. */
  27648. Scene.prototype.addAnimation = function (newAnimation) {
  27649. this.animations.push(newAnimation);
  27650. };
  27651. /**
  27652. * Adds the given animation group to this scene.
  27653. * @param newAnimationGroup The animation group to add
  27654. */
  27655. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  27656. this.animationGroups.push(newAnimationGroup);
  27657. };
  27658. /**
  27659. * Adds the given multi-material to this scene
  27660. * @param newMultiMaterial The multi-material to add
  27661. */
  27662. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  27663. this.multiMaterials.push(newMultiMaterial);
  27664. };
  27665. /**
  27666. * Adds the given material to this scene
  27667. * @param newMaterial The material to add
  27668. */
  27669. Scene.prototype.addMaterial = function (newMaterial) {
  27670. this.materials.push(newMaterial);
  27671. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  27672. };
  27673. /**
  27674. * Adds the given morph target to this scene
  27675. * @param newMorphTargetManager The morph target to add
  27676. */
  27677. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  27678. this.morphTargetManagers.push(newMorphTargetManager);
  27679. };
  27680. /**
  27681. * Adds the given geometry to this scene
  27682. * @param newGeometry The geometry to add
  27683. */
  27684. Scene.prototype.addGeometry = function (newGeometry) {
  27685. this.geometries.push(newGeometry);
  27686. };
  27687. /**
  27688. * Adds the given action manager to this scene
  27689. * @param newActionManager The action manager to add
  27690. */
  27691. Scene.prototype.addActionManager = function (newActionManager) {
  27692. this.actionManagers.push(newActionManager);
  27693. };
  27694. /**
  27695. * Adds the given texture to this scene.
  27696. * @param newTexture The texture to add
  27697. */
  27698. Scene.prototype.addTexture = function (newTexture) {
  27699. this.textures.push(newTexture);
  27700. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  27701. };
  27702. /**
  27703. * Switch active camera
  27704. * @param newCamera defines the new active camera
  27705. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  27706. */
  27707. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  27708. if (attachControl === void 0) { attachControl = true; }
  27709. var canvas = this._engine.getRenderingCanvas();
  27710. if (!canvas) {
  27711. return;
  27712. }
  27713. if (this.activeCamera) {
  27714. this.activeCamera.detachControl(canvas);
  27715. }
  27716. this.activeCamera = newCamera;
  27717. if (attachControl) {
  27718. newCamera.attachControl(canvas);
  27719. }
  27720. };
  27721. /**
  27722. * sets the active camera of the scene using its ID
  27723. * @param id defines the camera's ID
  27724. * @return the new active camera or null if none found.
  27725. */
  27726. Scene.prototype.setActiveCameraByID = function (id) {
  27727. var camera = this.getCameraByID(id);
  27728. if (camera) {
  27729. this.activeCamera = camera;
  27730. return camera;
  27731. }
  27732. return null;
  27733. };
  27734. /**
  27735. * sets the active camera of the scene using its name
  27736. * @param name defines the camera's name
  27737. * @returns the new active camera or null if none found.
  27738. */
  27739. Scene.prototype.setActiveCameraByName = function (name) {
  27740. var camera = this.getCameraByName(name);
  27741. if (camera) {
  27742. this.activeCamera = camera;
  27743. return camera;
  27744. }
  27745. return null;
  27746. };
  27747. /**
  27748. * get an animation group using its name
  27749. * @param name defines the material's name
  27750. * @return the animation group or null if none found.
  27751. */
  27752. Scene.prototype.getAnimationGroupByName = function (name) {
  27753. for (var index = 0; index < this.animationGroups.length; index++) {
  27754. if (this.animationGroups[index].name === name) {
  27755. return this.animationGroups[index];
  27756. }
  27757. }
  27758. return null;
  27759. };
  27760. /**
  27761. * get a material using its id
  27762. * @param id defines the material's ID
  27763. * @return the material or null if none found.
  27764. */
  27765. Scene.prototype.getMaterialByID = function (id) {
  27766. for (var index = 0; index < this.materials.length; index++) {
  27767. if (this.materials[index].id === id) {
  27768. return this.materials[index];
  27769. }
  27770. }
  27771. return null;
  27772. };
  27773. /**
  27774. * Gets a material using its name
  27775. * @param name defines the material's name
  27776. * @return the material or null if none found.
  27777. */
  27778. Scene.prototype.getMaterialByName = function (name) {
  27779. for (var index = 0; index < this.materials.length; index++) {
  27780. if (this.materials[index].name === name) {
  27781. return this.materials[index];
  27782. }
  27783. }
  27784. return null;
  27785. };
  27786. /**
  27787. * Gets a camera using its id
  27788. * @param id defines the id to look for
  27789. * @returns the camera or null if not found
  27790. */
  27791. Scene.prototype.getCameraByID = function (id) {
  27792. for (var index = 0; index < this.cameras.length; index++) {
  27793. if (this.cameras[index].id === id) {
  27794. return this.cameras[index];
  27795. }
  27796. }
  27797. return null;
  27798. };
  27799. /**
  27800. * Gets a camera using its unique id
  27801. * @param uniqueId defines the unique id to look for
  27802. * @returns the camera or null if not found
  27803. */
  27804. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27805. for (var index = 0; index < this.cameras.length; index++) {
  27806. if (this.cameras[index].uniqueId === uniqueId) {
  27807. return this.cameras[index];
  27808. }
  27809. }
  27810. return null;
  27811. };
  27812. /**
  27813. * Gets a camera using its name
  27814. * @param name defines the camera's name
  27815. * @return the camera or null if none found.
  27816. */
  27817. Scene.prototype.getCameraByName = function (name) {
  27818. for (var index = 0; index < this.cameras.length; index++) {
  27819. if (this.cameras[index].name === name) {
  27820. return this.cameras[index];
  27821. }
  27822. }
  27823. return null;
  27824. };
  27825. /**
  27826. * Gets a bone using its id
  27827. * @param id defines the bone's id
  27828. * @return the bone or null if not found
  27829. */
  27830. Scene.prototype.getBoneByID = function (id) {
  27831. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27832. var skeleton = this.skeletons[skeletonIndex];
  27833. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27834. if (skeleton.bones[boneIndex].id === id) {
  27835. return skeleton.bones[boneIndex];
  27836. }
  27837. }
  27838. }
  27839. return null;
  27840. };
  27841. /**
  27842. * Gets a bone using its id
  27843. * @param name defines the bone's name
  27844. * @return the bone or null if not found
  27845. */
  27846. Scene.prototype.getBoneByName = function (name) {
  27847. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27848. var skeleton = this.skeletons[skeletonIndex];
  27849. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27850. if (skeleton.bones[boneIndex].name === name) {
  27851. return skeleton.bones[boneIndex];
  27852. }
  27853. }
  27854. }
  27855. return null;
  27856. };
  27857. /**
  27858. * Gets a light node using its name
  27859. * @param name defines the the light's name
  27860. * @return the light or null if none found.
  27861. */
  27862. Scene.prototype.getLightByName = function (name) {
  27863. for (var index = 0; index < this.lights.length; index++) {
  27864. if (this.lights[index].name === name) {
  27865. return this.lights[index];
  27866. }
  27867. }
  27868. return null;
  27869. };
  27870. /**
  27871. * Gets a light node using its id
  27872. * @param id defines the light's id
  27873. * @return the light or null if none found.
  27874. */
  27875. Scene.prototype.getLightByID = function (id) {
  27876. for (var index = 0; index < this.lights.length; index++) {
  27877. if (this.lights[index].id === id) {
  27878. return this.lights[index];
  27879. }
  27880. }
  27881. return null;
  27882. };
  27883. /**
  27884. * Gets a light node using its scene-generated unique ID
  27885. * @param uniqueId defines the light's unique id
  27886. * @return the light or null if none found.
  27887. */
  27888. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27889. for (var index = 0; index < this.lights.length; index++) {
  27890. if (this.lights[index].uniqueId === uniqueId) {
  27891. return this.lights[index];
  27892. }
  27893. }
  27894. return null;
  27895. };
  27896. /**
  27897. * Gets a particle system by id
  27898. * @param id defines the particle system id
  27899. * @return the corresponding system or null if none found
  27900. */
  27901. Scene.prototype.getParticleSystemByID = function (id) {
  27902. for (var index = 0; index < this.particleSystems.length; index++) {
  27903. if (this.particleSystems[index].id === id) {
  27904. return this.particleSystems[index];
  27905. }
  27906. }
  27907. return null;
  27908. };
  27909. /**
  27910. * Gets a geometry using its ID
  27911. * @param id defines the geometry's id
  27912. * @return the geometry or null if none found.
  27913. */
  27914. Scene.prototype.getGeometryByID = function (id) {
  27915. for (var index = 0; index < this.geometries.length; index++) {
  27916. if (this.geometries[index].id === id) {
  27917. return this.geometries[index];
  27918. }
  27919. }
  27920. return null;
  27921. };
  27922. /**
  27923. * Add a new geometry to this scene
  27924. * @param geometry defines the geometry to be added to the scene.
  27925. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27926. * @return a boolean defining if the geometry was added or not
  27927. */
  27928. Scene.prototype.pushGeometry = function (geometry, force) {
  27929. if (!force && this.getGeometryByID(geometry.id)) {
  27930. return false;
  27931. }
  27932. this.geometries.push(geometry);
  27933. //notify the collision coordinator
  27934. if (this.collisionCoordinator) {
  27935. this.collisionCoordinator.onGeometryAdded(geometry);
  27936. }
  27937. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27938. return true;
  27939. };
  27940. /**
  27941. * Removes an existing geometry
  27942. * @param geometry defines the geometry to be removed from the scene
  27943. * @return a boolean defining if the geometry was removed or not
  27944. */
  27945. Scene.prototype.removeGeometry = function (geometry) {
  27946. var index = this.geometries.indexOf(geometry);
  27947. if (index > -1) {
  27948. this.geometries.splice(index, 1);
  27949. //notify the collision coordinator
  27950. if (this.collisionCoordinator) {
  27951. this.collisionCoordinator.onGeometryDeleted(geometry);
  27952. }
  27953. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27954. return true;
  27955. }
  27956. return false;
  27957. };
  27958. /**
  27959. * Gets the list of geometries attached to the scene
  27960. * @returns an array of Geometry
  27961. */
  27962. Scene.prototype.getGeometries = function () {
  27963. return this.geometries;
  27964. };
  27965. /**
  27966. * Gets the first added mesh found of a given ID
  27967. * @param id defines the id to search for
  27968. * @return the mesh found or null if not found at all
  27969. */
  27970. Scene.prototype.getMeshByID = function (id) {
  27971. for (var index = 0; index < this.meshes.length; index++) {
  27972. if (this.meshes[index].id === id) {
  27973. return this.meshes[index];
  27974. }
  27975. }
  27976. return null;
  27977. };
  27978. /**
  27979. * Gets a list of meshes using their id
  27980. * @param id defines the id to search for
  27981. * @returns a list of meshes
  27982. */
  27983. Scene.prototype.getMeshesByID = function (id) {
  27984. return this.meshes.filter(function (m) {
  27985. return m.id === id;
  27986. });
  27987. };
  27988. /**
  27989. * Gets the first added transform node found of a given ID
  27990. * @param id defines the id to search for
  27991. * @return the found transform node or null if not found at all.
  27992. */
  27993. Scene.prototype.getTransformNodeByID = function (id) {
  27994. for (var index = 0; index < this.transformNodes.length; index++) {
  27995. if (this.transformNodes[index].id === id) {
  27996. return this.transformNodes[index];
  27997. }
  27998. }
  27999. return null;
  28000. };
  28001. /**
  28002. * Gets a list of transform nodes using their id
  28003. * @param id defines the id to search for
  28004. * @returns a list of transform nodes
  28005. */
  28006. Scene.prototype.getTransformNodesByID = function (id) {
  28007. return this.transformNodes.filter(function (m) {
  28008. return m.id === id;
  28009. });
  28010. };
  28011. /**
  28012. * Gets a mesh with its auto-generated unique id
  28013. * @param uniqueId defines the unique id to search for
  28014. * @return the found mesh or null if not found at all.
  28015. */
  28016. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  28017. for (var index = 0; index < this.meshes.length; index++) {
  28018. if (this.meshes[index].uniqueId === uniqueId) {
  28019. return this.meshes[index];
  28020. }
  28021. }
  28022. return null;
  28023. };
  28024. /**
  28025. * Gets a the last added mesh using a given id
  28026. * @param id defines the id to search for
  28027. * @return the found mesh or null if not found at all.
  28028. */
  28029. Scene.prototype.getLastMeshByID = function (id) {
  28030. for (var index = this.meshes.length - 1; index >= 0; index--) {
  28031. if (this.meshes[index].id === id) {
  28032. return this.meshes[index];
  28033. }
  28034. }
  28035. return null;
  28036. };
  28037. /**
  28038. * Gets a the last added node (Mesh, Camera, Light) using a given id
  28039. * @param id defines the id to search for
  28040. * @return the found node or null if not found at all
  28041. */
  28042. Scene.prototype.getLastEntryByID = function (id) {
  28043. var index;
  28044. for (index = this.meshes.length - 1; index >= 0; index--) {
  28045. if (this.meshes[index].id === id) {
  28046. return this.meshes[index];
  28047. }
  28048. }
  28049. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  28050. if (this.transformNodes[index].id === id) {
  28051. return this.transformNodes[index];
  28052. }
  28053. }
  28054. for (index = this.cameras.length - 1; index >= 0; index--) {
  28055. if (this.cameras[index].id === id) {
  28056. return this.cameras[index];
  28057. }
  28058. }
  28059. for (index = this.lights.length - 1; index >= 0; index--) {
  28060. if (this.lights[index].id === id) {
  28061. return this.lights[index];
  28062. }
  28063. }
  28064. return null;
  28065. };
  28066. /**
  28067. * Gets a node (Mesh, Camera, Light) using a given id
  28068. * @param id defines the id to search for
  28069. * @return the found node or null if not found at all
  28070. */
  28071. Scene.prototype.getNodeByID = function (id) {
  28072. var mesh = this.getMeshByID(id);
  28073. if (mesh) {
  28074. return mesh;
  28075. }
  28076. var light = this.getLightByID(id);
  28077. if (light) {
  28078. return light;
  28079. }
  28080. var camera = this.getCameraByID(id);
  28081. if (camera) {
  28082. return camera;
  28083. }
  28084. var bone = this.getBoneByID(id);
  28085. return bone;
  28086. };
  28087. /**
  28088. * Gets a node (Mesh, Camera, Light) using a given name
  28089. * @param name defines the name to search for
  28090. * @return the found node or null if not found at all.
  28091. */
  28092. Scene.prototype.getNodeByName = function (name) {
  28093. var mesh = this.getMeshByName(name);
  28094. if (mesh) {
  28095. return mesh;
  28096. }
  28097. var light = this.getLightByName(name);
  28098. if (light) {
  28099. return light;
  28100. }
  28101. var camera = this.getCameraByName(name);
  28102. if (camera) {
  28103. return camera;
  28104. }
  28105. var bone = this.getBoneByName(name);
  28106. return bone;
  28107. };
  28108. /**
  28109. * Gets a mesh using a given name
  28110. * @param name defines the name to search for
  28111. * @return the found mesh or null if not found at all.
  28112. */
  28113. Scene.prototype.getMeshByName = function (name) {
  28114. for (var index = 0; index < this.meshes.length; index++) {
  28115. if (this.meshes[index].name === name) {
  28116. return this.meshes[index];
  28117. }
  28118. }
  28119. return null;
  28120. };
  28121. /**
  28122. * Gets a transform node using a given name
  28123. * @param name defines the name to search for
  28124. * @return the found transform node or null if not found at all.
  28125. */
  28126. Scene.prototype.getTransformNodeByName = function (name) {
  28127. for (var index = 0; index < this.transformNodes.length; index++) {
  28128. if (this.transformNodes[index].name === name) {
  28129. return this.transformNodes[index];
  28130. }
  28131. }
  28132. return null;
  28133. };
  28134. /**
  28135. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  28136. * @param id defines the id to search for
  28137. * @return the found skeleton or null if not found at all.
  28138. */
  28139. Scene.prototype.getLastSkeletonByID = function (id) {
  28140. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  28141. if (this.skeletons[index].id === id) {
  28142. return this.skeletons[index];
  28143. }
  28144. }
  28145. return null;
  28146. };
  28147. /**
  28148. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  28149. * @param id defines the id to search for
  28150. * @return the found skeleton or null if not found at all.
  28151. */
  28152. Scene.prototype.getSkeletonById = function (id) {
  28153. for (var index = 0; index < this.skeletons.length; index++) {
  28154. if (this.skeletons[index].id === id) {
  28155. return this.skeletons[index];
  28156. }
  28157. }
  28158. return null;
  28159. };
  28160. /**
  28161. * Gets a skeleton using a given name
  28162. * @param name defines the name to search for
  28163. * @return the found skeleton or null if not found at all.
  28164. */
  28165. Scene.prototype.getSkeletonByName = function (name) {
  28166. for (var index = 0; index < this.skeletons.length; index++) {
  28167. if (this.skeletons[index].name === name) {
  28168. return this.skeletons[index];
  28169. }
  28170. }
  28171. return null;
  28172. };
  28173. /**
  28174. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  28175. * @param id defines the id to search for
  28176. * @return the found morph target manager or null if not found at all.
  28177. */
  28178. Scene.prototype.getMorphTargetManagerById = function (id) {
  28179. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  28180. if (this.morphTargetManagers[index].uniqueId === id) {
  28181. return this.morphTargetManagers[index];
  28182. }
  28183. }
  28184. return null;
  28185. };
  28186. /**
  28187. * Gets a boolean indicating if the given mesh is active
  28188. * @param mesh defines the mesh to look for
  28189. * @returns true if the mesh is in the active list
  28190. */
  28191. Scene.prototype.isActiveMesh = function (mesh) {
  28192. return (this._activeMeshes.indexOf(mesh) !== -1);
  28193. };
  28194. Object.defineProperty(Scene.prototype, "uid", {
  28195. /**
  28196. * Return a unique id as a string which can serve as an identifier for the scene
  28197. */
  28198. get: function () {
  28199. if (!this._uid) {
  28200. this._uid = BABYLON.Tools.RandomId();
  28201. }
  28202. return this._uid;
  28203. },
  28204. enumerable: true,
  28205. configurable: true
  28206. });
  28207. /**
  28208. * Add an externaly attached data from its key.
  28209. * This method call will fail and return false, if such key already exists.
  28210. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  28211. * @param key the unique key that identifies the data
  28212. * @param data the data object to associate to the key for this Engine instance
  28213. * @return true if no such key were already present and the data was added successfully, false otherwise
  28214. */
  28215. Scene.prototype.addExternalData = function (key, data) {
  28216. if (!this._externalData) {
  28217. this._externalData = new BABYLON.StringDictionary();
  28218. }
  28219. return this._externalData.add(key, data);
  28220. };
  28221. /**
  28222. * Get an externaly attached data from its key
  28223. * @param key the unique key that identifies the data
  28224. * @return the associated data, if present (can be null), or undefined if not present
  28225. */
  28226. Scene.prototype.getExternalData = function (key) {
  28227. if (!this._externalData) {
  28228. return null;
  28229. }
  28230. return this._externalData.get(key);
  28231. };
  28232. /**
  28233. * Get an externaly attached data from its key, create it using a factory if it's not already present
  28234. * @param key the unique key that identifies the data
  28235. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  28236. * @return the associated data, can be null if the factory returned null.
  28237. */
  28238. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  28239. if (!this._externalData) {
  28240. this._externalData = new BABYLON.StringDictionary();
  28241. }
  28242. return this._externalData.getOrAddWithFactory(key, factory);
  28243. };
  28244. /**
  28245. * Remove an externaly attached data from the Engine instance
  28246. * @param key the unique key that identifies the data
  28247. * @return true if the data was successfully removed, false if it doesn't exist
  28248. */
  28249. Scene.prototype.removeExternalData = function (key) {
  28250. return this._externalData.remove(key);
  28251. };
  28252. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  28253. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  28254. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  28255. var step = _a[_i];
  28256. step.action(mesh, subMesh);
  28257. }
  28258. var material = subMesh.getMaterial();
  28259. if (material !== null && material !== undefined) {
  28260. // Render targets
  28261. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  28262. if (this._processedMaterials.indexOf(material) === -1) {
  28263. this._processedMaterials.push(material);
  28264. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  28265. }
  28266. }
  28267. // Dispatch
  28268. this._activeIndices.addCount(subMesh.indexCount, false);
  28269. this._renderingManager.dispatch(subMesh, mesh, material);
  28270. }
  28271. }
  28272. };
  28273. /**
  28274. * Clear the processed materials smart array preventing retention point in material dispose.
  28275. */
  28276. Scene.prototype.freeProcessedMaterials = function () {
  28277. this._processedMaterials.dispose();
  28278. };
  28279. /**
  28280. * Clear the active meshes smart array preventing retention point in mesh dispose.
  28281. */
  28282. Scene.prototype.freeActiveMeshes = function () {
  28283. this._activeMeshes.dispose();
  28284. if (this.activeCamera && this.activeCamera._activeMeshes) {
  28285. this.activeCamera._activeMeshes.dispose();
  28286. }
  28287. if (this.activeCameras) {
  28288. for (var i = 0; i < this.activeCameras.length; i++) {
  28289. var activeCamera = this.activeCameras[i];
  28290. if (activeCamera && activeCamera._activeMeshes) {
  28291. activeCamera._activeMeshes.dispose();
  28292. }
  28293. }
  28294. }
  28295. };
  28296. /**
  28297. * Clear the info related to rendering groups preventing retention points during dispose.
  28298. */
  28299. Scene.prototype.freeRenderingGroups = function () {
  28300. if (this._renderingManager) {
  28301. this._renderingManager.freeRenderingGroups();
  28302. }
  28303. if (this.textures) {
  28304. for (var i = 0; i < this.textures.length; i++) {
  28305. var texture = this.textures[i];
  28306. if (texture && texture.renderList) {
  28307. texture.freeRenderingGroups();
  28308. }
  28309. }
  28310. }
  28311. };
  28312. /** @hidden */
  28313. Scene.prototype._isInIntermediateRendering = function () {
  28314. return this._intermediateRendering;
  28315. };
  28316. /**
  28317. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  28318. * @returns the current scene
  28319. */
  28320. Scene.prototype.freezeActiveMeshes = function () {
  28321. if (!this.activeCamera) {
  28322. return this;
  28323. }
  28324. if (!this._frustumPlanes) {
  28325. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28326. }
  28327. this._evaluateActiveMeshes();
  28328. this._activeMeshesFrozen = true;
  28329. return this;
  28330. };
  28331. /**
  28332. * Use this function to restart evaluating active meshes on every frame
  28333. * @returns the current scene
  28334. */
  28335. Scene.prototype.unfreezeActiveMeshes = function () {
  28336. this._activeMeshesFrozen = false;
  28337. return this;
  28338. };
  28339. Scene.prototype._evaluateActiveMeshes = function () {
  28340. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  28341. return;
  28342. }
  28343. if (!this.activeCamera) {
  28344. return;
  28345. }
  28346. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  28347. this.activeCamera._activeMeshes.reset();
  28348. this._activeMeshes.reset();
  28349. this._renderingManager.reset();
  28350. this._processedMaterials.reset();
  28351. this._activeParticleSystems.reset();
  28352. this._activeSkeletons.reset();
  28353. this._softwareSkinnedMeshes.reset();
  28354. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  28355. var step = _a[_i];
  28356. step.action();
  28357. }
  28358. // Determine mesh candidates
  28359. var meshes = this.getActiveMeshCandidates();
  28360. // Check each mesh
  28361. var len = meshes.length;
  28362. for (var i = 0; i < len; i++) {
  28363. var mesh = meshes.data[i];
  28364. if (mesh.isBlocked) {
  28365. continue;
  28366. }
  28367. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  28368. if (!mesh.isReady() || !mesh.isEnabled()) {
  28369. continue;
  28370. }
  28371. mesh.computeWorldMatrix();
  28372. // Intersections
  28373. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  28374. this._meshesForIntersections.pushNoDuplicate(mesh);
  28375. }
  28376. // Switch to current LOD
  28377. var meshLOD = mesh.getLOD(this.activeCamera);
  28378. if (meshLOD === undefined || meshLOD === null) {
  28379. continue;
  28380. }
  28381. mesh._preActivate();
  28382. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  28383. this._activeMeshes.push(mesh);
  28384. this.activeCamera._activeMeshes.push(mesh);
  28385. mesh._activate(this._renderId);
  28386. if (meshLOD !== mesh) {
  28387. meshLOD._activate(this._renderId);
  28388. }
  28389. this._activeMesh(mesh, meshLOD);
  28390. }
  28391. }
  28392. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  28393. // Particle systems
  28394. if (this.particlesEnabled) {
  28395. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  28396. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  28397. var particleSystem = this.particleSystems[particleIndex];
  28398. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  28399. continue;
  28400. }
  28401. var emitter = particleSystem.emitter;
  28402. if (!emitter.position || emitter.isEnabled()) {
  28403. this._activeParticleSystems.push(particleSystem);
  28404. particleSystem.animate();
  28405. this._renderingManager.dispatchParticles(particleSystem);
  28406. }
  28407. }
  28408. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  28409. }
  28410. };
  28411. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  28412. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  28413. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  28414. mesh.skeleton.prepare();
  28415. }
  28416. if (!mesh.computeBonesUsingShaders) {
  28417. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  28418. }
  28419. }
  28420. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  28421. var step = _a[_i];
  28422. step.action(sourceMesh, mesh);
  28423. }
  28424. if (mesh !== undefined && mesh !== null
  28425. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  28426. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  28427. var len = subMeshes.length;
  28428. for (var i = 0; i < len; i++) {
  28429. var subMesh = subMeshes.data[i];
  28430. this._evaluateSubMesh(subMesh, mesh);
  28431. }
  28432. }
  28433. };
  28434. /**
  28435. * Update the transform matrix to update from the current active camera
  28436. * @param force defines a boolean used to force the update even if cache is up to date
  28437. */
  28438. Scene.prototype.updateTransformMatrix = function (force) {
  28439. if (!this.activeCamera) {
  28440. return;
  28441. }
  28442. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  28443. };
  28444. /**
  28445. * 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)
  28446. * @param alternateCamera defines the camera to use
  28447. */
  28448. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  28449. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  28450. };
  28451. Scene.prototype._renderForCamera = function (camera, rigParent) {
  28452. if (camera && camera._skipRendering) {
  28453. return;
  28454. }
  28455. var engine = this._engine;
  28456. this.activeCamera = camera;
  28457. if (!this.activeCamera)
  28458. throw new Error("Active camera not set");
  28459. // Viewport
  28460. engine.setViewport(this.activeCamera.viewport);
  28461. // Camera
  28462. this.resetCachedMaterial();
  28463. this._renderId++;
  28464. this.updateTransformMatrix();
  28465. if (camera._alternateCamera) {
  28466. this.updateAlternateTransformMatrix(camera._alternateCamera);
  28467. this._alternateRendering = true;
  28468. }
  28469. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  28470. // Meshes
  28471. this._evaluateActiveMeshes();
  28472. // Software skinning
  28473. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  28474. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  28475. mesh.applySkeleton(mesh.skeleton);
  28476. }
  28477. // Render targets
  28478. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28479. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  28480. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  28481. }
  28482. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  28483. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  28484. }
  28485. // Collects render targets from external components.
  28486. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  28487. var step = _a[_i];
  28488. step.action(this._renderTargets);
  28489. }
  28490. if (this.renderTargetsEnabled) {
  28491. this._intermediateRendering = true;
  28492. if (this._renderTargets.length > 0) {
  28493. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28494. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  28495. var renderTarget = this._renderTargets.data[renderIndex];
  28496. if (renderTarget._shouldRender()) {
  28497. this._renderId++;
  28498. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  28499. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  28500. }
  28501. }
  28502. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28503. this._renderId++;
  28504. }
  28505. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  28506. var step = _c[_b];
  28507. step.action(this.activeCamera);
  28508. }
  28509. this._intermediateRendering = false;
  28510. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  28511. }
  28512. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28513. // Prepare Frame
  28514. if (this.postProcessManager) {
  28515. this.postProcessManager._prepareFrame();
  28516. }
  28517. // Before Camera Draw
  28518. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  28519. var step = _e[_d];
  28520. step.action(this.activeCamera);
  28521. }
  28522. // Render
  28523. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  28524. this._renderingManager.render(null, null, true, true);
  28525. this.onAfterDrawPhaseObservable.notifyObservers(this);
  28526. // After Camera Draw
  28527. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  28528. var step = _g[_f];
  28529. step.action(this.activeCamera);
  28530. }
  28531. // Finalize frame
  28532. if (this.postProcessManager) {
  28533. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  28534. }
  28535. // Reset some special arrays
  28536. this._renderTargets.reset();
  28537. this._alternateRendering = false;
  28538. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  28539. };
  28540. Scene.prototype._processSubCameras = function (camera) {
  28541. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  28542. this._renderForCamera(camera);
  28543. return;
  28544. }
  28545. // rig cameras
  28546. for (var index = 0; index < camera._rigCameras.length; index++) {
  28547. this._renderForCamera(camera._rigCameras[index], camera);
  28548. }
  28549. this.activeCamera = camera;
  28550. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28551. };
  28552. Scene.prototype._checkIntersections = function () {
  28553. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  28554. var sourceMesh = this._meshesForIntersections.data[index];
  28555. if (!sourceMesh.actionManager) {
  28556. continue;
  28557. }
  28558. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  28559. var action = sourceMesh.actionManager.actions[actionIndex];
  28560. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28561. var parameters = action.getTriggerParameter();
  28562. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  28563. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  28564. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  28565. if (areIntersecting && currentIntersectionInProgress === -1) {
  28566. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  28567. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28568. sourceMesh._intersectionsInProgress.push(otherMesh);
  28569. }
  28570. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28571. sourceMesh._intersectionsInProgress.push(otherMesh);
  28572. }
  28573. }
  28574. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  28575. //They intersected, and now they don't.
  28576. //is this trigger an exit trigger? execute an event.
  28577. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28578. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28579. }
  28580. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  28581. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  28582. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  28583. return otherMesh === parameterMesh;
  28584. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28585. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  28586. }
  28587. }
  28588. }
  28589. }
  28590. }
  28591. };
  28592. /** @hidden */
  28593. Scene.prototype._advancePhysicsEngineStep = function (step) {
  28594. // Do nothing. Code will be replaced if physics engine component is referenced
  28595. };
  28596. /**
  28597. * Render the scene
  28598. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  28599. */
  28600. Scene.prototype.render = function (updateCameras) {
  28601. if (updateCameras === void 0) { updateCameras = true; }
  28602. if (this.isDisposed) {
  28603. return;
  28604. }
  28605. this._frameId++;
  28606. // Register components that have been associated lately to the scene.
  28607. this._registerTransientComponents();
  28608. this._activeParticles.fetchNewFrame();
  28609. this._totalVertices.fetchNewFrame();
  28610. this._activeIndices.fetchNewFrame();
  28611. this._activeBones.fetchNewFrame();
  28612. this._meshesForIntersections.reset();
  28613. this.resetCachedMaterial();
  28614. this.onBeforeAnimationsObservable.notifyObservers(this);
  28615. // Actions
  28616. if (this.actionManager) {
  28617. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  28618. }
  28619. if (this._engine.isDeterministicLockStep()) {
  28620. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28621. var defaultFPS = (60.0 / 1000.0);
  28622. var defaultFrameTime = this.getDeterministicFrameTime();
  28623. var stepsTaken = 0;
  28624. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28625. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28626. internalSteps = Math.min(internalSteps, maxSubSteps);
  28627. do {
  28628. this.onBeforeStepObservable.notifyObservers(this);
  28629. // Animations
  28630. this._animationRatio = defaultFrameTime * defaultFPS;
  28631. this._animate();
  28632. this.onAfterAnimationsObservable.notifyObservers(this);
  28633. // Physics
  28634. this._advancePhysicsEngineStep(defaultFrameTime);
  28635. this.onAfterStepObservable.notifyObservers(this);
  28636. this._currentStepId++;
  28637. stepsTaken++;
  28638. deltaTime -= defaultFrameTime;
  28639. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28640. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28641. }
  28642. else {
  28643. // Animations
  28644. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28645. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28646. this._animate();
  28647. this.onAfterAnimationsObservable.notifyObservers(this);
  28648. // Physics
  28649. this._advancePhysicsEngineStep(deltaTime);
  28650. }
  28651. // Before camera update steps
  28652. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  28653. var step = _a[_i];
  28654. step.action();
  28655. }
  28656. // Update Cameras
  28657. if (updateCameras) {
  28658. if (this.activeCameras.length > 0) {
  28659. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28660. var camera = this.activeCameras[cameraIndex];
  28661. camera.update();
  28662. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28663. // rig cameras
  28664. for (var index = 0; index < camera._rigCameras.length; index++) {
  28665. camera._rigCameras[index].update();
  28666. }
  28667. }
  28668. }
  28669. }
  28670. else if (this.activeCamera) {
  28671. this.activeCamera.update();
  28672. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28673. // rig cameras
  28674. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28675. this.activeCamera._rigCameras[index].update();
  28676. }
  28677. }
  28678. }
  28679. }
  28680. // Before render
  28681. this.onBeforeRenderObservable.notifyObservers(this);
  28682. // Customs render targets
  28683. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28684. var engine = this.getEngine();
  28685. var currentActiveCamera = this.activeCamera;
  28686. if (this.renderTargetsEnabled) {
  28687. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28688. this._intermediateRendering = true;
  28689. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28690. var renderTarget = this.customRenderTargets[customIndex];
  28691. if (renderTarget._shouldRender()) {
  28692. this._renderId++;
  28693. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28694. if (!this.activeCamera)
  28695. throw new Error("Active camera not set");
  28696. // Viewport
  28697. engine.setViewport(this.activeCamera.viewport);
  28698. // Camera
  28699. this.updateTransformMatrix();
  28700. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28701. }
  28702. }
  28703. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28704. this._intermediateRendering = false;
  28705. this._renderId++;
  28706. }
  28707. // Restore back buffer
  28708. if (this.customRenderTargets.length > 0) {
  28709. engine.restoreDefaultFramebuffer();
  28710. }
  28711. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28712. this.activeCamera = currentActiveCamera;
  28713. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  28714. var step = _c[_b];
  28715. step.action();
  28716. }
  28717. // Clear
  28718. if (this.autoClearDepthAndStencil || this.autoClear) {
  28719. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28720. }
  28721. // Collects render targets from external components.
  28722. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  28723. var step = _e[_d];
  28724. step.action(this._renderTargets);
  28725. }
  28726. // Multi-cameras?
  28727. if (this.activeCameras.length > 0) {
  28728. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28729. if (cameraIndex > 0) {
  28730. this._engine.clear(null, false, true, true);
  28731. }
  28732. this._processSubCameras(this.activeCameras[cameraIndex]);
  28733. }
  28734. }
  28735. else {
  28736. if (!this.activeCamera) {
  28737. throw new Error("No camera defined");
  28738. }
  28739. this._processSubCameras(this.activeCamera);
  28740. }
  28741. // Intersection checks
  28742. this._checkIntersections();
  28743. // Executes the after render stage actions.
  28744. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  28745. var step = _g[_f];
  28746. step.action();
  28747. }
  28748. // After render
  28749. if (this.afterRender) {
  28750. this.afterRender();
  28751. }
  28752. this.onAfterRenderObservable.notifyObservers(this);
  28753. // Cleaning
  28754. if (this._toBeDisposed.length) {
  28755. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28756. var data = this._toBeDisposed[index];
  28757. if (data) {
  28758. data.dispose();
  28759. }
  28760. }
  28761. this._toBeDisposed = [];
  28762. }
  28763. if (this.dumpNextRenderTargets) {
  28764. this.dumpNextRenderTargets = false;
  28765. }
  28766. this._activeBones.addCount(0, true);
  28767. this._activeIndices.addCount(0, true);
  28768. this._activeParticles.addCount(0, true);
  28769. };
  28770. /**
  28771. * Freeze all materials
  28772. * A frozen material will not be updatable but should be faster to render
  28773. */
  28774. Scene.prototype.freezeMaterials = function () {
  28775. for (var i = 0; i < this.materials.length; i++) {
  28776. this.materials[i].freeze();
  28777. }
  28778. };
  28779. /**
  28780. * Unfreeze all materials
  28781. * A frozen material will not be updatable but should be faster to render
  28782. */
  28783. Scene.prototype.unfreezeMaterials = function () {
  28784. for (var i = 0; i < this.materials.length; i++) {
  28785. this.materials[i].unfreeze();
  28786. }
  28787. };
  28788. /**
  28789. * Releases all held ressources
  28790. */
  28791. Scene.prototype.dispose = function () {
  28792. this.beforeRender = null;
  28793. this.afterRender = null;
  28794. this.skeletons = [];
  28795. this.morphTargetManagers = [];
  28796. this._transientComponents = [];
  28797. this._isReadyForMeshStage.clear();
  28798. this._beforeEvaluateActiveMeshStage.clear();
  28799. this._evaluateSubMeshStage.clear();
  28800. this._activeMeshStage.clear();
  28801. this._cameraDrawRenderTargetStage.clear();
  28802. this._beforeCameraDrawStage.clear();
  28803. this._beforeRenderingGroupDrawStage.clear();
  28804. this._beforeRenderingMeshStage.clear();
  28805. this._afterRenderingMeshStage.clear();
  28806. this._afterRenderingGroupDrawStage.clear();
  28807. this._afterCameraDrawStage.clear();
  28808. this._afterRenderStage.clear();
  28809. this._beforeCameraUpdateStage.clear();
  28810. this._beforeClearStage.clear();
  28811. this._gatherRenderTargetsStage.clear();
  28812. this._gatherActiveCameraRenderTargetsStage.clear();
  28813. this._pointerMoveStage.clear();
  28814. this._pointerDownStage.clear();
  28815. this._pointerUpStage.clear();
  28816. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28817. var component = _a[_i];
  28818. component.dispose();
  28819. }
  28820. this.importedMeshesFiles = new Array();
  28821. this.stopAllAnimations();
  28822. this.resetCachedMaterial();
  28823. // Smart arrays
  28824. if (this.activeCamera) {
  28825. this.activeCamera._activeMeshes.dispose();
  28826. this.activeCamera = null;
  28827. }
  28828. this._activeMeshes.dispose();
  28829. this._renderingManager.dispose();
  28830. this._processedMaterials.dispose();
  28831. this._activeParticleSystems.dispose();
  28832. this._activeSkeletons.dispose();
  28833. this._softwareSkinnedMeshes.dispose();
  28834. this._renderTargets.dispose();
  28835. this._registeredForLateAnimationBindings.dispose();
  28836. this._meshesForIntersections.dispose();
  28837. this._toBeDisposed = [];
  28838. // Abort active requests
  28839. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28840. var request = _c[_b];
  28841. request.abort();
  28842. }
  28843. // Events
  28844. this.onDisposeObservable.notifyObservers(this);
  28845. this.onDisposeObservable.clear();
  28846. this.onBeforeRenderObservable.clear();
  28847. this.onAfterRenderObservable.clear();
  28848. this.onBeforeRenderTargetsRenderObservable.clear();
  28849. this.onAfterRenderTargetsRenderObservable.clear();
  28850. this.onAfterStepObservable.clear();
  28851. this.onBeforeStepObservable.clear();
  28852. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28853. this.onAfterActiveMeshesEvaluationObservable.clear();
  28854. this.onBeforeParticlesRenderingObservable.clear();
  28855. this.onAfterParticlesRenderingObservable.clear();
  28856. this.onBeforeDrawPhaseObservable.clear();
  28857. this.onAfterDrawPhaseObservable.clear();
  28858. this.onBeforeAnimationsObservable.clear();
  28859. this.onAfterAnimationsObservable.clear();
  28860. this.onDataLoadedObservable.clear();
  28861. this.onBeforeRenderingGroupObservable.clear();
  28862. this.onAfterRenderingGroupObservable.clear();
  28863. this.onMeshImportedObservable.clear();
  28864. this.onBeforeCameraRenderObservable.clear();
  28865. this.onAfterCameraRenderObservable.clear();
  28866. this.onReadyObservable.clear();
  28867. this.onNewCameraAddedObservable.clear();
  28868. this.onCameraRemovedObservable.clear();
  28869. this.onNewLightAddedObservable.clear();
  28870. this.onLightRemovedObservable.clear();
  28871. this.onNewGeometryAddedObservable.clear();
  28872. this.onGeometryRemovedObservable.clear();
  28873. this.onNewTransformNodeAddedObservable.clear();
  28874. this.onTransformNodeRemovedObservable.clear();
  28875. this.onNewMeshAddedObservable.clear();
  28876. this.onMeshRemovedObservable.clear();
  28877. this.onNewMaterialAddedObservable.clear();
  28878. this.onMaterialRemovedObservable.clear();
  28879. this.onNewTextureAddedObservable.clear();
  28880. this.onTextureRemovedObservable.clear();
  28881. this.onPrePointerObservable.clear();
  28882. this.onPointerObservable.clear();
  28883. this.onPreKeyboardObservable.clear();
  28884. this.onKeyboardObservable.clear();
  28885. this.detachControl();
  28886. // Detach cameras
  28887. var canvas = this._engine.getRenderingCanvas();
  28888. if (canvas) {
  28889. var index;
  28890. for (index = 0; index < this.cameras.length; index++) {
  28891. this.cameras[index].detachControl(canvas);
  28892. }
  28893. }
  28894. // Release animation groups
  28895. while (this.animationGroups.length) {
  28896. this.animationGroups[0].dispose();
  28897. }
  28898. // Release lights
  28899. while (this.lights.length) {
  28900. this.lights[0].dispose();
  28901. }
  28902. // Release meshes
  28903. while (this.meshes.length) {
  28904. this.meshes[0].dispose(true);
  28905. }
  28906. while (this.transformNodes.length) {
  28907. this.removeTransformNode(this.transformNodes[0]);
  28908. }
  28909. // Release cameras
  28910. while (this.cameras.length) {
  28911. this.cameras[0].dispose();
  28912. }
  28913. // Release materials
  28914. if (this.defaultMaterial) {
  28915. this.defaultMaterial.dispose();
  28916. }
  28917. while (this.multiMaterials.length) {
  28918. this.multiMaterials[0].dispose();
  28919. }
  28920. while (this.materials.length) {
  28921. this.materials[0].dispose();
  28922. }
  28923. // Release particles
  28924. while (this.particleSystems.length) {
  28925. this.particleSystems[0].dispose();
  28926. }
  28927. // Release postProcesses
  28928. while (this.postProcesses.length) {
  28929. this.postProcesses[0].dispose();
  28930. }
  28931. // Release textures
  28932. while (this.textures.length) {
  28933. this.textures[0].dispose();
  28934. }
  28935. // Release UBO
  28936. this._sceneUbo.dispose();
  28937. if (this._alternateSceneUbo) {
  28938. this._alternateSceneUbo.dispose();
  28939. }
  28940. // Post-processes
  28941. this.postProcessManager.dispose();
  28942. // Remove from engine
  28943. index = this._engine.scenes.indexOf(this);
  28944. if (index > -1) {
  28945. this._engine.scenes.splice(index, 1);
  28946. }
  28947. this._engine.wipeCaches(true);
  28948. this._isDisposed = true;
  28949. };
  28950. Object.defineProperty(Scene.prototype, "isDisposed", {
  28951. /**
  28952. * Gets if the scene is already disposed
  28953. */
  28954. get: function () {
  28955. return this._isDisposed;
  28956. },
  28957. enumerable: true,
  28958. configurable: true
  28959. });
  28960. /**
  28961. * Call this function to reduce memory footprint of the scene.
  28962. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28963. */
  28964. Scene.prototype.clearCachedVertexData = function () {
  28965. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28966. var mesh = this.meshes[meshIndex];
  28967. var geometry = mesh.geometry;
  28968. if (geometry) {
  28969. geometry._indices = [];
  28970. for (var vbName in geometry._vertexBuffers) {
  28971. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28972. continue;
  28973. }
  28974. geometry._vertexBuffers[vbName]._buffer._data = null;
  28975. }
  28976. }
  28977. }
  28978. };
  28979. /**
  28980. * This function will remove the local cached buffer data from texture.
  28981. * It will save memory but will prevent the texture from being rebuilt
  28982. */
  28983. Scene.prototype.cleanCachedTextureBuffer = function () {
  28984. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28985. var baseTexture = _a[_i];
  28986. var buffer = baseTexture._buffer;
  28987. if (buffer) {
  28988. baseTexture._buffer = null;
  28989. }
  28990. }
  28991. };
  28992. /**
  28993. * Get the world extend vectors with an optional filter
  28994. *
  28995. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28996. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28997. */
  28998. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28999. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29000. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  29001. filterPredicate = filterPredicate || (function () { return true; });
  29002. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  29003. mesh.computeWorldMatrix(true);
  29004. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  29005. return;
  29006. }
  29007. var boundingInfo = mesh.getBoundingInfo();
  29008. var minBox = boundingInfo.boundingBox.minimumWorld;
  29009. var maxBox = boundingInfo.boundingBox.maximumWorld;
  29010. BABYLON.Tools.CheckExtends(minBox, min, max);
  29011. BABYLON.Tools.CheckExtends(maxBox, min, max);
  29012. });
  29013. return {
  29014. min: min,
  29015. max: max
  29016. };
  29017. };
  29018. // Picking
  29019. /**
  29020. * Creates a ray that can be used to pick in the scene
  29021. * @param x defines the x coordinate of the origin (on-screen)
  29022. * @param y defines the y coordinate of the origin (on-screen)
  29023. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29024. * @param camera defines the camera to use for the picking
  29025. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29026. * @returns a Ray
  29027. */
  29028. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  29029. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29030. var result = BABYLON.Ray.Zero();
  29031. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  29032. return result;
  29033. };
  29034. /**
  29035. * Creates a ray that can be used to pick in the scene
  29036. * @param x defines the x coordinate of the origin (on-screen)
  29037. * @param y defines the y coordinate of the origin (on-screen)
  29038. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29039. * @param result defines the ray where to store the picking ray
  29040. * @param camera defines the camera to use for the picking
  29041. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29042. * @returns the current scene
  29043. */
  29044. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  29045. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29046. var engine = this._engine;
  29047. if (!camera) {
  29048. if (!this.activeCamera)
  29049. throw new Error("Active camera not set");
  29050. camera = this.activeCamera;
  29051. }
  29052. var cameraViewport = camera.viewport;
  29053. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29054. // Moving coordinates to local viewport world
  29055. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29056. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29057. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  29058. return this;
  29059. };
  29060. /**
  29061. * Creates a ray that can be used to pick in the scene
  29062. * @param x defines the x coordinate of the origin (on-screen)
  29063. * @param y defines the y coordinate of the origin (on-screen)
  29064. * @param camera defines the camera to use for the picking
  29065. * @returns a Ray
  29066. */
  29067. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  29068. var result = BABYLON.Ray.Zero();
  29069. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  29070. return result;
  29071. };
  29072. /**
  29073. * Creates a ray that can be used to pick in the scene
  29074. * @param x defines the x coordinate of the origin (on-screen)
  29075. * @param y defines the y coordinate of the origin (on-screen)
  29076. * @param result defines the ray where to store the picking ray
  29077. * @param camera defines the camera to use for the picking
  29078. * @returns the current scene
  29079. */
  29080. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  29081. if (!BABYLON.PickingInfo) {
  29082. return this;
  29083. }
  29084. var engine = this._engine;
  29085. if (!camera) {
  29086. if (!this.activeCamera)
  29087. throw new Error("Active camera not set");
  29088. camera = this.activeCamera;
  29089. }
  29090. var cameraViewport = camera.viewport;
  29091. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29092. var identity = BABYLON.Matrix.Identity();
  29093. // Moving coordinates to local viewport world
  29094. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29095. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29096. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  29097. return this;
  29098. };
  29099. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  29100. if (!BABYLON.PickingInfo) {
  29101. return null;
  29102. }
  29103. var pickingInfo = null;
  29104. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29105. var mesh = this.meshes[meshIndex];
  29106. if (predicate) {
  29107. if (!predicate(mesh)) {
  29108. continue;
  29109. }
  29110. }
  29111. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29112. continue;
  29113. }
  29114. var world = mesh.getWorldMatrix();
  29115. var ray = rayFunction(world);
  29116. var result = mesh.intersects(ray, fastCheck);
  29117. if (!result || !result.hit)
  29118. continue;
  29119. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  29120. continue;
  29121. pickingInfo = result;
  29122. if (fastCheck) {
  29123. break;
  29124. }
  29125. }
  29126. return pickingInfo || new BABYLON.PickingInfo();
  29127. };
  29128. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  29129. if (!BABYLON.PickingInfo) {
  29130. return null;
  29131. }
  29132. var pickingInfos = new Array();
  29133. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29134. var mesh = this.meshes[meshIndex];
  29135. if (predicate) {
  29136. if (!predicate(mesh)) {
  29137. continue;
  29138. }
  29139. }
  29140. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29141. continue;
  29142. }
  29143. var world = mesh.getWorldMatrix();
  29144. var ray = rayFunction(world);
  29145. var result = mesh.intersects(ray, false);
  29146. if (!result || !result.hit)
  29147. continue;
  29148. pickingInfos.push(result);
  29149. }
  29150. return pickingInfos;
  29151. };
  29152. /** Launch a ray to try to pick a mesh in the scene
  29153. * @param x position on screen
  29154. * @param y position on screen
  29155. * @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
  29156. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  29157. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29158. * @returns a PickingInfo
  29159. */
  29160. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  29161. var _this = this;
  29162. if (!BABYLON.PickingInfo) {
  29163. return null;
  29164. }
  29165. var result = this._internalPick(function (world) {
  29166. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  29167. return _this._tempPickingRay;
  29168. }, predicate, fastCheck);
  29169. if (result) {
  29170. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  29171. }
  29172. return result;
  29173. };
  29174. /** Use the given ray to pick a mesh in the scene
  29175. * @param ray The ray to use to pick meshes
  29176. * @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
  29177. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  29178. * @returns a PickingInfo
  29179. */
  29180. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  29181. var _this = this;
  29182. var result = this._internalPick(function (world) {
  29183. if (!_this._pickWithRayInverseMatrix) {
  29184. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29185. }
  29186. world.invertToRef(_this._pickWithRayInverseMatrix);
  29187. if (!_this._cachedRayForTransform) {
  29188. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29189. }
  29190. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29191. return _this._cachedRayForTransform;
  29192. }, predicate, fastCheck);
  29193. if (result) {
  29194. result.ray = ray;
  29195. }
  29196. return result;
  29197. };
  29198. /**
  29199. * Launch a ray to try to pick a mesh in the scene
  29200. * @param x X position on screen
  29201. * @param y Y position on screen
  29202. * @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
  29203. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29204. * @returns an array of PickingInfo
  29205. */
  29206. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  29207. var _this = this;
  29208. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  29209. };
  29210. /**
  29211. * Launch a ray to try to pick a mesh in the scene
  29212. * @param ray Ray to use
  29213. * @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
  29214. * @returns an array of PickingInfo
  29215. */
  29216. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  29217. var _this = this;
  29218. return this._internalMultiPick(function (world) {
  29219. if (!_this._pickWithRayInverseMatrix) {
  29220. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29221. }
  29222. world.invertToRef(_this._pickWithRayInverseMatrix);
  29223. if (!_this._cachedRayForTransform) {
  29224. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29225. }
  29226. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29227. return _this._cachedRayForTransform;
  29228. }, predicate);
  29229. };
  29230. /**
  29231. * Force the value of meshUnderPointer
  29232. * @param mesh defines the mesh to use
  29233. */
  29234. Scene.prototype.setPointerOverMesh = function (mesh) {
  29235. if (this._pointerOverMesh === mesh) {
  29236. return;
  29237. }
  29238. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29239. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29240. }
  29241. this._pointerOverMesh = mesh;
  29242. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29243. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29244. }
  29245. };
  29246. /**
  29247. * Gets the mesh under the pointer
  29248. * @returns a Mesh or null if no mesh is under the pointer
  29249. */
  29250. Scene.prototype.getPointerOverMesh = function () {
  29251. return this._pointerOverMesh;
  29252. };
  29253. // Misc.
  29254. /** @hidden */
  29255. Scene.prototype._rebuildGeometries = function () {
  29256. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  29257. var geometry = _a[_i];
  29258. geometry._rebuild();
  29259. }
  29260. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  29261. var mesh = _c[_b];
  29262. mesh._rebuild();
  29263. }
  29264. if (this.postProcessManager) {
  29265. this.postProcessManager._rebuild();
  29266. }
  29267. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  29268. var component = _e[_d];
  29269. component.rebuild();
  29270. }
  29271. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  29272. var system = _g[_f];
  29273. system.rebuild();
  29274. }
  29275. };
  29276. /** @hidden */
  29277. Scene.prototype._rebuildTextures = function () {
  29278. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29279. var texture = _a[_i];
  29280. texture._rebuild();
  29281. }
  29282. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29283. };
  29284. // Tags
  29285. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29286. if (tagsQuery === undefined) {
  29287. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29288. return list;
  29289. }
  29290. var listByTags = [];
  29291. forEach = forEach || (function (item) { return; });
  29292. for (var i in list) {
  29293. var item = list[i];
  29294. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29295. listByTags.push(item);
  29296. forEach(item);
  29297. }
  29298. }
  29299. return listByTags;
  29300. };
  29301. /**
  29302. * Get a list of meshes by tags
  29303. * @param tagsQuery defines the tags query to use
  29304. * @param forEach defines a predicate used to filter results
  29305. * @returns an array of Mesh
  29306. */
  29307. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29308. return this._getByTags(this.meshes, tagsQuery, forEach);
  29309. };
  29310. /**
  29311. * Get a list of cameras by tags
  29312. * @param tagsQuery defines the tags query to use
  29313. * @param forEach defines a predicate used to filter results
  29314. * @returns an array of Camera
  29315. */
  29316. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29317. return this._getByTags(this.cameras, tagsQuery, forEach);
  29318. };
  29319. /**
  29320. * Get a list of lights by tags
  29321. * @param tagsQuery defines the tags query to use
  29322. * @param forEach defines a predicate used to filter results
  29323. * @returns an array of Light
  29324. */
  29325. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29326. return this._getByTags(this.lights, tagsQuery, forEach);
  29327. };
  29328. /**
  29329. * Get a list of materials by tags
  29330. * @param tagsQuery defines the tags query to use
  29331. * @param forEach defines a predicate used to filter results
  29332. * @returns an array of Material
  29333. */
  29334. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29335. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29336. };
  29337. /**
  29338. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29339. * This allowed control for front to back rendering or reversly depending of the special needs.
  29340. *
  29341. * @param renderingGroupId The rendering group id corresponding to its index
  29342. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29343. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29344. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29345. */
  29346. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29347. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29348. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29349. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29350. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29351. };
  29352. /**
  29353. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29354. *
  29355. * @param renderingGroupId The rendering group id corresponding to its index
  29356. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29357. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29358. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29359. */
  29360. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29361. if (depth === void 0) { depth = true; }
  29362. if (stencil === void 0) { stencil = true; }
  29363. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29364. };
  29365. /**
  29366. * Gets the current auto clear configuration for one rendering group of the rendering
  29367. * manager.
  29368. * @param index the rendering group index to get the information for
  29369. * @returns The auto clear setup for the requested rendering group
  29370. */
  29371. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  29372. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  29373. };
  29374. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  29375. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  29376. get: function () {
  29377. return this._blockMaterialDirtyMechanism;
  29378. },
  29379. set: function (value) {
  29380. if (this._blockMaterialDirtyMechanism === value) {
  29381. return;
  29382. }
  29383. this._blockMaterialDirtyMechanism = value;
  29384. if (!value) { // Do a complete update
  29385. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  29386. }
  29387. },
  29388. enumerable: true,
  29389. configurable: true
  29390. });
  29391. /**
  29392. * Will flag all materials as dirty to trigger new shader compilation
  29393. * @param flag defines the flag used to specify which material part must be marked as dirty
  29394. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29395. */
  29396. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29397. if (this._blockMaterialDirtyMechanism) {
  29398. return;
  29399. }
  29400. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29401. var material = _a[_i];
  29402. if (predicate && !predicate(material)) {
  29403. continue;
  29404. }
  29405. material.markAsDirty(flag);
  29406. }
  29407. };
  29408. /** @hidden */
  29409. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29410. var _this = this;
  29411. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29412. this._activeRequests.push(request);
  29413. request.onCompleteObservable.add(function (request) {
  29414. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29415. });
  29416. return request;
  29417. };
  29418. /** @hidden */
  29419. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29420. var _this = this;
  29421. return new Promise(function (resolve, reject) {
  29422. _this._loadFile(url, function (data) {
  29423. resolve(data);
  29424. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29425. reject(exception);
  29426. });
  29427. });
  29428. };
  29429. // Statics
  29430. Scene._uniqueIdCounter = 0;
  29431. /** The fog is deactivated */
  29432. Scene.FOGMODE_NONE = 0;
  29433. /** The fog density is following an exponential function */
  29434. Scene.FOGMODE_EXP = 1;
  29435. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29436. Scene.FOGMODE_EXP2 = 2;
  29437. /** The fog density is following a linear function. */
  29438. Scene.FOGMODE_LINEAR = 3;
  29439. /**
  29440. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29441. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29442. */
  29443. Scene.MinDeltaTime = 1.0;
  29444. /**
  29445. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29446. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29447. */
  29448. Scene.MaxDeltaTime = 1000.0;
  29449. /** The distance in pixel that you have to move to prevent some events */
  29450. Scene.DragMovementThreshold = 10; // in pixels
  29451. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29452. Scene.LongPressDelay = 500; // in milliseconds
  29453. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29454. Scene.DoubleClickDelay = 300; // in milliseconds
  29455. /** If you need to check double click without raising a single click at first click, enable this flag */
  29456. Scene.ExclusiveDoubleClickMode = false;
  29457. return Scene;
  29458. }(BABYLON.AbstractScene));
  29459. BABYLON.Scene = Scene;
  29460. })(BABYLON || (BABYLON = {}));
  29461. //# sourceMappingURL=babylon.scene.js.map
  29462. var BABYLON;
  29463. (function (BABYLON) {
  29464. /**
  29465. * Set of assets to keep when moving a scene into an asset container.
  29466. */
  29467. var KeepAssets = /** @class */ (function (_super) {
  29468. __extends(KeepAssets, _super);
  29469. function KeepAssets() {
  29470. return _super !== null && _super.apply(this, arguments) || this;
  29471. }
  29472. return KeepAssets;
  29473. }(BABYLON.AbstractScene));
  29474. BABYLON.KeepAssets = KeepAssets;
  29475. /**
  29476. * Container with a set of assets that can be added or removed from a scene.
  29477. */
  29478. var AssetContainer = /** @class */ (function (_super) {
  29479. __extends(AssetContainer, _super);
  29480. /**
  29481. * Instantiates an AssetContainer.
  29482. * @param scene The scene the AssetContainer belongs to.
  29483. */
  29484. function AssetContainer(scene) {
  29485. var _this = _super.call(this) || this;
  29486. _this.scene = scene;
  29487. return _this;
  29488. }
  29489. /**
  29490. * Adds all the assets from the container to the scene.
  29491. */
  29492. AssetContainer.prototype.addAllToScene = function () {
  29493. var _this = this;
  29494. this.cameras.forEach(function (o) {
  29495. _this.scene.addCamera(o);
  29496. });
  29497. this.lights.forEach(function (o) {
  29498. _this.scene.addLight(o);
  29499. });
  29500. this.meshes.forEach(function (o) {
  29501. _this.scene.addMesh(o);
  29502. });
  29503. this.skeletons.forEach(function (o) {
  29504. _this.scene.addSkeleton(o);
  29505. });
  29506. this.animations.forEach(function (o) {
  29507. _this.scene.addAnimation(o);
  29508. });
  29509. this.animationGroups.forEach(function (o) {
  29510. _this.scene.addAnimationGroup(o);
  29511. });
  29512. this.multiMaterials.forEach(function (o) {
  29513. _this.scene.addMultiMaterial(o);
  29514. });
  29515. this.materials.forEach(function (o) {
  29516. _this.scene.addMaterial(o);
  29517. });
  29518. this.morphTargetManagers.forEach(function (o) {
  29519. _this.scene.addMorphTargetManager(o);
  29520. });
  29521. this.geometries.forEach(function (o) {
  29522. _this.scene.addGeometry(o);
  29523. });
  29524. this.transformNodes.forEach(function (o) {
  29525. _this.scene.addTransformNode(o);
  29526. });
  29527. this.actionManagers.forEach(function (o) {
  29528. _this.scene.addActionManager(o);
  29529. });
  29530. this.textures.forEach(function (o) {
  29531. _this.scene.addTexture(o);
  29532. });
  29533. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29534. var component = _a[_i];
  29535. component.addFromContainer(this.scene);
  29536. }
  29537. };
  29538. /**
  29539. * Removes all the assets in the container from the scene
  29540. */
  29541. AssetContainer.prototype.removeAllFromScene = function () {
  29542. var _this = this;
  29543. this.cameras.forEach(function (o) {
  29544. _this.scene.removeCamera(o);
  29545. });
  29546. this.lights.forEach(function (o) {
  29547. _this.scene.removeLight(o);
  29548. });
  29549. this.meshes.forEach(function (o) {
  29550. _this.scene.removeMesh(o);
  29551. });
  29552. this.skeletons.forEach(function (o) {
  29553. _this.scene.removeSkeleton(o);
  29554. });
  29555. this.animations.forEach(function (o) {
  29556. _this.scene.removeAnimation(o);
  29557. });
  29558. this.animationGroups.forEach(function (o) {
  29559. _this.scene.removeAnimationGroup(o);
  29560. });
  29561. this.multiMaterials.forEach(function (o) {
  29562. _this.scene.removeMultiMaterial(o);
  29563. });
  29564. this.materials.forEach(function (o) {
  29565. _this.scene.removeMaterial(o);
  29566. });
  29567. this.morphTargetManagers.forEach(function (o) {
  29568. _this.scene.removeMorphTargetManager(o);
  29569. });
  29570. this.geometries.forEach(function (o) {
  29571. _this.scene.removeGeometry(o);
  29572. });
  29573. this.transformNodes.forEach(function (o) {
  29574. _this.scene.removeTransformNode(o);
  29575. });
  29576. this.actionManagers.forEach(function (o) {
  29577. _this.scene.removeActionManager(o);
  29578. });
  29579. this.textures.forEach(function (o) {
  29580. _this.scene.removeTexture(o);
  29581. });
  29582. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29583. var component = _a[_i];
  29584. component.removeFromContainer(this.scene);
  29585. }
  29586. };
  29587. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29588. if (!sourceAssets) {
  29589. return;
  29590. }
  29591. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29592. var asset = sourceAssets_1[_i];
  29593. var move = true;
  29594. if (keepAssets) {
  29595. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29596. var keepAsset = keepAssets_1[_a];
  29597. if (asset === keepAsset) {
  29598. move = false;
  29599. break;
  29600. }
  29601. }
  29602. }
  29603. if (move) {
  29604. targetAssets.push(asset);
  29605. }
  29606. }
  29607. };
  29608. /**
  29609. * Removes all the assets contained in the scene and adds them to the container.
  29610. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29611. */
  29612. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29613. if (keepAssets === undefined) {
  29614. keepAssets = new KeepAssets();
  29615. }
  29616. for (var key in this) {
  29617. if (this.hasOwnProperty(key)) {
  29618. this[key] = this[key] || [];
  29619. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29620. }
  29621. }
  29622. this.removeAllFromScene();
  29623. };
  29624. /**
  29625. * 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.
  29626. * @returns the root mesh
  29627. */
  29628. AssetContainer.prototype.createRootMesh = function () {
  29629. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29630. this.meshes.forEach(function (m) {
  29631. if (!m.parent) {
  29632. rootMesh.addChild(m);
  29633. }
  29634. });
  29635. this.meshes.unshift(rootMesh);
  29636. return rootMesh;
  29637. };
  29638. return AssetContainer;
  29639. }(BABYLON.AbstractScene));
  29640. BABYLON.AssetContainer = AssetContainer;
  29641. })(BABYLON || (BABYLON = {}));
  29642. //# sourceMappingURL=babylon.assetContainer.js.map
  29643. var BABYLON;
  29644. (function (BABYLON) {
  29645. /**
  29646. * Class used to store data that will be store in GPU memory
  29647. */
  29648. var Buffer = /** @class */ (function () {
  29649. /**
  29650. * Constructor
  29651. * @param engine the engine
  29652. * @param data the data to use for this buffer
  29653. * @param updatable whether the data is updatable
  29654. * @param stride the stride (optional)
  29655. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29656. * @param instanced whether the buffer is instanced (optional)
  29657. * @param useBytes set to true if the stride in in bytes (optional)
  29658. */
  29659. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29660. if (stride === void 0) { stride = 0; }
  29661. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29662. if (instanced === void 0) { instanced = false; }
  29663. if (useBytes === void 0) { useBytes = false; }
  29664. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29665. this._engine = engine.getScene().getEngine();
  29666. }
  29667. else {
  29668. this._engine = engine;
  29669. }
  29670. this._updatable = updatable;
  29671. this._instanced = instanced;
  29672. this._data = data;
  29673. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29674. if (!postponeInternalCreation) { // by default
  29675. this.create();
  29676. }
  29677. }
  29678. /**
  29679. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29680. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29681. * @param offset defines offset in the buffer (0 by default)
  29682. * @param size defines the size in floats of attributes (position is 3 for instance)
  29683. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29684. * @param instanced defines if the vertex buffer contains indexed data
  29685. * @param useBytes defines if the offset and stride are in bytes
  29686. * @returns the new vertex buffer
  29687. */
  29688. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29689. if (useBytes === void 0) { useBytes = false; }
  29690. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29691. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29692. // a lot of these parameters are ignored as they are overriden by the buffer
  29693. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29694. };
  29695. // Properties
  29696. /**
  29697. * Gets a boolean indicating if the Buffer is updatable?
  29698. * @returns true if the buffer is updatable
  29699. */
  29700. Buffer.prototype.isUpdatable = function () {
  29701. return this._updatable;
  29702. };
  29703. /**
  29704. * Gets current buffer's data
  29705. * @returns a DataArray or null
  29706. */
  29707. Buffer.prototype.getData = function () {
  29708. return this._data;
  29709. };
  29710. /**
  29711. * Gets underlying native buffer
  29712. * @returns underlying native buffer
  29713. */
  29714. Buffer.prototype.getBuffer = function () {
  29715. return this._buffer;
  29716. };
  29717. /**
  29718. * Gets the stride in float32 units (i.e. byte stride / 4).
  29719. * May not be an integer if the byte stride is not divisible by 4.
  29720. * DEPRECATED. Use byteStride instead.
  29721. * @returns the stride in float32 units
  29722. */
  29723. Buffer.prototype.getStrideSize = function () {
  29724. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29725. };
  29726. // Methods
  29727. /**
  29728. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  29729. * @param data defines the data to store
  29730. */
  29731. Buffer.prototype.create = function (data) {
  29732. if (data === void 0) { data = null; }
  29733. if (!data && this._buffer) {
  29734. return; // nothing to do
  29735. }
  29736. data = data || this._data;
  29737. if (!data) {
  29738. return;
  29739. }
  29740. if (!this._buffer) { // create buffer
  29741. if (this._updatable) {
  29742. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29743. this._data = data;
  29744. }
  29745. else {
  29746. this._buffer = this._engine.createVertexBuffer(data);
  29747. }
  29748. }
  29749. else if (this._updatable) { // update buffer
  29750. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29751. this._data = data;
  29752. }
  29753. };
  29754. /** @hidden */
  29755. Buffer.prototype._rebuild = function () {
  29756. this._buffer = null;
  29757. this.create(this._data);
  29758. };
  29759. /**
  29760. * Update current buffer data
  29761. * @param data defines the data to store
  29762. */
  29763. Buffer.prototype.update = function (data) {
  29764. this.create(data);
  29765. };
  29766. /**
  29767. * Updates the data directly.
  29768. * @param data the new data
  29769. * @param offset the new offset
  29770. * @param vertexCount the vertex count (optional)
  29771. * @param useBytes set to true if the offset is in bytes
  29772. */
  29773. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29774. if (useBytes === void 0) { useBytes = false; }
  29775. if (!this._buffer) {
  29776. return;
  29777. }
  29778. if (this._updatable) { // update buffer
  29779. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29780. this._data = null;
  29781. }
  29782. };
  29783. /**
  29784. * Release all resources
  29785. */
  29786. Buffer.prototype.dispose = function () {
  29787. if (!this._buffer) {
  29788. return;
  29789. }
  29790. if (this._engine._releaseBuffer(this._buffer)) {
  29791. this._buffer = null;
  29792. }
  29793. };
  29794. return Buffer;
  29795. }());
  29796. BABYLON.Buffer = Buffer;
  29797. })(BABYLON || (BABYLON = {}));
  29798. //# sourceMappingURL=babylon.buffer.js.map
  29799. var BABYLON;
  29800. (function (BABYLON) {
  29801. /**
  29802. * Specialized buffer used to store vertex data
  29803. */
  29804. var VertexBuffer = /** @class */ (function () {
  29805. /**
  29806. * Constructor
  29807. * @param engine the engine
  29808. * @param data the data to use for this vertex buffer
  29809. * @param kind the vertex buffer kind
  29810. * @param updatable whether the data is updatable
  29811. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29812. * @param stride the stride (optional)
  29813. * @param instanced whether the buffer is instanced (optional)
  29814. * @param offset the offset of the data (optional)
  29815. * @param size the number of components (optional)
  29816. * @param type the type of the component (optional)
  29817. * @param normalized whether the data contains normalized data (optional)
  29818. * @param useBytes set to true if stride and offset are in bytes (optional)
  29819. */
  29820. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29821. if (normalized === void 0) { normalized = false; }
  29822. if (useBytes === void 0) { useBytes = false; }
  29823. if (data instanceof BABYLON.Buffer) {
  29824. this._buffer = data;
  29825. this._ownsBuffer = false;
  29826. }
  29827. else {
  29828. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29829. this._ownsBuffer = true;
  29830. }
  29831. this._kind = kind;
  29832. if (type == undefined) {
  29833. var data_1 = this.getData();
  29834. this.type = VertexBuffer.FLOAT;
  29835. if (data_1 instanceof Int8Array)
  29836. this.type = VertexBuffer.BYTE;
  29837. else if (data_1 instanceof Uint8Array)
  29838. this.type = VertexBuffer.UNSIGNED_BYTE;
  29839. else if (data_1 instanceof Int16Array)
  29840. this.type = VertexBuffer.SHORT;
  29841. else if (data_1 instanceof Uint16Array)
  29842. this.type = VertexBuffer.UNSIGNED_SHORT;
  29843. else if (data_1 instanceof Int32Array)
  29844. this.type = VertexBuffer.INT;
  29845. else if (data_1 instanceof Uint32Array)
  29846. this.type = VertexBuffer.UNSIGNED_INT;
  29847. }
  29848. else {
  29849. this.type = type;
  29850. }
  29851. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29852. if (useBytes) {
  29853. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29854. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29855. this.byteOffset = offset || 0;
  29856. }
  29857. else {
  29858. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29859. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29860. this.byteOffset = (offset || 0) * typeByteLength;
  29861. }
  29862. this.normalized = normalized;
  29863. this._instanced = instanced !== undefined ? instanced : false;
  29864. this._instanceDivisor = instanced ? 1 : 0;
  29865. }
  29866. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29867. /**
  29868. * Gets or sets the instance divisor when in instanced mode
  29869. */
  29870. get: function () {
  29871. return this._instanceDivisor;
  29872. },
  29873. set: function (value) {
  29874. this._instanceDivisor = value;
  29875. if (value == 0) {
  29876. this._instanced = false;
  29877. }
  29878. else {
  29879. this._instanced = true;
  29880. }
  29881. },
  29882. enumerable: true,
  29883. configurable: true
  29884. });
  29885. /** @hidden */
  29886. VertexBuffer.prototype._rebuild = function () {
  29887. if (!this._buffer) {
  29888. return;
  29889. }
  29890. this._buffer._rebuild();
  29891. };
  29892. /**
  29893. * Returns the kind of the VertexBuffer (string)
  29894. * @returns a string
  29895. */
  29896. VertexBuffer.prototype.getKind = function () {
  29897. return this._kind;
  29898. };
  29899. // Properties
  29900. /**
  29901. * Gets a boolean indicating if the VertexBuffer is updatable?
  29902. * @returns true if the buffer is updatable
  29903. */
  29904. VertexBuffer.prototype.isUpdatable = function () {
  29905. return this._buffer.isUpdatable();
  29906. };
  29907. /**
  29908. * Gets current buffer's data
  29909. * @returns a DataArray or null
  29910. */
  29911. VertexBuffer.prototype.getData = function () {
  29912. return this._buffer.getData();
  29913. };
  29914. /**
  29915. * Gets underlying native buffer
  29916. * @returns underlying native buffer
  29917. */
  29918. VertexBuffer.prototype.getBuffer = function () {
  29919. return this._buffer.getBuffer();
  29920. };
  29921. /**
  29922. * Gets the stride in float32 units (i.e. byte stride / 4).
  29923. * May not be an integer if the byte stride is not divisible by 4.
  29924. * DEPRECATED. Use byteStride instead.
  29925. * @returns the stride in float32 units
  29926. */
  29927. VertexBuffer.prototype.getStrideSize = function () {
  29928. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29929. };
  29930. /**
  29931. * Returns the offset as a multiple of the type byte length.
  29932. * DEPRECATED. Use byteOffset instead.
  29933. * @returns the offset in bytes
  29934. */
  29935. VertexBuffer.prototype.getOffset = function () {
  29936. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29937. };
  29938. /**
  29939. * Returns the number of components per vertex attribute (integer)
  29940. * @returns the size in float
  29941. */
  29942. VertexBuffer.prototype.getSize = function () {
  29943. return this._size;
  29944. };
  29945. /**
  29946. * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
  29947. * @returns true if this buffer is instanced
  29948. */
  29949. VertexBuffer.prototype.getIsInstanced = function () {
  29950. return this._instanced;
  29951. };
  29952. /**
  29953. * Returns the instancing divisor, zero for non-instanced (integer).
  29954. * @returns a number
  29955. */
  29956. VertexBuffer.prototype.getInstanceDivisor = function () {
  29957. return this._instanceDivisor;
  29958. };
  29959. // Methods
  29960. /**
  29961. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  29962. * @param data defines the data to store
  29963. */
  29964. VertexBuffer.prototype.create = function (data) {
  29965. this._buffer.create(data);
  29966. };
  29967. /**
  29968. * Updates the underlying buffer according to the passed numeric array or Float32Array.
  29969. * This function will create a new buffer if the current one is not updatable
  29970. * @param data defines the data to store
  29971. */
  29972. VertexBuffer.prototype.update = function (data) {
  29973. this._buffer.update(data);
  29974. };
  29975. /**
  29976. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29977. * Returns the directly updated WebGLBuffer.
  29978. * @param data the new data
  29979. * @param offset the new offset
  29980. * @param useBytes set to true if the offset is in bytes
  29981. */
  29982. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29983. if (useBytes === void 0) { useBytes = false; }
  29984. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29985. };
  29986. /**
  29987. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29988. */
  29989. VertexBuffer.prototype.dispose = function () {
  29990. if (this._ownsBuffer) {
  29991. this._buffer.dispose();
  29992. }
  29993. };
  29994. /**
  29995. * Enumerates each value of this vertex buffer as numbers.
  29996. * @param count the number of values to enumerate
  29997. * @param callback the callback function called for each value
  29998. */
  29999. VertexBuffer.prototype.forEach = function (count, callback) {
  30000. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  30001. };
  30002. /**
  30003. * Deduces the stride given a kind.
  30004. * @param kind The kind string to deduce
  30005. * @returns The deduced stride
  30006. */
  30007. VertexBuffer.DeduceStride = function (kind) {
  30008. switch (kind) {
  30009. case VertexBuffer.UVKind:
  30010. case VertexBuffer.UV2Kind:
  30011. case VertexBuffer.UV3Kind:
  30012. case VertexBuffer.UV4Kind:
  30013. case VertexBuffer.UV5Kind:
  30014. case VertexBuffer.UV6Kind:
  30015. return 2;
  30016. case VertexBuffer.NormalKind:
  30017. case VertexBuffer.PositionKind:
  30018. return 3;
  30019. case VertexBuffer.ColorKind:
  30020. case VertexBuffer.MatricesIndicesKind:
  30021. case VertexBuffer.MatricesIndicesExtraKind:
  30022. case VertexBuffer.MatricesWeightsKind:
  30023. case VertexBuffer.MatricesWeightsExtraKind:
  30024. case VertexBuffer.TangentKind:
  30025. return 4;
  30026. default:
  30027. throw new Error("Invalid kind '" + kind + "'");
  30028. }
  30029. };
  30030. /**
  30031. * Gets the byte length of the given type.
  30032. * @param type the type
  30033. * @returns the number of bytes
  30034. */
  30035. VertexBuffer.GetTypeByteLength = function (type) {
  30036. switch (type) {
  30037. case VertexBuffer.BYTE:
  30038. case VertexBuffer.UNSIGNED_BYTE:
  30039. return 1;
  30040. case VertexBuffer.SHORT:
  30041. case VertexBuffer.UNSIGNED_SHORT:
  30042. return 2;
  30043. case VertexBuffer.INT:
  30044. case VertexBuffer.FLOAT:
  30045. return 4;
  30046. default:
  30047. throw new Error("Invalid type '" + type + "'");
  30048. }
  30049. };
  30050. /**
  30051. * Enumerates each value of the given parameters as numbers.
  30052. * @param data the data to enumerate
  30053. * @param byteOffset the byte offset of the data
  30054. * @param byteStride the byte stride of the data
  30055. * @param componentCount the number of components per element
  30056. * @param componentType the type of the component
  30057. * @param count the total number of components
  30058. * @param normalized whether the data is normalized
  30059. * @param callback the callback function called for each value
  30060. */
  30061. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30062. if (data instanceof Array) {
  30063. var offset = byteOffset / 4;
  30064. var stride = byteStride / 4;
  30065. for (var index = 0; index < count; index += componentCount) {
  30066. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30067. callback(data[offset + componentIndex], index + componentIndex);
  30068. }
  30069. offset += stride;
  30070. }
  30071. }
  30072. else {
  30073. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30074. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30075. for (var index = 0; index < count; index += componentCount) {
  30076. var componentByteOffset = byteOffset;
  30077. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30078. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30079. callback(value, index + componentIndex);
  30080. componentByteOffset += componentByteLength;
  30081. }
  30082. byteOffset += byteStride;
  30083. }
  30084. }
  30085. };
  30086. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30087. switch (type) {
  30088. case VertexBuffer.BYTE: {
  30089. var value = dataView.getInt8(byteOffset);
  30090. if (normalized) {
  30091. value = Math.max(value / 127, -1);
  30092. }
  30093. return value;
  30094. }
  30095. case VertexBuffer.UNSIGNED_BYTE: {
  30096. var value = dataView.getUint8(byteOffset);
  30097. if (normalized) {
  30098. value = value / 255;
  30099. }
  30100. return value;
  30101. }
  30102. case VertexBuffer.SHORT: {
  30103. var value = dataView.getInt16(byteOffset, true);
  30104. if (normalized) {
  30105. value = Math.max(value / 16383, -1);
  30106. }
  30107. return value;
  30108. }
  30109. case VertexBuffer.UNSIGNED_SHORT: {
  30110. var value = dataView.getUint16(byteOffset, true);
  30111. if (normalized) {
  30112. value = value / 65535;
  30113. }
  30114. return value;
  30115. }
  30116. case VertexBuffer.FLOAT: {
  30117. return dataView.getFloat32(byteOffset, true);
  30118. }
  30119. default: {
  30120. throw new Error("Invalid component type " + type);
  30121. }
  30122. }
  30123. };
  30124. /**
  30125. * The byte type.
  30126. */
  30127. VertexBuffer.BYTE = 5120;
  30128. /**
  30129. * The unsigned byte type.
  30130. */
  30131. VertexBuffer.UNSIGNED_BYTE = 5121;
  30132. /**
  30133. * The short type.
  30134. */
  30135. VertexBuffer.SHORT = 5122;
  30136. /**
  30137. * The unsigned short type.
  30138. */
  30139. VertexBuffer.UNSIGNED_SHORT = 5123;
  30140. /**
  30141. * The integer type.
  30142. */
  30143. VertexBuffer.INT = 5124;
  30144. /**
  30145. * The unsigned integer type.
  30146. */
  30147. VertexBuffer.UNSIGNED_INT = 5125;
  30148. /**
  30149. * The float type.
  30150. */
  30151. VertexBuffer.FLOAT = 5126;
  30152. // Enums
  30153. /**
  30154. * Positions
  30155. */
  30156. VertexBuffer.PositionKind = "position";
  30157. /**
  30158. * Normals
  30159. */
  30160. VertexBuffer.NormalKind = "normal";
  30161. /**
  30162. * Tangents
  30163. */
  30164. VertexBuffer.TangentKind = "tangent";
  30165. /**
  30166. * Texture coordinates
  30167. */
  30168. VertexBuffer.UVKind = "uv";
  30169. /**
  30170. * Texture coordinates 2
  30171. */
  30172. VertexBuffer.UV2Kind = "uv2";
  30173. /**
  30174. * Texture coordinates 3
  30175. */
  30176. VertexBuffer.UV3Kind = "uv3";
  30177. /**
  30178. * Texture coordinates 4
  30179. */
  30180. VertexBuffer.UV4Kind = "uv4";
  30181. /**
  30182. * Texture coordinates 5
  30183. */
  30184. VertexBuffer.UV5Kind = "uv5";
  30185. /**
  30186. * Texture coordinates 6
  30187. */
  30188. VertexBuffer.UV6Kind = "uv6";
  30189. /**
  30190. * Colors
  30191. */
  30192. VertexBuffer.ColorKind = "color";
  30193. /**
  30194. * Matrix indices (for bones)
  30195. */
  30196. VertexBuffer.MatricesIndicesKind = "matricesIndices";
  30197. /**
  30198. * Matrix weights (for bones)
  30199. */
  30200. VertexBuffer.MatricesWeightsKind = "matricesWeights";
  30201. /**
  30202. * Additional matrix indices (for bones)
  30203. */
  30204. VertexBuffer.MatricesIndicesExtraKind = "matricesIndicesExtra";
  30205. /**
  30206. * Additional matrix weights (for bones)
  30207. */
  30208. VertexBuffer.MatricesWeightsExtraKind = "matricesWeightsExtra";
  30209. return VertexBuffer;
  30210. }());
  30211. BABYLON.VertexBuffer = VertexBuffer;
  30212. })(BABYLON || (BABYLON = {}));
  30213. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30214. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  30215. var BABYLON;
  30216. (function (BABYLON) {
  30217. /**
  30218. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30219. */
  30220. var DummyInternalTextureTracker = /** @class */ (function () {
  30221. function DummyInternalTextureTracker() {
  30222. /**
  30223. * Gets or set the previous tracker in the list
  30224. */
  30225. this.previous = null;
  30226. /**
  30227. * Gets or set the next tracker in the list
  30228. */
  30229. this.next = null;
  30230. }
  30231. return DummyInternalTextureTracker;
  30232. }());
  30233. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30234. })(BABYLON || (BABYLON = {}));
  30235. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30236. var BABYLON;
  30237. (function (BABYLON) {
  30238. /**
  30239. * Class used to store data associated with WebGL texture data for the engine
  30240. * This class should not be used directly
  30241. */
  30242. var InternalTexture = /** @class */ (function () {
  30243. /**
  30244. * Creates a new InternalTexture
  30245. * @param engine defines the engine to use
  30246. * @param dataSource defines the type of data that will be used
  30247. */
  30248. function InternalTexture(engine, dataSource) {
  30249. /**
  30250. * Observable called when the texture is loaded
  30251. */
  30252. this.onLoadedObservable = new BABYLON.Observable();
  30253. /**
  30254. * Gets or set the previous tracker in the list
  30255. */
  30256. this.previous = null;
  30257. /**
  30258. * Gets or set the next tracker in the list
  30259. */
  30260. this.next = null;
  30261. // Private
  30262. /** @hidden */
  30263. this._initialSlot = -1;
  30264. /** @hidden */
  30265. this._designatedSlot = -1;
  30266. /** @hidden */
  30267. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30268. /** @hidden */
  30269. this._comparisonFunction = 0;
  30270. /** @hidden */
  30271. this._sphericalPolynomial = null;
  30272. /** @hidden */
  30273. this._lodGenerationScale = 0;
  30274. /** @hidden */
  30275. this._lodGenerationOffset = 0;
  30276. /** @hidden */
  30277. this._isRGBD = false;
  30278. /** @hidden */
  30279. this._references = 1;
  30280. this._engine = engine;
  30281. this._dataSource = dataSource;
  30282. this._webGLTexture = engine._createTexture();
  30283. }
  30284. /**
  30285. * Gets the Engine the texture belongs to.
  30286. * @returns The babylon engine
  30287. */
  30288. InternalTexture.prototype.getEngine = function () {
  30289. return this._engine;
  30290. };
  30291. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30292. /**
  30293. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30294. */
  30295. get: function () {
  30296. return this._dataSource;
  30297. },
  30298. enumerable: true,
  30299. configurable: true
  30300. });
  30301. /**
  30302. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30303. */
  30304. InternalTexture.prototype.incrementReferences = function () {
  30305. this._references++;
  30306. };
  30307. /**
  30308. * Change the size of the texture (not the size of the content)
  30309. * @param width defines the new width
  30310. * @param height defines the new height
  30311. * @param depth defines the new depth (1 by default)
  30312. */
  30313. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30314. if (depth === void 0) { depth = 1; }
  30315. this.width = width;
  30316. this.height = height;
  30317. this.depth = depth;
  30318. this.baseWidth = width;
  30319. this.baseHeight = height;
  30320. this.baseDepth = depth;
  30321. this._size = width * height * depth;
  30322. };
  30323. /** @hidden */
  30324. InternalTexture.prototype._rebuild = function () {
  30325. var _this = this;
  30326. var proxy;
  30327. this.isReady = false;
  30328. this._cachedCoordinatesMode = null;
  30329. this._cachedWrapU = null;
  30330. this._cachedWrapV = null;
  30331. this._cachedAnisotropicFilteringLevel = null;
  30332. switch (this._dataSource) {
  30333. case InternalTexture.DATASOURCE_TEMP:
  30334. return;
  30335. case InternalTexture.DATASOURCE_URL:
  30336. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30337. _this.isReady = true;
  30338. }, null, this._buffer, undefined, this.format);
  30339. proxy._swapAndDie(this);
  30340. return;
  30341. case InternalTexture.DATASOURCE_RAW:
  30342. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30343. proxy._swapAndDie(this);
  30344. this.isReady = true;
  30345. return;
  30346. case InternalTexture.DATASOURCE_RAW3D:
  30347. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30348. proxy._swapAndDie(this);
  30349. this.isReady = true;
  30350. return;
  30351. case InternalTexture.DATASOURCE_DYNAMIC:
  30352. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30353. proxy._swapAndDie(this);
  30354. // The engine will make sure to update content so no need to flag it as isReady = true
  30355. return;
  30356. case InternalTexture.DATASOURCE_RENDERTARGET:
  30357. var options = new BABYLON.RenderTargetCreationOptions();
  30358. options.generateDepthBuffer = this._generateDepthBuffer;
  30359. options.generateMipMaps = this.generateMipMaps;
  30360. options.generateStencilBuffer = this._generateStencilBuffer;
  30361. options.samplingMode = this.samplingMode;
  30362. options.type = this.type;
  30363. if (this.isCube) {
  30364. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30365. }
  30366. else {
  30367. var size = {
  30368. width: this.width,
  30369. height: this.height
  30370. };
  30371. proxy = this._engine.createRenderTargetTexture(size, options);
  30372. }
  30373. proxy._swapAndDie(this);
  30374. this.isReady = true;
  30375. return;
  30376. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30377. var depthTextureOptions = {
  30378. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30379. comparisonFunction: this._comparisonFunction,
  30380. generateStencil: this._generateStencilBuffer,
  30381. isCube: this.isCube
  30382. };
  30383. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30384. proxy._swapAndDie(this);
  30385. this.isReady = true;
  30386. return;
  30387. case InternalTexture.DATASOURCE_CUBE:
  30388. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30389. _this.isReady = true;
  30390. }, null, this.format, this._extension);
  30391. proxy._swapAndDie(this);
  30392. return;
  30393. case InternalTexture.DATASOURCE_CUBERAW:
  30394. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30395. proxy._swapAndDie(this);
  30396. this.isReady = true;
  30397. return;
  30398. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30399. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30400. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30401. _this.isReady = true;
  30402. });
  30403. proxy._swapAndDie(this);
  30404. return;
  30405. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30406. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30407. if (proxy) {
  30408. proxy._swapAndDie(_this);
  30409. }
  30410. _this.isReady = true;
  30411. }, null, this.format, this._extension);
  30412. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30413. return;
  30414. }
  30415. };
  30416. /** @hidden */
  30417. InternalTexture.prototype._swapAndDie = function (target) {
  30418. target._webGLTexture = this._webGLTexture;
  30419. if (this._framebuffer) {
  30420. target._framebuffer = this._framebuffer;
  30421. }
  30422. if (this._depthStencilBuffer) {
  30423. target._depthStencilBuffer = this._depthStencilBuffer;
  30424. }
  30425. if (this._lodTextureHigh) {
  30426. if (target._lodTextureHigh) {
  30427. target._lodTextureHigh.dispose();
  30428. }
  30429. target._lodTextureHigh = this._lodTextureHigh;
  30430. }
  30431. if (this._lodTextureMid) {
  30432. if (target._lodTextureMid) {
  30433. target._lodTextureMid.dispose();
  30434. }
  30435. target._lodTextureMid = this._lodTextureMid;
  30436. }
  30437. if (this._lodTextureLow) {
  30438. if (target._lodTextureLow) {
  30439. target._lodTextureLow.dispose();
  30440. }
  30441. target._lodTextureLow = this._lodTextureLow;
  30442. }
  30443. var cache = this._engine.getLoadedTexturesCache();
  30444. var index = cache.indexOf(this);
  30445. if (index !== -1) {
  30446. cache.splice(index, 1);
  30447. }
  30448. };
  30449. /**
  30450. * Dispose the current allocated resources
  30451. */
  30452. InternalTexture.prototype.dispose = function () {
  30453. if (!this._webGLTexture) {
  30454. return;
  30455. }
  30456. this._references--;
  30457. if (this._references === 0) {
  30458. this._engine._releaseTexture(this);
  30459. this._webGLTexture = null;
  30460. this.previous = null;
  30461. this.next = null;
  30462. }
  30463. };
  30464. /**
  30465. * The source of the texture data is unknown
  30466. */
  30467. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30468. /**
  30469. * Texture data comes from an URL
  30470. */
  30471. InternalTexture.DATASOURCE_URL = 1;
  30472. /**
  30473. * Texture data is only used for temporary storage
  30474. */
  30475. InternalTexture.DATASOURCE_TEMP = 2;
  30476. /**
  30477. * Texture data comes from raw data (ArrayBuffer)
  30478. */
  30479. InternalTexture.DATASOURCE_RAW = 3;
  30480. /**
  30481. * Texture content is dynamic (video or dynamic texture)
  30482. */
  30483. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30484. /**
  30485. * Texture content is generated by rendering to it
  30486. */
  30487. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30488. /**
  30489. * Texture content is part of a multi render target process
  30490. */
  30491. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30492. /**
  30493. * Texture data comes from a cube data file
  30494. */
  30495. InternalTexture.DATASOURCE_CUBE = 7;
  30496. /**
  30497. * Texture data comes from a raw cube data
  30498. */
  30499. InternalTexture.DATASOURCE_CUBERAW = 8;
  30500. /**
  30501. * Texture data come from a prefiltered cube data file
  30502. */
  30503. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30504. /**
  30505. * Texture content is raw 3D data
  30506. */
  30507. InternalTexture.DATASOURCE_RAW3D = 10;
  30508. /**
  30509. * Texture content is a depth texture
  30510. */
  30511. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30512. /**
  30513. * Texture data comes from a raw cube data encoded with RGBD
  30514. */
  30515. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30516. return InternalTexture;
  30517. }());
  30518. BABYLON.InternalTexture = InternalTexture;
  30519. })(BABYLON || (BABYLON = {}));
  30520. //# sourceMappingURL=babylon.internalTexture.js.map
  30521. var BABYLON;
  30522. (function (BABYLON) {
  30523. /**
  30524. * Base class of all the textures in babylon.
  30525. * It groups all the common properties the materials, post process, lights... might need
  30526. * in order to make a correct use of the texture.
  30527. */
  30528. var BaseTexture = /** @class */ (function () {
  30529. /**
  30530. * Instantiates a new BaseTexture.
  30531. * Base class of all the textures in babylon.
  30532. * It groups all the common properties the materials, post process, lights... might need
  30533. * in order to make a correct use of the texture.
  30534. * @param scene Define the scene the texture blongs to
  30535. */
  30536. function BaseTexture(scene) {
  30537. this._hasAlpha = false;
  30538. /**
  30539. * Defines if the alpha value should be determined via the rgb values.
  30540. * If true the luminance of the pixel might be used to find the corresponding alpha value.
  30541. */
  30542. this.getAlphaFromRGB = false;
  30543. /**
  30544. * Intensity or strength of the texture.
  30545. * It is commonly used by materials to fine tune the intensity of the texture
  30546. */
  30547. this.level = 1;
  30548. /**
  30549. * Define the UV chanel to use starting from 0 and defaulting to 0.
  30550. * This is part of the texture as textures usually maps to one uv set.
  30551. */
  30552. this.coordinatesIndex = 0;
  30553. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30554. /**
  30555. * | Value | Type | Description |
  30556. * | ----- | ------------------ | ----------- |
  30557. * | 0 | CLAMP_ADDRESSMODE | |
  30558. * | 1 | WRAP_ADDRESSMODE | |
  30559. * | 2 | MIRROR_ADDRESSMODE | |
  30560. */
  30561. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30562. /**
  30563. * | Value | Type | Description |
  30564. * | ----- | ------------------ | ----------- |
  30565. * | 0 | CLAMP_ADDRESSMODE | |
  30566. * | 1 | WRAP_ADDRESSMODE | |
  30567. * | 2 | MIRROR_ADDRESSMODE | |
  30568. */
  30569. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30570. /**
  30571. * | Value | Type | Description |
  30572. * | ----- | ------------------ | ----------- |
  30573. * | 0 | CLAMP_ADDRESSMODE | |
  30574. * | 1 | WRAP_ADDRESSMODE | |
  30575. * | 2 | MIRROR_ADDRESSMODE | |
  30576. */
  30577. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30578. /**
  30579. * With compliant hardware and browser (supporting anisotropic filtering)
  30580. * this defines the level of anisotropic filtering in the texture.
  30581. * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
  30582. */
  30583. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30584. /**
  30585. * Define if the texture is a cube texture or if false a 2d texture.
  30586. */
  30587. this.isCube = false;
  30588. /**
  30589. * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
  30590. */
  30591. this.is3D = false;
  30592. /**
  30593. * Define if the texture contains data in gamma space (most of the png/jpg aside bump).
  30594. * HDR texture are usually stored in linear space.
  30595. * This only impacts the PBR and Background materials
  30596. */
  30597. this.gammaSpace = true;
  30598. /**
  30599. * Is Z inverted in the texture (useful in a cube texture).
  30600. */
  30601. this.invertZ = false;
  30602. /**
  30603. * @hidden
  30604. */
  30605. this.lodLevelInAlpha = false;
  30606. /**
  30607. * Define if the texture is a render target.
  30608. */
  30609. this.isRenderTarget = false;
  30610. /**
  30611. * Define the list of animation attached to the texture.
  30612. */
  30613. this.animations = new Array();
  30614. /**
  30615. * An event triggered when the texture is disposed.
  30616. */
  30617. this.onDisposeObservable = new BABYLON.Observable();
  30618. /**
  30619. * Define the current state of the loading sequence when in delayed load mode.
  30620. */
  30621. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30622. this._cachedSize = BABYLON.Size.Zero();
  30623. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30624. if (this._scene) {
  30625. this._scene.textures.push(this);
  30626. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  30627. }
  30628. this._uid = null;
  30629. }
  30630. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30631. get: function () {
  30632. return this._hasAlpha;
  30633. },
  30634. /**
  30635. * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).
  30636. */
  30637. set: function (value) {
  30638. if (this._hasAlpha === value) {
  30639. return;
  30640. }
  30641. this._hasAlpha = value;
  30642. if (this._scene) {
  30643. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30644. }
  30645. },
  30646. enumerable: true,
  30647. configurable: true
  30648. });
  30649. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30650. get: function () {
  30651. return this._coordinatesMode;
  30652. },
  30653. /**
  30654. * How a texture is mapped.
  30655. *
  30656. * | Value | Type | Description |
  30657. * | ----- | ----------------------------------- | ----------- |
  30658. * | 0 | EXPLICIT_MODE | |
  30659. * | 1 | SPHERICAL_MODE | |
  30660. * | 2 | PLANAR_MODE | |
  30661. * | 3 | CUBIC_MODE | |
  30662. * | 4 | PROJECTION_MODE | |
  30663. * | 5 | SKYBOX_MODE | |
  30664. * | 6 | INVCUBIC_MODE | |
  30665. * | 7 | EQUIRECTANGULAR_MODE | |
  30666. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30667. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30668. */
  30669. set: function (value) {
  30670. if (this._coordinatesMode === value) {
  30671. return;
  30672. }
  30673. this._coordinatesMode = value;
  30674. if (this._scene) {
  30675. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30676. }
  30677. },
  30678. enumerable: true,
  30679. configurable: true
  30680. });
  30681. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30682. /**
  30683. * Gets whether or not the texture contains RGBD data.
  30684. */
  30685. get: function () {
  30686. return this._texture != null && this._texture._isRGBD;
  30687. },
  30688. enumerable: true,
  30689. configurable: true
  30690. });
  30691. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30692. /**
  30693. * With prefiltered texture, defined the offset used during the prefiltering steps.
  30694. */
  30695. get: function () {
  30696. if (this._texture)
  30697. return this._texture._lodGenerationOffset;
  30698. return 0.0;
  30699. },
  30700. set: function (value) {
  30701. if (this._texture)
  30702. this._texture._lodGenerationOffset = value;
  30703. },
  30704. enumerable: true,
  30705. configurable: true
  30706. });
  30707. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30708. /**
  30709. * With prefiltered texture, defined the scale used during the prefiltering steps.
  30710. */
  30711. get: function () {
  30712. if (this._texture)
  30713. return this._texture._lodGenerationScale;
  30714. return 0.0;
  30715. },
  30716. set: function (value) {
  30717. if (this._texture)
  30718. this._texture._lodGenerationScale = value;
  30719. },
  30720. enumerable: true,
  30721. configurable: true
  30722. });
  30723. Object.defineProperty(BaseTexture.prototype, "uid", {
  30724. /**
  30725. * Define the unique id of the texture in the scene.
  30726. */
  30727. get: function () {
  30728. if (!this._uid) {
  30729. this._uid = BABYLON.Tools.RandomId();
  30730. }
  30731. return this._uid;
  30732. },
  30733. enumerable: true,
  30734. configurable: true
  30735. });
  30736. /**
  30737. * Return a string representation of the texture.
  30738. * @returns the texture as a string
  30739. */
  30740. BaseTexture.prototype.toString = function () {
  30741. return this.name;
  30742. };
  30743. /**
  30744. * Get the class name of the texture.
  30745. * @returns "BaseTexture"
  30746. */
  30747. BaseTexture.prototype.getClassName = function () {
  30748. return "BaseTexture";
  30749. };
  30750. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30751. /**
  30752. * Callback triggered when the texture has been disposed.
  30753. * Kept for back compatibility, you can use the onDisposeObservable instead.
  30754. */
  30755. set: function (callback) {
  30756. if (this._onDisposeObserver) {
  30757. this.onDisposeObservable.remove(this._onDisposeObserver);
  30758. }
  30759. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30760. },
  30761. enumerable: true,
  30762. configurable: true
  30763. });
  30764. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30765. /**
  30766. * Define if the texture is preventinga material to render or not.
  30767. * If not and the texture is not ready, the engine will use a default black texture instead.
  30768. */
  30769. get: function () {
  30770. return true;
  30771. },
  30772. enumerable: true,
  30773. configurable: true
  30774. });
  30775. /**
  30776. * Get the scene the texture belongs to.
  30777. * @returns the scene or null if undefined
  30778. */
  30779. BaseTexture.prototype.getScene = function () {
  30780. return this._scene;
  30781. };
  30782. /**
  30783. * Get the texture transform matrix used to offset tile the texture for istance.
  30784. * @returns the transformation matrix
  30785. */
  30786. BaseTexture.prototype.getTextureMatrix = function () {
  30787. return BABYLON.Matrix.IdentityReadOnly;
  30788. };
  30789. /**
  30790. * Get the texture reflection matrix used to rotate/transform the reflection.
  30791. * @returns the reflection matrix
  30792. */
  30793. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30794. return BABYLON.Matrix.IdentityReadOnly;
  30795. };
  30796. /**
  30797. * Get the underlying lower level texture from Babylon.
  30798. * @returns the insternal texture
  30799. */
  30800. BaseTexture.prototype.getInternalTexture = function () {
  30801. return this._texture;
  30802. };
  30803. /**
  30804. * Get if the texture is ready to be consumed (either it is ready or it is not blocking)
  30805. * @returns true if ready or not blocking
  30806. */
  30807. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30808. return !this.isBlocking || this.isReady();
  30809. };
  30810. /**
  30811. * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
  30812. * @returns true if fully ready
  30813. */
  30814. BaseTexture.prototype.isReady = function () {
  30815. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30816. this.delayLoad();
  30817. return false;
  30818. }
  30819. if (this._texture) {
  30820. return this._texture.isReady;
  30821. }
  30822. return false;
  30823. };
  30824. /**
  30825. * Get the size of the texture.
  30826. * @returns the texture size.
  30827. */
  30828. BaseTexture.prototype.getSize = function () {
  30829. if (this._texture) {
  30830. if (this._texture.width) {
  30831. this._cachedSize.width = this._texture.width;
  30832. this._cachedSize.height = this._texture.height;
  30833. return this._cachedSize;
  30834. }
  30835. if (this._texture._size) {
  30836. this._cachedSize.width = this._texture._size;
  30837. this._cachedSize.height = this._texture._size;
  30838. return this._cachedSize;
  30839. }
  30840. }
  30841. return this._cachedSize;
  30842. };
  30843. /**
  30844. * Get the base size of the texture.
  30845. * It can be different from the size if the texture has been resized for POT for instance
  30846. * @returns the base size
  30847. */
  30848. BaseTexture.prototype.getBaseSize = function () {
  30849. if (!this.isReady() || !this._texture)
  30850. return BABYLON.Size.Zero();
  30851. if (this._texture._size) {
  30852. return new BABYLON.Size(this._texture._size, this._texture._size);
  30853. }
  30854. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30855. };
  30856. /**
  30857. * Scales the texture if is `canRescale()`
  30858. * @param ratio the resize factor we want to use to rescale
  30859. */
  30860. BaseTexture.prototype.scale = function (ratio) {
  30861. };
  30862. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30863. /**
  30864. * Get if the texture can rescale.
  30865. */
  30866. get: function () {
  30867. return false;
  30868. },
  30869. enumerable: true,
  30870. configurable: true
  30871. });
  30872. /** @hidden */
  30873. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30874. if (!this._scene) {
  30875. return null;
  30876. }
  30877. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30878. for (var index = 0; index < texturesCache.length; index++) {
  30879. var texturesCacheEntry = texturesCache[index];
  30880. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30881. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30882. texturesCacheEntry.incrementReferences();
  30883. return texturesCacheEntry;
  30884. }
  30885. }
  30886. }
  30887. return null;
  30888. };
  30889. /** @hidden */
  30890. BaseTexture.prototype._rebuild = function () {
  30891. };
  30892. /**
  30893. * Triggers the load sequence in delayed load mode.
  30894. */
  30895. BaseTexture.prototype.delayLoad = function () {
  30896. };
  30897. /**
  30898. * Clones the texture.
  30899. * @returns the cloned texture
  30900. */
  30901. BaseTexture.prototype.clone = function () {
  30902. return null;
  30903. };
  30904. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30905. /**
  30906. * Get the texture underlying type (INT, FLOAT...)
  30907. */
  30908. get: function () {
  30909. if (!this._texture) {
  30910. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30911. }
  30912. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30913. },
  30914. enumerable: true,
  30915. configurable: true
  30916. });
  30917. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30918. /**
  30919. * Get the texture underlying format (RGB, RGBA...)
  30920. */
  30921. get: function () {
  30922. if (!this._texture) {
  30923. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30924. }
  30925. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30926. },
  30927. enumerable: true,
  30928. configurable: true
  30929. });
  30930. /**
  30931. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30932. * This will returns an RGBA array buffer containing either in values (0-255) or
  30933. * float values (0-1) depending of the underlying buffer type.
  30934. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  30935. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  30936. * @param buffer defines a user defined buffer to fill with data (can be null)
  30937. * @returns The Array buffer containing the pixels data.
  30938. */
  30939. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  30940. if (faceIndex === void 0) { faceIndex = 0; }
  30941. if (level === void 0) { level = 0; }
  30942. if (buffer === void 0) { buffer = null; }
  30943. if (!this._texture) {
  30944. return null;
  30945. }
  30946. var size = this.getSize();
  30947. var width = size.width;
  30948. var height = size.height;
  30949. var scene = this.getScene();
  30950. if (!scene) {
  30951. return null;
  30952. }
  30953. var engine = scene.getEngine();
  30954. if (level != 0) {
  30955. width = width / Math.pow(2, level);
  30956. height = height / Math.pow(2, level);
  30957. width = Math.round(width);
  30958. height = Math.round(height);
  30959. }
  30960. if (this._texture.isCube) {
  30961. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  30962. }
  30963. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  30964. };
  30965. /**
  30966. * Release and destroy the underlying lower level texture aka internalTexture.
  30967. */
  30968. BaseTexture.prototype.releaseInternalTexture = function () {
  30969. if (this._texture) {
  30970. this._texture.dispose();
  30971. this._texture = null;
  30972. }
  30973. };
  30974. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30975. /**
  30976. * Get the polynomial representation of the texture data.
  30977. * This is mainly use as a fast way to recover IBL Diffuse irradiance data.
  30978. * @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance
  30979. */
  30980. get: function () {
  30981. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30982. return null;
  30983. }
  30984. if (!this._texture._sphericalPolynomial) {
  30985. this._texture._sphericalPolynomial =
  30986. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30987. }
  30988. return this._texture._sphericalPolynomial;
  30989. },
  30990. set: function (value) {
  30991. if (this._texture) {
  30992. this._texture._sphericalPolynomial = value;
  30993. }
  30994. },
  30995. enumerable: true,
  30996. configurable: true
  30997. });
  30998. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30999. /** @hidden */
  31000. get: function () {
  31001. if (this._texture) {
  31002. return this._texture._lodTextureHigh;
  31003. }
  31004. return null;
  31005. },
  31006. enumerable: true,
  31007. configurable: true
  31008. });
  31009. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  31010. /** @hidden */
  31011. get: function () {
  31012. if (this._texture) {
  31013. return this._texture._lodTextureMid;
  31014. }
  31015. return null;
  31016. },
  31017. enumerable: true,
  31018. configurable: true
  31019. });
  31020. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  31021. /** @hidden */
  31022. get: function () {
  31023. if (this._texture) {
  31024. return this._texture._lodTextureLow;
  31025. }
  31026. return null;
  31027. },
  31028. enumerable: true,
  31029. configurable: true
  31030. });
  31031. /**
  31032. * Dispose the texture and release its associated resources.
  31033. */
  31034. BaseTexture.prototype.dispose = function () {
  31035. if (!this._scene) {
  31036. return;
  31037. }
  31038. // Animations
  31039. this._scene.stopAnimation(this);
  31040. // Remove from scene
  31041. this._scene._removePendingData(this);
  31042. var index = this._scene.textures.indexOf(this);
  31043. if (index >= 0) {
  31044. this._scene.textures.splice(index, 1);
  31045. }
  31046. this._scene.onTextureRemovedObservable.notifyObservers(this);
  31047. if (this._texture === undefined) {
  31048. return;
  31049. }
  31050. // Release
  31051. this.releaseInternalTexture();
  31052. // Callback
  31053. this.onDisposeObservable.notifyObservers(this);
  31054. this.onDisposeObservable.clear();
  31055. };
  31056. /**
  31057. * Serialize the texture into a JSON representation that can be parsed later on.
  31058. * @returns the JSON representation of the texture
  31059. */
  31060. BaseTexture.prototype.serialize = function () {
  31061. if (!this.name) {
  31062. return null;
  31063. }
  31064. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31065. // Animations
  31066. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31067. return serializationObject;
  31068. };
  31069. /**
  31070. * Helper function to be called back once a list of texture contains only ready textures.
  31071. * @param textures Define the list of textures to wait for
  31072. * @param callback Define the callback triggered once the entire list will be ready
  31073. */
  31074. BaseTexture.WhenAllReady = function (textures, callback) {
  31075. var numRemaining = textures.length;
  31076. if (numRemaining === 0) {
  31077. callback();
  31078. return;
  31079. }
  31080. var _loop_1 = function () {
  31081. texture = textures[i];
  31082. if (texture.isReady()) {
  31083. if (--numRemaining === 0) {
  31084. callback();
  31085. }
  31086. }
  31087. else {
  31088. onLoadObservable = texture.onLoadObservable;
  31089. var onLoadCallback_1 = function () {
  31090. onLoadObservable.removeCallback(onLoadCallback_1);
  31091. if (--numRemaining === 0) {
  31092. callback();
  31093. }
  31094. };
  31095. onLoadObservable.add(onLoadCallback_1);
  31096. }
  31097. };
  31098. var texture, onLoadObservable;
  31099. for (var i = 0; i < textures.length; i++) {
  31100. _loop_1();
  31101. }
  31102. };
  31103. /**
  31104. * Default anisotropic filtering level for the application.
  31105. * It is set to 4 as a good tradeoff between perf and quality.
  31106. */
  31107. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  31108. __decorate([
  31109. BABYLON.serialize()
  31110. ], BaseTexture.prototype, "name", void 0);
  31111. __decorate([
  31112. BABYLON.serialize("hasAlpha")
  31113. ], BaseTexture.prototype, "_hasAlpha", void 0);
  31114. __decorate([
  31115. BABYLON.serialize()
  31116. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  31117. __decorate([
  31118. BABYLON.serialize()
  31119. ], BaseTexture.prototype, "level", void 0);
  31120. __decorate([
  31121. BABYLON.serialize()
  31122. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  31123. __decorate([
  31124. BABYLON.serialize("coordinatesMode")
  31125. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  31126. __decorate([
  31127. BABYLON.serialize()
  31128. ], BaseTexture.prototype, "wrapU", void 0);
  31129. __decorate([
  31130. BABYLON.serialize()
  31131. ], BaseTexture.prototype, "wrapV", void 0);
  31132. __decorate([
  31133. BABYLON.serialize()
  31134. ], BaseTexture.prototype, "wrapR", void 0);
  31135. __decorate([
  31136. BABYLON.serialize()
  31137. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  31138. __decorate([
  31139. BABYLON.serialize()
  31140. ], BaseTexture.prototype, "isCube", void 0);
  31141. __decorate([
  31142. BABYLON.serialize()
  31143. ], BaseTexture.prototype, "is3D", void 0);
  31144. __decorate([
  31145. BABYLON.serialize()
  31146. ], BaseTexture.prototype, "gammaSpace", void 0);
  31147. __decorate([
  31148. BABYLON.serialize()
  31149. ], BaseTexture.prototype, "invertZ", void 0);
  31150. __decorate([
  31151. BABYLON.serialize()
  31152. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  31153. __decorate([
  31154. BABYLON.serialize()
  31155. ], BaseTexture.prototype, "lodGenerationOffset", null);
  31156. __decorate([
  31157. BABYLON.serialize()
  31158. ], BaseTexture.prototype, "lodGenerationScale", null);
  31159. __decorate([
  31160. BABYLON.serialize()
  31161. ], BaseTexture.prototype, "isRenderTarget", void 0);
  31162. return BaseTexture;
  31163. }());
  31164. BABYLON.BaseTexture = BaseTexture;
  31165. })(BABYLON || (BABYLON = {}));
  31166. //# sourceMappingURL=babylon.baseTexture.js.map
  31167. var BABYLON;
  31168. (function (BABYLON) {
  31169. var Texture = /** @class */ (function (_super) {
  31170. __extends(Texture, _super);
  31171. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  31172. if (noMipmap === void 0) { noMipmap = false; }
  31173. if (invertY === void 0) { invertY = true; }
  31174. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31175. if (onLoad === void 0) { onLoad = null; }
  31176. if (onError === void 0) { onError = null; }
  31177. if (buffer === void 0) { buffer = null; }
  31178. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31179. var _this = _super.call(this, scene) || this;
  31180. _this.uOffset = 0;
  31181. _this.vOffset = 0;
  31182. _this.uScale = 1.0;
  31183. _this.vScale = 1.0;
  31184. _this.uAng = 0;
  31185. _this.vAng = 0;
  31186. _this.wAng = 0;
  31187. /**
  31188. * Defines the center of rotation (U)
  31189. */
  31190. _this.uRotationCenter = 0.5;
  31191. /**
  31192. * Defines the center of rotation (V)
  31193. */
  31194. _this.vRotationCenter = 0.5;
  31195. /**
  31196. * Defines the center of rotation (W)
  31197. */
  31198. _this.wRotationCenter = 0.5;
  31199. _this._isBlocking = true;
  31200. _this.name = url || "";
  31201. _this.url = url;
  31202. _this._noMipmap = noMipmap;
  31203. _this._invertY = invertY;
  31204. _this._samplingMode = samplingMode;
  31205. _this._buffer = buffer;
  31206. _this._deleteBuffer = deleteBuffer;
  31207. if (format) {
  31208. _this._format = format;
  31209. }
  31210. scene = _this.getScene();
  31211. if (!scene) {
  31212. return _this;
  31213. }
  31214. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  31215. var load = function () {
  31216. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  31217. _this.onLoadObservable.notifyObservers(_this);
  31218. }
  31219. if (onLoad) {
  31220. onLoad();
  31221. }
  31222. if (!_this.isBlocking && scene) {
  31223. scene.resetCachedMaterial();
  31224. }
  31225. };
  31226. if (!_this.url) {
  31227. _this._delayedOnLoad = load;
  31228. _this._delayedOnError = onError;
  31229. return _this;
  31230. }
  31231. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31232. if (!_this._texture) {
  31233. if (!scene.useDelayedTextureLoading) {
  31234. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31235. if (deleteBuffer) {
  31236. delete _this._buffer;
  31237. }
  31238. }
  31239. else {
  31240. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31241. _this._delayedOnLoad = load;
  31242. _this._delayedOnError = onError;
  31243. }
  31244. }
  31245. else {
  31246. if (_this._texture.isReady) {
  31247. BABYLON.Tools.SetImmediate(function () { return load(); });
  31248. }
  31249. else {
  31250. _this._texture.onLoadedObservable.add(load);
  31251. }
  31252. }
  31253. return _this;
  31254. }
  31255. Object.defineProperty(Texture.prototype, "noMipmap", {
  31256. get: function () {
  31257. return this._noMipmap;
  31258. },
  31259. enumerable: true,
  31260. configurable: true
  31261. });
  31262. Object.defineProperty(Texture.prototype, "isBlocking", {
  31263. get: function () {
  31264. return this._isBlocking;
  31265. },
  31266. set: function (value) {
  31267. this._isBlocking = value;
  31268. },
  31269. enumerable: true,
  31270. configurable: true
  31271. });
  31272. Object.defineProperty(Texture.prototype, "samplingMode", {
  31273. get: function () {
  31274. return this._samplingMode;
  31275. },
  31276. enumerable: true,
  31277. configurable: true
  31278. });
  31279. /**
  31280. * Update the url (and optional buffer) of this texture if url was null during construction.
  31281. * @param url the url of the texture
  31282. * @param buffer the buffer of the texture (defaults to null)
  31283. */
  31284. Texture.prototype.updateURL = function (url, buffer) {
  31285. if (buffer === void 0) { buffer = null; }
  31286. if (this.url) {
  31287. throw new Error("URL is already set");
  31288. }
  31289. this.url = url;
  31290. this._buffer = buffer;
  31291. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31292. this.delayLoad();
  31293. };
  31294. Texture.prototype.delayLoad = function () {
  31295. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31296. return;
  31297. }
  31298. var scene = this.getScene();
  31299. if (!scene) {
  31300. return;
  31301. }
  31302. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31303. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31304. if (!this._texture) {
  31305. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31306. if (this._deleteBuffer) {
  31307. delete this._buffer;
  31308. }
  31309. }
  31310. else {
  31311. if (this._delayedOnLoad) {
  31312. if (this._texture.isReady) {
  31313. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31314. }
  31315. else {
  31316. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31317. }
  31318. }
  31319. }
  31320. this._delayedOnLoad = null;
  31321. this._delayedOnError = null;
  31322. };
  31323. /**
  31324. * Default is Trilinear mode.
  31325. *
  31326. * | Value | Type | Description |
  31327. * | ----- | ------------------ | ----------- |
  31328. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  31329. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  31330. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  31331. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  31332. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  31333. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  31334. * | 7 | NEAREST_LINEAR | |
  31335. * | 8 | NEAREST_NEAREST | |
  31336. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  31337. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  31338. * | 11 | LINEAR_LINEAR | |
  31339. * | 12 | LINEAR_NEAREST | |
  31340. *
  31341. * > _mag_: magnification filter (close to the viewer)
  31342. * > _min_: minification filter (far from the viewer)
  31343. * > _mip_: filter used between mip map levels
  31344. *
  31345. */
  31346. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31347. if (!this._texture) {
  31348. return;
  31349. }
  31350. var scene = this.getScene();
  31351. if (!scene) {
  31352. return;
  31353. }
  31354. this._samplingMode = samplingMode;
  31355. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31356. };
  31357. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31358. x *= this.uScale;
  31359. y *= this.vScale;
  31360. x -= this.uRotationCenter * this.uScale;
  31361. y -= this.vRotationCenter * this.vScale;
  31362. z -= this.wRotationCenter;
  31363. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31364. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31365. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31366. t.z += this.wRotationCenter;
  31367. };
  31368. Texture.prototype.getTextureMatrix = function () {
  31369. var _this = this;
  31370. if (this.uOffset === this._cachedUOffset &&
  31371. this.vOffset === this._cachedVOffset &&
  31372. this.uScale === this._cachedUScale &&
  31373. this.vScale === this._cachedVScale &&
  31374. this.uAng === this._cachedUAng &&
  31375. this.vAng === this._cachedVAng &&
  31376. this.wAng === this._cachedWAng) {
  31377. return this._cachedTextureMatrix;
  31378. }
  31379. this._cachedUOffset = this.uOffset;
  31380. this._cachedVOffset = this.vOffset;
  31381. this._cachedUScale = this.uScale;
  31382. this._cachedVScale = this.vScale;
  31383. this._cachedUAng = this.uAng;
  31384. this._cachedVAng = this.vAng;
  31385. this._cachedWAng = this.wAng;
  31386. if (!this._cachedTextureMatrix) {
  31387. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31388. this._rowGenerationMatrix = new BABYLON.Matrix();
  31389. this._t0 = BABYLON.Vector3.Zero();
  31390. this._t1 = BABYLON.Vector3.Zero();
  31391. this._t2 = BABYLON.Vector3.Zero();
  31392. }
  31393. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31394. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31395. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31396. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31397. this._t1.subtractInPlace(this._t0);
  31398. this._t2.subtractInPlace(this._t0);
  31399. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31400. this._cachedTextureMatrix.m[0] = this._t1.x;
  31401. this._cachedTextureMatrix.m[1] = this._t1.y;
  31402. this._cachedTextureMatrix.m[2] = this._t1.z;
  31403. this._cachedTextureMatrix.m[4] = this._t2.x;
  31404. this._cachedTextureMatrix.m[5] = this._t2.y;
  31405. this._cachedTextureMatrix.m[6] = this._t2.z;
  31406. this._cachedTextureMatrix.m[8] = this._t0.x;
  31407. this._cachedTextureMatrix.m[9] = this._t0.y;
  31408. this._cachedTextureMatrix.m[10] = this._t0.z;
  31409. var scene = this.getScene();
  31410. if (!scene) {
  31411. return this._cachedTextureMatrix;
  31412. }
  31413. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31414. return mat.hasTexture(_this);
  31415. });
  31416. return this._cachedTextureMatrix;
  31417. };
  31418. Texture.prototype.getReflectionTextureMatrix = function () {
  31419. var _this = this;
  31420. var scene = this.getScene();
  31421. if (!scene) {
  31422. return this._cachedTextureMatrix;
  31423. }
  31424. if (this.uOffset === this._cachedUOffset &&
  31425. this.vOffset === this._cachedVOffset &&
  31426. this.uScale === this._cachedUScale &&
  31427. this.vScale === this._cachedVScale &&
  31428. this.coordinatesMode === this._cachedCoordinatesMode) {
  31429. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31430. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31431. return this._cachedTextureMatrix;
  31432. }
  31433. }
  31434. else {
  31435. return this._cachedTextureMatrix;
  31436. }
  31437. }
  31438. if (!this._cachedTextureMatrix) {
  31439. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31440. }
  31441. if (!this._projectionModeMatrix) {
  31442. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31443. }
  31444. this._cachedUOffset = this.uOffset;
  31445. this._cachedVOffset = this.vOffset;
  31446. this._cachedUScale = this.uScale;
  31447. this._cachedVScale = this.vScale;
  31448. this._cachedCoordinatesMode = this.coordinatesMode;
  31449. switch (this.coordinatesMode) {
  31450. case Texture.PLANAR_MODE:
  31451. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31452. this._cachedTextureMatrix[0] = this.uScale;
  31453. this._cachedTextureMatrix[5] = this.vScale;
  31454. this._cachedTextureMatrix[12] = this.uOffset;
  31455. this._cachedTextureMatrix[13] = this.vOffset;
  31456. break;
  31457. case Texture.PROJECTION_MODE:
  31458. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31459. this._projectionModeMatrix.m[0] = 0.5;
  31460. this._projectionModeMatrix.m[5] = -0.5;
  31461. this._projectionModeMatrix.m[10] = 0.0;
  31462. this._projectionModeMatrix.m[12] = 0.5;
  31463. this._projectionModeMatrix.m[13] = 0.5;
  31464. this._projectionModeMatrix.m[14] = 1.0;
  31465. this._projectionModeMatrix.m[15] = 1.0;
  31466. var projectionMatrix = scene.getProjectionMatrix();
  31467. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31468. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31469. break;
  31470. default:
  31471. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31472. break;
  31473. }
  31474. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31475. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31476. });
  31477. return this._cachedTextureMatrix;
  31478. };
  31479. Texture.prototype.clone = function () {
  31480. var _this = this;
  31481. return BABYLON.SerializationHelper.Clone(function () {
  31482. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31483. }, this);
  31484. };
  31485. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31486. get: function () {
  31487. if (!this._onLoadObservable) {
  31488. this._onLoadObservable = new BABYLON.Observable();
  31489. }
  31490. return this._onLoadObservable;
  31491. },
  31492. enumerable: true,
  31493. configurable: true
  31494. });
  31495. Texture.prototype.serialize = function () {
  31496. var serializationObject = _super.prototype.serialize.call(this);
  31497. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31498. serializationObject.base64String = this._buffer;
  31499. serializationObject.name = serializationObject.name.replace("data:", "");
  31500. }
  31501. serializationObject.invertY = this._invertY;
  31502. serializationObject.samplingMode = this.samplingMode;
  31503. return serializationObject;
  31504. };
  31505. Texture.prototype.getClassName = function () {
  31506. return "Texture";
  31507. };
  31508. Texture.prototype.dispose = function () {
  31509. _super.prototype.dispose.call(this);
  31510. if (this._onLoadObservable) {
  31511. this._onLoadObservable.clear();
  31512. this._onLoadObservable = null;
  31513. }
  31514. this._delayedOnLoad = null;
  31515. this._delayedOnError = null;
  31516. };
  31517. // Statics
  31518. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31519. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31520. if (onLoad === void 0) { onLoad = null; }
  31521. if (onError === void 0) { onError = null; }
  31522. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31523. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31524. };
  31525. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31526. if (parsedTexture.customType) {
  31527. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31528. // Update Sampling Mode
  31529. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31530. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31531. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31532. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31533. }
  31534. }
  31535. return parsedCustomTexture;
  31536. }
  31537. if (parsedTexture.isCube) {
  31538. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31539. }
  31540. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31541. return null;
  31542. }
  31543. var texture = BABYLON.SerializationHelper.Parse(function () {
  31544. var generateMipMaps = true;
  31545. if (parsedTexture.noMipmap) {
  31546. generateMipMaps = false;
  31547. }
  31548. if (parsedTexture.mirrorPlane) {
  31549. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31550. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31551. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31552. return mirrorTexture;
  31553. }
  31554. else if (parsedTexture.isRenderTarget) {
  31555. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31556. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31557. return renderTargetTexture;
  31558. }
  31559. else {
  31560. var texture;
  31561. if (parsedTexture.base64String) {
  31562. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31563. }
  31564. else {
  31565. var url = rootUrl + parsedTexture.name;
  31566. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31567. url = parsedTexture.url;
  31568. }
  31569. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31570. }
  31571. return texture;
  31572. }
  31573. }, parsedTexture, scene);
  31574. // Update Sampling Mode
  31575. if (parsedTexture.samplingMode) {
  31576. var sampling = parsedTexture.samplingMode;
  31577. if (texture._samplingMode !== sampling) {
  31578. texture.updateSamplingMode(sampling);
  31579. }
  31580. }
  31581. // Animations
  31582. if (parsedTexture.animations) {
  31583. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31584. var parsedAnimation = parsedTexture.animations[animationIndex];
  31585. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31586. }
  31587. }
  31588. return texture;
  31589. };
  31590. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31591. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31592. if (noMipmap === void 0) { noMipmap = false; }
  31593. if (invertY === void 0) { invertY = true; }
  31594. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31595. if (onLoad === void 0) { onLoad = null; }
  31596. if (onError === void 0) { onError = null; }
  31597. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31598. if (name.substr(0, 5) !== "data:") {
  31599. name = "data:" + name;
  31600. }
  31601. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31602. };
  31603. // Constants
  31604. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  31605. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  31606. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  31607. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  31608. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  31609. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  31610. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  31611. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  31612. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  31613. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  31614. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  31615. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  31616. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  31617. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  31618. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  31619. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  31620. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  31621. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  31622. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  31623. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  31624. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  31625. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  31626. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  31627. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  31628. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  31629. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  31630. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  31631. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  31632. /**
  31633. * 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
  31634. */
  31635. Texture.UseSerializedUrlIfAny = false;
  31636. __decorate([
  31637. BABYLON.serialize()
  31638. ], Texture.prototype, "url", void 0);
  31639. __decorate([
  31640. BABYLON.serialize()
  31641. ], Texture.prototype, "uOffset", void 0);
  31642. __decorate([
  31643. BABYLON.serialize()
  31644. ], Texture.prototype, "vOffset", void 0);
  31645. __decorate([
  31646. BABYLON.serialize()
  31647. ], Texture.prototype, "uScale", void 0);
  31648. __decorate([
  31649. BABYLON.serialize()
  31650. ], Texture.prototype, "vScale", void 0);
  31651. __decorate([
  31652. BABYLON.serialize()
  31653. ], Texture.prototype, "uAng", void 0);
  31654. __decorate([
  31655. BABYLON.serialize()
  31656. ], Texture.prototype, "vAng", void 0);
  31657. __decorate([
  31658. BABYLON.serialize()
  31659. ], Texture.prototype, "wAng", void 0);
  31660. __decorate([
  31661. BABYLON.serialize()
  31662. ], Texture.prototype, "uRotationCenter", void 0);
  31663. __decorate([
  31664. BABYLON.serialize()
  31665. ], Texture.prototype, "vRotationCenter", void 0);
  31666. __decorate([
  31667. BABYLON.serialize()
  31668. ], Texture.prototype, "wRotationCenter", void 0);
  31669. __decorate([
  31670. BABYLON.serialize()
  31671. ], Texture.prototype, "isBlocking", null);
  31672. return Texture;
  31673. }(BABYLON.BaseTexture));
  31674. BABYLON.Texture = Texture;
  31675. })(BABYLON || (BABYLON = {}));
  31676. //# sourceMappingURL=babylon.texture.js.map
  31677. var BABYLON;
  31678. (function (BABYLON) {
  31679. /**
  31680. * @hidden
  31681. **/
  31682. var _CreationDataStorage = /** @class */ (function () {
  31683. function _CreationDataStorage() {
  31684. }
  31685. return _CreationDataStorage;
  31686. }());
  31687. BABYLON._CreationDataStorage = _CreationDataStorage;
  31688. /**
  31689. * @hidden
  31690. **/
  31691. var _InstanceDataStorage = /** @class */ (function () {
  31692. function _InstanceDataStorage() {
  31693. this.visibleInstances = {};
  31694. this.renderIdForInstances = new Array();
  31695. this.batchCache = new _InstancesBatch();
  31696. this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31697. }
  31698. return _InstanceDataStorage;
  31699. }());
  31700. /**
  31701. * @hidden
  31702. **/
  31703. var _InstancesBatch = /** @class */ (function () {
  31704. function _InstancesBatch() {
  31705. this.mustReturn = false;
  31706. this.visibleInstances = new Array();
  31707. this.renderSelf = new Array();
  31708. }
  31709. return _InstancesBatch;
  31710. }());
  31711. BABYLON._InstancesBatch = _InstancesBatch;
  31712. /**
  31713. * Class used to represent renderable models
  31714. */
  31715. var Mesh = /** @class */ (function (_super) {
  31716. __extends(Mesh, _super);
  31717. /**
  31718. * @constructor
  31719. * @param name The value used by scene.getMeshByName() to do a lookup.
  31720. * @param scene The scene to add this mesh to.
  31721. * @param parent The parent of this mesh, if it has one
  31722. * @param source An optional Mesh from which geometry is shared, cloned.
  31723. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31724. * When false, achieved by calling a clone(), also passing False.
  31725. * This will make creation of children, recursive.
  31726. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31727. */
  31728. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31729. if (scene === void 0) { scene = null; }
  31730. if (parent === void 0) { parent = null; }
  31731. if (source === void 0) { source = null; }
  31732. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31733. var _this = _super.call(this, name, scene) || this;
  31734. // Members
  31735. /**
  31736. * Gets the delay loading state of the mesh (when delay loading is turned on)
  31737. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  31738. */
  31739. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31740. /**
  31741. * Gets the list of instances created from this mesh
  31742. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  31743. */
  31744. _this.instances = new Array();
  31745. _this._LODLevels = new Array();
  31746. /** @hidden */
  31747. _this._instanceDataStorage = new _InstanceDataStorage();
  31748. // Use by builder only to know what orientation were the mesh build in.
  31749. /** @hidden */
  31750. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  31751. /**
  31752. * Use this property to change the original side orientation defined at construction time
  31753. */
  31754. _this.overrideMaterialSideOrientation = null;
  31755. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31756. // Will be used to save a source mesh reference, If any
  31757. _this._source = null;
  31758. scene = _this.getScene();
  31759. if (source) {
  31760. // Geometry
  31761. if (source._geometry) {
  31762. source._geometry.applyToMesh(_this);
  31763. }
  31764. // Deep copy
  31765. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31766. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  31767. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  31768. ], ["_poseMatrix"]);
  31769. // Source mesh
  31770. _this._source = source;
  31771. // Construction Params
  31772. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  31773. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  31774. _this._creationDataStorage = source._creationDataStorage;
  31775. // Animation ranges
  31776. if (_this._source._ranges) {
  31777. var ranges = _this._source._ranges;
  31778. for (var name in ranges) {
  31779. if (!ranges.hasOwnProperty(name)) {
  31780. continue;
  31781. }
  31782. if (!ranges[name]) {
  31783. continue;
  31784. }
  31785. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  31786. }
  31787. }
  31788. // Metadata
  31789. if (source.metadata && source.metadata.clone) {
  31790. _this.metadata = source.metadata.clone();
  31791. }
  31792. else {
  31793. _this.metadata = source.metadata;
  31794. }
  31795. // Tags
  31796. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31797. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31798. }
  31799. // Parent
  31800. _this.parent = source.parent;
  31801. // Pivot
  31802. _this.setPivotMatrix(source.getPivotMatrix());
  31803. _this.id = name + "." + source.id;
  31804. // Material
  31805. _this.material = source.material;
  31806. var index;
  31807. if (!doNotCloneChildren) {
  31808. // Children
  31809. var directDescendants = source.getDescendants(true);
  31810. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31811. var child = directDescendants[index_1];
  31812. if (child.clone) {
  31813. child.clone(name + "." + child.name, _this);
  31814. }
  31815. }
  31816. }
  31817. // Physics clone
  31818. var physicsEngine = _this.getScene().getPhysicsEngine();
  31819. if (clonePhysicsImpostor && physicsEngine) {
  31820. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31821. if (impostor) {
  31822. _this.physicsImpostor = impostor.clone(_this);
  31823. }
  31824. }
  31825. // Particles
  31826. for (index = 0; index < scene.particleSystems.length; index++) {
  31827. var system = scene.particleSystems[index];
  31828. if (system.emitter === source) {
  31829. system.clone(system.name, _this);
  31830. }
  31831. }
  31832. _this.refreshBoundingInfo();
  31833. _this.computeWorldMatrix(true);
  31834. }
  31835. // Parent
  31836. if (parent !== null) {
  31837. _this.parent = parent;
  31838. }
  31839. return _this;
  31840. }
  31841. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31842. /**
  31843. * An event triggered before rendering the mesh
  31844. */
  31845. get: function () {
  31846. if (!this._onBeforeRenderObservable) {
  31847. this._onBeforeRenderObservable = new BABYLON.Observable();
  31848. }
  31849. return this._onBeforeRenderObservable;
  31850. },
  31851. enumerable: true,
  31852. configurable: true
  31853. });
  31854. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31855. /**
  31856. * An event triggered after rendering the mesh
  31857. */
  31858. get: function () {
  31859. if (!this._onAfterRenderObservable) {
  31860. this._onAfterRenderObservable = new BABYLON.Observable();
  31861. }
  31862. return this._onAfterRenderObservable;
  31863. },
  31864. enumerable: true,
  31865. configurable: true
  31866. });
  31867. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31868. /**
  31869. * An event triggered before drawing the mesh
  31870. */
  31871. get: function () {
  31872. if (!this._onBeforeDrawObservable) {
  31873. this._onBeforeDrawObservable = new BABYLON.Observable();
  31874. }
  31875. return this._onBeforeDrawObservable;
  31876. },
  31877. enumerable: true,
  31878. configurable: true
  31879. });
  31880. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31881. /**
  31882. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  31883. */
  31884. set: function (callback) {
  31885. if (this._onBeforeDrawObserver) {
  31886. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31887. }
  31888. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31889. },
  31890. enumerable: true,
  31891. configurable: true
  31892. });
  31893. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31894. /**
  31895. * Gets or sets the morph target manager
  31896. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  31897. */
  31898. get: function () {
  31899. return this._morphTargetManager;
  31900. },
  31901. set: function (value) {
  31902. if (this._morphTargetManager === value) {
  31903. return;
  31904. }
  31905. this._morphTargetManager = value;
  31906. this._syncGeometryWithMorphTargetManager();
  31907. },
  31908. enumerable: true,
  31909. configurable: true
  31910. });
  31911. Object.defineProperty(Mesh.prototype, "source", {
  31912. /**
  31913. * Gets the source mesh (the one used to clone this one from)
  31914. */
  31915. get: function () {
  31916. return this._source;
  31917. },
  31918. enumerable: true,
  31919. configurable: true
  31920. });
  31921. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31922. /**
  31923. * Gets or sets a boolean indicating that this mesh does not use index buffer
  31924. */
  31925. get: function () {
  31926. return this._unIndexed;
  31927. },
  31928. set: function (value) {
  31929. if (this._unIndexed !== value) {
  31930. this._unIndexed = value;
  31931. this._markSubMeshesAsAttributesDirty();
  31932. }
  31933. },
  31934. enumerable: true,
  31935. configurable: true
  31936. });
  31937. // Methods
  31938. /**
  31939. * Gets the class name
  31940. * @returns the string "Mesh".
  31941. */
  31942. Mesh.prototype.getClassName = function () {
  31943. return "Mesh";
  31944. };
  31945. /**
  31946. * Returns a description of this mesh
  31947. * @param fullDetails define if full details about this mesh must be used
  31948. * @returns a descriptive string representing this mesh
  31949. */
  31950. Mesh.prototype.toString = function (fullDetails) {
  31951. var ret = _super.prototype.toString.call(this, fullDetails);
  31952. ret += ", n vertices: " + this.getTotalVertices();
  31953. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31954. if (this.animations) {
  31955. for (var i = 0; i < this.animations.length; i++) {
  31956. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31957. }
  31958. }
  31959. if (fullDetails) {
  31960. if (this._geometry) {
  31961. var ib = this.getIndices();
  31962. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31963. if (vb && ib) {
  31964. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31965. }
  31966. }
  31967. else {
  31968. ret += ", flat shading: UNKNOWN";
  31969. }
  31970. }
  31971. return ret;
  31972. };
  31973. /** @hidden */
  31974. Mesh.prototype._unBindEffect = function () {
  31975. _super.prototype._unBindEffect.call(this);
  31976. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31977. var instance = _a[_i];
  31978. instance._unBindEffect();
  31979. }
  31980. };
  31981. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31982. /**
  31983. * Gets a boolean indicating if this mesh has LOD
  31984. */
  31985. get: function () {
  31986. return this._LODLevels.length > 0;
  31987. },
  31988. enumerable: true,
  31989. configurable: true
  31990. });
  31991. /**
  31992. * Gets the list of MeshLODLevel associated with the current mesh
  31993. * @returns an array of MeshLODLevel
  31994. */
  31995. Mesh.prototype.getLODLevels = function () {
  31996. return this._LODLevels;
  31997. };
  31998. Mesh.prototype._sortLODLevels = function () {
  31999. this._LODLevels.sort(function (a, b) {
  32000. if (a.distance < b.distance) {
  32001. return 1;
  32002. }
  32003. if (a.distance > b.distance) {
  32004. return -1;
  32005. }
  32006. return 0;
  32007. });
  32008. };
  32009. /**
  32010. * Add a mesh as LOD level triggered at the given distance.
  32011. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32012. * @param distance The distance from the center of the object to show this level
  32013. * @param mesh The mesh to be added as LOD level (can be null)
  32014. * @return This mesh (for chaining)
  32015. */
  32016. Mesh.prototype.addLODLevel = function (distance, mesh) {
  32017. if (mesh && mesh._masterMesh) {
  32018. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  32019. return this;
  32020. }
  32021. var level = new BABYLON.MeshLODLevel(distance, mesh);
  32022. this._LODLevels.push(level);
  32023. if (mesh) {
  32024. mesh._masterMesh = this;
  32025. }
  32026. this._sortLODLevels();
  32027. return this;
  32028. };
  32029. /**
  32030. * Returns the LOD level mesh at the passed distance or null if not found.
  32031. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32032. * @param distance The distance from the center of the object to show this level
  32033. * @returns a Mesh or `null`
  32034. */
  32035. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  32036. for (var index = 0; index < this._LODLevels.length; index++) {
  32037. var level = this._LODLevels[index];
  32038. if (level.distance === distance) {
  32039. return level.mesh;
  32040. }
  32041. }
  32042. return null;
  32043. };
  32044. /**
  32045. * Remove a mesh from the LOD array
  32046. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32047. * @param mesh defines the mesh to be removed
  32048. * @return This mesh (for chaining)
  32049. */
  32050. Mesh.prototype.removeLODLevel = function (mesh) {
  32051. for (var index = 0; index < this._LODLevels.length; index++) {
  32052. if (this._LODLevels[index].mesh === mesh) {
  32053. this._LODLevels.splice(index, 1);
  32054. if (mesh) {
  32055. mesh._masterMesh = null;
  32056. }
  32057. }
  32058. }
  32059. this._sortLODLevels();
  32060. return this;
  32061. };
  32062. /**
  32063. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  32064. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32065. * @param camera defines the camera to use to compute distance
  32066. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  32067. * @return This mesh (for chaining)
  32068. */
  32069. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  32070. if (!this._LODLevels || this._LODLevels.length === 0) {
  32071. return this;
  32072. }
  32073. var bSphere;
  32074. if (boundingSphere) {
  32075. bSphere = boundingSphere;
  32076. }
  32077. else {
  32078. var boundingInfo = this.getBoundingInfo();
  32079. bSphere = boundingInfo.boundingSphere;
  32080. }
  32081. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  32082. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  32083. if (this.onLODLevelSelection) {
  32084. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  32085. }
  32086. return this;
  32087. }
  32088. for (var index = 0; index < this._LODLevels.length; index++) {
  32089. var level = this._LODLevels[index];
  32090. if (level.distance < distanceToCamera) {
  32091. if (level.mesh) {
  32092. level.mesh._preActivate();
  32093. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  32094. }
  32095. if (this.onLODLevelSelection) {
  32096. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  32097. }
  32098. return level.mesh;
  32099. }
  32100. }
  32101. if (this.onLODLevelSelection) {
  32102. this.onLODLevelSelection(distanceToCamera, this, this);
  32103. }
  32104. return this;
  32105. };
  32106. Object.defineProperty(Mesh.prototype, "geometry", {
  32107. /**
  32108. * Gets the mesh internal Geometry object
  32109. */
  32110. get: function () {
  32111. return this._geometry;
  32112. },
  32113. enumerable: true,
  32114. configurable: true
  32115. });
  32116. /**
  32117. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  32118. * @returns the total number of vertices
  32119. */
  32120. Mesh.prototype.getTotalVertices = function () {
  32121. if (this._geometry === null || this._geometry === undefined) {
  32122. return 0;
  32123. }
  32124. return this._geometry.getTotalVertices();
  32125. };
  32126. /**
  32127. * Returns the content of an associated vertex buffer
  32128. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32129. * - BABYLON.VertexBuffer.PositionKind
  32130. * - BABYLON.VertexBuffer.UVKind
  32131. * - BABYLON.VertexBuffer.UV2Kind
  32132. * - BABYLON.VertexBuffer.UV3Kind
  32133. * - BABYLON.VertexBuffer.UV4Kind
  32134. * - BABYLON.VertexBuffer.UV5Kind
  32135. * - BABYLON.VertexBuffer.UV6Kind
  32136. * - BABYLON.VertexBuffer.ColorKind
  32137. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32138. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32139. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32140. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32141. * @param copyWhenShared defines a boolean indicating that if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one
  32142. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  32143. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  32144. */
  32145. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32146. if (!this._geometry) {
  32147. return null;
  32148. }
  32149. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  32150. };
  32151. /**
  32152. * Returns the mesh VertexBuffer object from the requested `kind`
  32153. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32154. * - BABYLON.VertexBuffer.PositionKind
  32155. * - BABYLON.VertexBuffer.UVKind
  32156. * - BABYLON.VertexBuffer.UV2Kind
  32157. * - BABYLON.VertexBuffer.UV3Kind
  32158. * - BABYLON.VertexBuffer.UV4Kind
  32159. * - BABYLON.VertexBuffer.UV5Kind
  32160. * - BABYLON.VertexBuffer.UV6Kind
  32161. * - BABYLON.VertexBuffer.ColorKind
  32162. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32163. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32164. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32165. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32166. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  32167. */
  32168. Mesh.prototype.getVertexBuffer = function (kind) {
  32169. if (!this._geometry) {
  32170. return null;
  32171. }
  32172. return this._geometry.getVertexBuffer(kind);
  32173. };
  32174. /**
  32175. * Tests if a specific vertex buffer is associated with this mesh
  32176. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32177. * - BABYLON.VertexBuffer.PositionKind
  32178. * - BABYLON.VertexBuffer.UVKind
  32179. * - BABYLON.VertexBuffer.UV2Kind
  32180. * - BABYLON.VertexBuffer.UV3Kind
  32181. * - BABYLON.VertexBuffer.UV4Kind
  32182. * - BABYLON.VertexBuffer.UV5Kind
  32183. * - BABYLON.VertexBuffer.UV6Kind
  32184. * - BABYLON.VertexBuffer.ColorKind
  32185. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32186. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32187. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32188. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32189. * @returns a boolean
  32190. */
  32191. Mesh.prototype.isVerticesDataPresent = function (kind) {
  32192. if (!this._geometry) {
  32193. if (this._delayInfo) {
  32194. return this._delayInfo.indexOf(kind) !== -1;
  32195. }
  32196. return false;
  32197. }
  32198. return this._geometry.isVerticesDataPresent(kind);
  32199. };
  32200. /**
  32201. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  32202. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32203. * - BABYLON.VertexBuffer.PositionKind
  32204. * - BABYLON.VertexBuffer.UVKind
  32205. * - BABYLON.VertexBuffer.UV2Kind
  32206. * - BABYLON.VertexBuffer.UV3Kind
  32207. * - BABYLON.VertexBuffer.UV4Kind
  32208. * - BABYLON.VertexBuffer.UV5Kind
  32209. * - BABYLON.VertexBuffer.UV6Kind
  32210. * - BABYLON.VertexBuffer.ColorKind
  32211. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32212. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32213. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32214. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32215. * @returns a boolean
  32216. */
  32217. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  32218. if (!this._geometry) {
  32219. if (this._delayInfo) {
  32220. return this._delayInfo.indexOf(kind) !== -1;
  32221. }
  32222. return false;
  32223. }
  32224. return this._geometry.isVertexBufferUpdatable(kind);
  32225. };
  32226. /**
  32227. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  32228. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32229. * - BABYLON.VertexBuffer.PositionKind
  32230. * - BABYLON.VertexBuffer.UVKind
  32231. * - BABYLON.VertexBuffer.UV2Kind
  32232. * - BABYLON.VertexBuffer.UV3Kind
  32233. * - BABYLON.VertexBuffer.UV4Kind
  32234. * - BABYLON.VertexBuffer.UV5Kind
  32235. * - BABYLON.VertexBuffer.UV6Kind
  32236. * - BABYLON.VertexBuffer.ColorKind
  32237. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32238. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32239. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32240. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32241. * @returns an array of strings
  32242. */
  32243. Mesh.prototype.getVerticesDataKinds = function () {
  32244. if (!this._geometry) {
  32245. var result = new Array();
  32246. if (this._delayInfo) {
  32247. this._delayInfo.forEach(function (kind, index, array) {
  32248. result.push(kind);
  32249. });
  32250. }
  32251. return result;
  32252. }
  32253. return this._geometry.getVerticesDataKinds();
  32254. };
  32255. /**
  32256. * Returns a positive integer : the total number of indices in this mesh geometry.
  32257. * @returns the numner of indices or zero if the mesh has no geometry.
  32258. */
  32259. Mesh.prototype.getTotalIndices = function () {
  32260. if (!this._geometry) {
  32261. return 0;
  32262. }
  32263. return this._geometry.getTotalIndices();
  32264. };
  32265. /**
  32266. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32267. * @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.
  32268. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32269. * @returns the indices array or an empty array if the mesh has no geometry
  32270. */
  32271. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  32272. if (!this._geometry) {
  32273. return [];
  32274. }
  32275. return this._geometry.getIndices(copyWhenShared, forceCopy);
  32276. };
  32277. Object.defineProperty(Mesh.prototype, "isBlocked", {
  32278. get: function () {
  32279. return this._masterMesh !== null && this._masterMesh !== undefined;
  32280. },
  32281. enumerable: true,
  32282. configurable: true
  32283. });
  32284. /**
  32285. * Determine if the current mesh is ready to be rendered
  32286. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32287. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32288. * @returns true if all associated assets are ready (material, textures, shaders)
  32289. */
  32290. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32291. if (completeCheck === void 0) { completeCheck = false; }
  32292. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32293. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32294. return false;
  32295. }
  32296. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32297. return false;
  32298. }
  32299. if (!this.subMeshes || this.subMeshes.length === 0) {
  32300. return true;
  32301. }
  32302. if (!completeCheck) {
  32303. return true;
  32304. }
  32305. var engine = this.getEngine();
  32306. var scene = this.getScene();
  32307. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32308. this.computeWorldMatrix();
  32309. var mat = this.material || scene.defaultMaterial;
  32310. if (mat) {
  32311. if (mat.storeEffectOnSubMeshes) {
  32312. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32313. var subMesh = _a[_i];
  32314. var effectiveMaterial = subMesh.getMaterial();
  32315. if (effectiveMaterial) {
  32316. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32317. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32318. return false;
  32319. }
  32320. }
  32321. else {
  32322. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32323. return false;
  32324. }
  32325. }
  32326. }
  32327. }
  32328. }
  32329. else {
  32330. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32331. return false;
  32332. }
  32333. }
  32334. }
  32335. // Shadows
  32336. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32337. var light = _c[_b];
  32338. var generator = light.getShadowGenerator();
  32339. if (generator) {
  32340. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32341. var subMesh = _e[_d];
  32342. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32343. return false;
  32344. }
  32345. }
  32346. }
  32347. }
  32348. // LOD
  32349. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32350. var lod = _g[_f];
  32351. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32352. return false;
  32353. }
  32354. }
  32355. return true;
  32356. };
  32357. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32358. /**
  32359. * Gets a boolean indicating if the normals aren't to be recomputed on next mesh `positions` array update. This property is pertinent only for updatable parametric shapes.
  32360. */
  32361. get: function () {
  32362. return this._areNormalsFrozen;
  32363. },
  32364. enumerable: true,
  32365. configurable: true
  32366. });
  32367. /**
  32368. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It prevents the mesh normals from being recomputed on next `positions` array update.
  32369. * @returns the current mesh
  32370. */
  32371. Mesh.prototype.freezeNormals = function () {
  32372. this._areNormalsFrozen = true;
  32373. return this;
  32374. };
  32375. /**
  32376. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It reactivates the mesh normals computation if it was previously frozen
  32377. * @returns the current mesh
  32378. */
  32379. Mesh.prototype.unfreezeNormals = function () {
  32380. this._areNormalsFrozen = false;
  32381. return this;
  32382. };
  32383. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32384. /**
  32385. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32386. */
  32387. set: function (count) {
  32388. this._instanceDataStorage.overridenInstanceCount = count;
  32389. },
  32390. enumerable: true,
  32391. configurable: true
  32392. });
  32393. // Methods
  32394. /** @hidden */
  32395. Mesh.prototype._preActivate = function () {
  32396. var sceneRenderId = this.getScene().getRenderId();
  32397. if (this._preActivateId === sceneRenderId) {
  32398. return this;
  32399. }
  32400. this._preActivateId = sceneRenderId;
  32401. this._instanceDataStorage.visibleInstances = null;
  32402. return this;
  32403. };
  32404. /** @hidden */
  32405. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32406. if (this._instanceDataStorage.visibleInstances) {
  32407. this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
  32408. }
  32409. return this;
  32410. };
  32411. /** @hidden */
  32412. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32413. if (!this._instanceDataStorage.visibleInstances) {
  32414. this._instanceDataStorage.visibleInstances = {};
  32415. this._instanceDataStorage.visibleInstances.defaultRenderId = renderId;
  32416. this._instanceDataStorage.visibleInstances.selfDefaultRenderId = this._renderId;
  32417. }
  32418. if (!this._instanceDataStorage.visibleInstances[renderId]) {
  32419. this._instanceDataStorage.visibleInstances[renderId] = new Array();
  32420. }
  32421. this._instanceDataStorage.visibleInstances[renderId].push(instance);
  32422. return this;
  32423. };
  32424. /**
  32425. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32426. * This means the mesh underlying bounding box and sphere are recomputed.
  32427. * @returns the current mesh
  32428. */
  32429. Mesh.prototype.refreshBoundingInfo = function () {
  32430. return this._refreshBoundingInfo(false);
  32431. };
  32432. /** @hidden */
  32433. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32434. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32435. return this;
  32436. }
  32437. var data = this._getPositionData(applySkeleton);
  32438. if (data) {
  32439. var bias = this.geometry ? this.geometry.boundingBias : null;
  32440. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  32441. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32442. }
  32443. if (this.subMeshes) {
  32444. for (var index = 0; index < this.subMeshes.length; index++) {
  32445. this.subMeshes[index].refreshBoundingInfo();
  32446. }
  32447. }
  32448. this._updateBoundingInfo();
  32449. return this;
  32450. };
  32451. Mesh.prototype._getPositionData = function (applySkeleton) {
  32452. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32453. if (data && applySkeleton && this.skeleton) {
  32454. data = BABYLON.Tools.Slice(data);
  32455. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32456. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32457. if (matricesWeightsData && matricesIndicesData) {
  32458. var needExtras = this.numBoneInfluencers > 4;
  32459. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32460. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32461. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32462. var tempVector = BABYLON.Tmp.Vector3[0];
  32463. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32464. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32465. var matWeightIdx = 0;
  32466. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32467. finalMatrix.reset();
  32468. var inf;
  32469. var weight;
  32470. for (inf = 0; inf < 4; inf++) {
  32471. weight = matricesWeightsData[matWeightIdx + inf];
  32472. if (weight > 0) {
  32473. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32474. finalMatrix.addToSelf(tempMatrix);
  32475. }
  32476. }
  32477. if (needExtras) {
  32478. for (inf = 0; inf < 4; inf++) {
  32479. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32480. if (weight > 0) {
  32481. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32482. finalMatrix.addToSelf(tempMatrix);
  32483. }
  32484. }
  32485. }
  32486. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32487. tempVector.toArray(data, index);
  32488. }
  32489. }
  32490. }
  32491. return data;
  32492. };
  32493. /** @hidden */
  32494. Mesh.prototype._createGlobalSubMesh = function (force) {
  32495. var totalVertices = this.getTotalVertices();
  32496. if (!totalVertices || !this.getIndices()) {
  32497. return null;
  32498. }
  32499. // Check if we need to recreate the submeshes
  32500. if (this.subMeshes && this.subMeshes.length > 0) {
  32501. var ib = this.getIndices();
  32502. if (!ib) {
  32503. return null;
  32504. }
  32505. var totalIndices = ib.length;
  32506. var needToRecreate = false;
  32507. if (force) {
  32508. needToRecreate = true;
  32509. }
  32510. else {
  32511. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32512. var submesh = _a[_i];
  32513. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32514. needToRecreate = true;
  32515. break;
  32516. }
  32517. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32518. needToRecreate = true;
  32519. break;
  32520. }
  32521. }
  32522. }
  32523. if (!needToRecreate) {
  32524. return this.subMeshes[0];
  32525. }
  32526. }
  32527. this.releaseSubMeshes();
  32528. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32529. };
  32530. /**
  32531. * This function will subdivide the mesh into multiple submeshes
  32532. * @param count defines the expected number of submeshes
  32533. */
  32534. Mesh.prototype.subdivide = function (count) {
  32535. if (count < 1) {
  32536. return;
  32537. }
  32538. var totalIndices = this.getTotalIndices();
  32539. var subdivisionSize = (totalIndices / count) | 0;
  32540. var offset = 0;
  32541. // Ensure that subdivisionSize is a multiple of 3
  32542. while (subdivisionSize % 3 !== 0) {
  32543. subdivisionSize++;
  32544. }
  32545. this.releaseSubMeshes();
  32546. for (var index = 0; index < count; index++) {
  32547. if (offset >= totalIndices) {
  32548. break;
  32549. }
  32550. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32551. offset += subdivisionSize;
  32552. }
  32553. this.synchronizeInstances();
  32554. };
  32555. /**
  32556. * Copy a FloatArray into a specific associated vertex buffer
  32557. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  32558. * - BABYLON.VertexBuffer.PositionKind
  32559. * - BABYLON.VertexBuffer.UVKind
  32560. * - BABYLON.VertexBuffer.UV2Kind
  32561. * - BABYLON.VertexBuffer.UV3Kind
  32562. * - BABYLON.VertexBuffer.UV4Kind
  32563. * - BABYLON.VertexBuffer.UV5Kind
  32564. * - BABYLON.VertexBuffer.UV6Kind
  32565. * - BABYLON.VertexBuffer.ColorKind
  32566. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32567. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32568. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32569. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32570. * @param data defines the data source
  32571. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  32572. * @param stride defines the data stride size (can be null)
  32573. * @returns the current mesh
  32574. */
  32575. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32576. if (updatable === void 0) { updatable = false; }
  32577. if (!this._geometry) {
  32578. var vertexData = new BABYLON.VertexData();
  32579. vertexData.set(data, kind);
  32580. var scene = this.getScene();
  32581. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32582. }
  32583. else {
  32584. this._geometry.setVerticesData(kind, data, updatable, stride);
  32585. }
  32586. return this;
  32587. };
  32588. /**
  32589. * Flags an associated vertex buffer as updatable
  32590. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  32591. * - BABYLON.VertexBuffer.PositionKind
  32592. * - BABYLON.VertexBuffer.UVKind
  32593. * - BABYLON.VertexBuffer.UV2Kind
  32594. * - BABYLON.VertexBuffer.UV3Kind
  32595. * - BABYLON.VertexBuffer.UV4Kind
  32596. * - BABYLON.VertexBuffer.UV5Kind
  32597. * - BABYLON.VertexBuffer.UV6Kind
  32598. * - BABYLON.VertexBuffer.ColorKind
  32599. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32600. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32601. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32602. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32603. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  32604. */
  32605. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32606. if (updatable === void 0) { updatable = true; }
  32607. var vb = this.getVertexBuffer(kind);
  32608. if (!vb || vb.isUpdatable() === updatable) {
  32609. return;
  32610. }
  32611. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32612. };
  32613. /**
  32614. * Sets the mesh global Vertex Buffer
  32615. * @param buffer defines the buffer to use
  32616. * @returns the current mesh
  32617. */
  32618. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32619. if (!this._geometry) {
  32620. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32621. }
  32622. this._geometry.setVerticesBuffer(buffer);
  32623. return this;
  32624. };
  32625. /**
  32626. * Update a specific associated vertex buffer
  32627. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  32628. * - BABYLON.VertexBuffer.PositionKind
  32629. * - BABYLON.VertexBuffer.UVKind
  32630. * - BABYLON.VertexBuffer.UV2Kind
  32631. * - BABYLON.VertexBuffer.UV3Kind
  32632. * - BABYLON.VertexBuffer.UV4Kind
  32633. * - BABYLON.VertexBuffer.UV5Kind
  32634. * - BABYLON.VertexBuffer.UV6Kind
  32635. * - BABYLON.VertexBuffer.ColorKind
  32636. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32637. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32638. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32639. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32640. * @param data defines the data source
  32641. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  32642. * @param makeItUnique defines if the geometry associated with the mesh must be cloned to make the change only for this mesh (and not all meshes associated with the same geometry)
  32643. * @returns the current mesh
  32644. */
  32645. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32646. if (!this._geometry) {
  32647. return this;
  32648. }
  32649. if (!makeItUnique) {
  32650. this._geometry.updateVerticesData(kind, data, updateExtends);
  32651. }
  32652. else {
  32653. this.makeGeometryUnique();
  32654. this.updateVerticesData(kind, data, updateExtends, false);
  32655. }
  32656. return this;
  32657. };
  32658. /**
  32659. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32660. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32661. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  32662. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  32663. * @returns the current mesh
  32664. */
  32665. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32666. if (computeNormals === void 0) { computeNormals = true; }
  32667. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32668. if (!positions) {
  32669. return this;
  32670. }
  32671. positionFunction(positions);
  32672. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32673. if (computeNormals) {
  32674. var indices = this.getIndices();
  32675. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32676. if (!normals) {
  32677. return this;
  32678. }
  32679. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32680. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32681. }
  32682. return this;
  32683. };
  32684. /**
  32685. * Creates a un-shared specific occurence of the geometry for the mesh.
  32686. * @returns the current mesh
  32687. */
  32688. Mesh.prototype.makeGeometryUnique = function () {
  32689. if (!this._geometry) {
  32690. return this;
  32691. }
  32692. var oldGeometry = this._geometry;
  32693. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32694. oldGeometry.releaseForMesh(this, true);
  32695. geometry.applyToMesh(this);
  32696. return this;
  32697. };
  32698. /**
  32699. * Set the index buffer of this mesh
  32700. * @param indices defines the source data
  32701. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  32702. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  32703. * @returns the current mesh
  32704. */
  32705. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32706. if (totalVertices === void 0) { totalVertices = null; }
  32707. if (updatable === void 0) { updatable = false; }
  32708. if (!this._geometry) {
  32709. var vertexData = new BABYLON.VertexData();
  32710. vertexData.indices = indices;
  32711. var scene = this.getScene();
  32712. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32713. }
  32714. else {
  32715. this._geometry.setIndices(indices, totalVertices, updatable);
  32716. }
  32717. return this;
  32718. };
  32719. /**
  32720. * Update the current index buffer
  32721. * @param indices defines the source data
  32722. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  32723. * @returns the current mesh
  32724. */
  32725. Mesh.prototype.updateIndices = function (indices, offset) {
  32726. if (!this._geometry) {
  32727. return this;
  32728. }
  32729. this._geometry.updateIndices(indices, offset);
  32730. return this;
  32731. };
  32732. /**
  32733. * Invert the geometry to move from a right handed system to a left handed one.
  32734. * @returns the current mesh
  32735. */
  32736. Mesh.prototype.toLeftHanded = function () {
  32737. if (!this._geometry) {
  32738. return this;
  32739. }
  32740. this._geometry.toLeftHanded();
  32741. return this;
  32742. };
  32743. /** @hidden */
  32744. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32745. if (!this._geometry) {
  32746. return this;
  32747. }
  32748. var engine = this.getScene().getEngine();
  32749. // Wireframe
  32750. var indexToBind;
  32751. if (this._unIndexed) {
  32752. indexToBind = null;
  32753. }
  32754. else {
  32755. switch (fillMode) {
  32756. case BABYLON.Material.PointFillMode:
  32757. indexToBind = null;
  32758. break;
  32759. case BABYLON.Material.WireFrameFillMode:
  32760. indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
  32761. break;
  32762. default:
  32763. case BABYLON.Material.TriangleFillMode:
  32764. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32765. break;
  32766. }
  32767. }
  32768. // VBOs
  32769. this._geometry._bind(effect, indexToBind);
  32770. return this;
  32771. };
  32772. /** @hidden */
  32773. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32774. if (alternate === void 0) { alternate = false; }
  32775. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32776. return this;
  32777. }
  32778. if (this._onBeforeDrawObservable) {
  32779. this._onBeforeDrawObservable.notifyObservers(this);
  32780. }
  32781. var scene = this.getScene();
  32782. var engine = scene.getEngine();
  32783. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32784. // or triangles as points
  32785. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32786. }
  32787. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32788. // Triangles as wireframe
  32789. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  32790. }
  32791. else {
  32792. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32793. }
  32794. if (scene._isAlternateRenderingEnabled && !alternate) {
  32795. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32796. if (!effect || !scene.activeCamera) {
  32797. return this;
  32798. }
  32799. scene._switchToAlternateCameraConfiguration(true);
  32800. this._effectiveMaterial.bindView(effect);
  32801. this._effectiveMaterial.bindViewProjection(effect);
  32802. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32803. this._draw(subMesh, fillMode, instancesCount, true);
  32804. engine.setViewport(scene.activeCamera.viewport);
  32805. scene._switchToAlternateCameraConfiguration(false);
  32806. this._effectiveMaterial.bindView(effect);
  32807. this._effectiveMaterial.bindViewProjection(effect);
  32808. }
  32809. return this;
  32810. };
  32811. /**
  32812. * Registers for this mesh a javascript function called just before the rendering process
  32813. * @param func defines the function to call before rendering this mesh
  32814. * @returns the current mesh
  32815. */
  32816. Mesh.prototype.registerBeforeRender = function (func) {
  32817. this.onBeforeRenderObservable.add(func);
  32818. return this;
  32819. };
  32820. /**
  32821. * Disposes a previously registered javascript function called before the rendering
  32822. * @param func defines the function to remove
  32823. * @returns the current mesh
  32824. */
  32825. Mesh.prototype.unregisterBeforeRender = function (func) {
  32826. this.onBeforeRenderObservable.removeCallback(func);
  32827. return this;
  32828. };
  32829. /**
  32830. * Registers for this mesh a javascript function called just after the rendering is complete
  32831. * @param func defines the function to call after rendering this mesh
  32832. * @returns the current mesh
  32833. */
  32834. Mesh.prototype.registerAfterRender = function (func) {
  32835. this.onAfterRenderObservable.add(func);
  32836. return this;
  32837. };
  32838. /**
  32839. * Disposes a previously registered javascript function called after the rendering.
  32840. * @param func defines the function to remove
  32841. * @returns the current mesh
  32842. */
  32843. Mesh.prototype.unregisterAfterRender = function (func) {
  32844. this.onAfterRenderObservable.removeCallback(func);
  32845. return this;
  32846. };
  32847. /** @hidden */
  32848. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32849. var scene = this.getScene();
  32850. var batchCache = this._instanceDataStorage.batchCache;
  32851. batchCache.mustReturn = false;
  32852. batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32853. batchCache.visibleInstances[subMeshId] = null;
  32854. if (this._instanceDataStorage.visibleInstances) {
  32855. var visibleInstances = this._instanceDataStorage.visibleInstances;
  32856. var currentRenderId = scene.getRenderId();
  32857. var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
  32858. batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
  32859. var selfRenderId = this._renderId;
  32860. if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32861. batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
  32862. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32863. selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
  32864. }
  32865. var visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
  32866. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32867. if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
  32868. batchCache.mustReturn = true;
  32869. return batchCache;
  32870. }
  32871. if (currentRenderId !== selfRenderId) {
  32872. batchCache.renderSelf[subMeshId] = false;
  32873. }
  32874. }
  32875. this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
  32876. }
  32877. return batchCache;
  32878. };
  32879. /** @hidden */
  32880. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32881. var visibleInstances = batch.visibleInstances[subMesh._id];
  32882. if (!visibleInstances) {
  32883. return this;
  32884. }
  32885. var matricesCount = visibleInstances.length + 1;
  32886. var bufferSize = matricesCount * 16 * 4;
  32887. var instanceStorage = this._instanceDataStorage;
  32888. var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
  32889. var instancesBuffer = instanceStorage.instancesBuffer;
  32890. while (instanceStorage.instancesBufferSize < bufferSize) {
  32891. instanceStorage.instancesBufferSize *= 2;
  32892. }
  32893. if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  32894. instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
  32895. }
  32896. var offset = 0;
  32897. var instancesCount = 0;
  32898. var world = this.getWorldMatrix();
  32899. if (batch.renderSelf[subMesh._id]) {
  32900. world.copyToArray(instanceStorage.instancesData, offset);
  32901. offset += 16;
  32902. instancesCount++;
  32903. }
  32904. if (visibleInstances) {
  32905. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32906. var instance = visibleInstances[instanceIndex];
  32907. instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
  32908. offset += 16;
  32909. instancesCount++;
  32910. }
  32911. }
  32912. if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  32913. if (instancesBuffer) {
  32914. instancesBuffer.dispose();
  32915. }
  32916. instancesBuffer = new BABYLON.Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
  32917. instanceStorage.instancesBuffer = instancesBuffer;
  32918. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32919. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32920. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32921. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32922. }
  32923. else {
  32924. instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
  32925. }
  32926. this._bind(subMesh, effect, fillMode);
  32927. this._draw(subMesh, fillMode, instancesCount);
  32928. engine.unbindInstanceAttributes();
  32929. return this;
  32930. };
  32931. /** @hidden */
  32932. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32933. var scene = this.getScene();
  32934. var engine = scene.getEngine();
  32935. if (hardwareInstancedRendering) {
  32936. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32937. }
  32938. else {
  32939. if (batch.renderSelf[subMesh._id]) {
  32940. // Draw
  32941. if (onBeforeDraw) {
  32942. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32943. }
  32944. this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
  32945. }
  32946. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32947. if (visibleInstancesForSubMesh) {
  32948. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32949. var instance = visibleInstancesForSubMesh[instanceIndex];
  32950. // World
  32951. var world = instance.getWorldMatrix();
  32952. if (onBeforeDraw) {
  32953. onBeforeDraw(true, world, effectiveMaterial);
  32954. }
  32955. // Draw
  32956. this._draw(subMesh, fillMode);
  32957. }
  32958. }
  32959. }
  32960. return this;
  32961. };
  32962. /**
  32963. * 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
  32964. * @param subMesh defines the subMesh to render
  32965. * @param enableAlphaMode defines if alpha mode can be changed
  32966. * @returns the current mesh
  32967. */
  32968. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32969. if (this._checkOcclusionQuery()) {
  32970. return this;
  32971. }
  32972. var scene = this.getScene();
  32973. // Managing instances
  32974. var batch = this._getInstancesRenderList(subMesh._id);
  32975. if (batch.mustReturn) {
  32976. return this;
  32977. }
  32978. // Checking geometry state
  32979. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32980. return this;
  32981. }
  32982. if (this._onBeforeRenderObservable) {
  32983. this._onBeforeRenderObservable.notifyObservers(this);
  32984. }
  32985. var engine = scene.getEngine();
  32986. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32987. // Material
  32988. var material = subMesh.getMaterial();
  32989. if (!material) {
  32990. return this;
  32991. }
  32992. this._effectiveMaterial = material;
  32993. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32994. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32995. return this;
  32996. }
  32997. }
  32998. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32999. return this;
  33000. }
  33001. // Alpha mode
  33002. if (enableAlphaMode) {
  33003. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  33004. }
  33005. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  33006. var step = _a[_i];
  33007. step.action(this, subMesh, batch);
  33008. }
  33009. var effect;
  33010. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33011. effect = subMesh.effect;
  33012. }
  33013. else {
  33014. effect = this._effectiveMaterial.getEffect();
  33015. }
  33016. if (!effect) {
  33017. return this;
  33018. }
  33019. var sideOrientation = this.overrideMaterialSideOrientation;
  33020. if (sideOrientation == null) {
  33021. sideOrientation = this._effectiveMaterial.sideOrientation;
  33022. if (this._getWorldMatrixDeterminant() < 0) {
  33023. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  33024. }
  33025. }
  33026. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  33027. if (this._effectiveMaterial.forceDepthWrite) {
  33028. engine.setDepthWrite(true);
  33029. }
  33030. // Bind
  33031. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  33032. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  33033. this._bind(subMesh, effect, fillMode);
  33034. }
  33035. var world = this.getWorldMatrix();
  33036. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33037. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  33038. }
  33039. else {
  33040. this._effectiveMaterial.bind(world, this);
  33041. }
  33042. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  33043. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  33044. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33045. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  33046. }
  33047. // Draw
  33048. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33049. // Unbind
  33050. this._effectiveMaterial.unbind();
  33051. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  33052. var step = _c[_b];
  33053. step.action(this, subMesh, batch);
  33054. }
  33055. if (this._onAfterRenderObservable) {
  33056. this._onAfterRenderObservable.notifyObservers(this);
  33057. }
  33058. return this;
  33059. };
  33060. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  33061. if (isInstance && effectiveMaterial) {
  33062. effectiveMaterial.bindOnlyWorldMatrix(world);
  33063. }
  33064. };
  33065. /**
  33066. * Normalize matrix weights so that all vertices have a total weight set to 1
  33067. */
  33068. Mesh.prototype.cleanMatrixWeights = function () {
  33069. var epsilon = 1e-3;
  33070. var noInfluenceBoneIndex = 0.0;
  33071. if (this.skeleton) {
  33072. noInfluenceBoneIndex = this.skeleton.bones.length;
  33073. }
  33074. else {
  33075. return;
  33076. }
  33077. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33078. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33079. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33080. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33081. var influencers = this.numBoneInfluencers;
  33082. var size = matricesWeights.length;
  33083. for (var i = 0; i < size; i += 4) {
  33084. var weight = 0.0;
  33085. var firstZeroWeight = -1;
  33086. for (var j = 0; j < 4; j++) {
  33087. var w = matricesWeights[i + j];
  33088. weight += w;
  33089. if (w < epsilon && firstZeroWeight < 0) {
  33090. firstZeroWeight = j;
  33091. }
  33092. }
  33093. if (matricesWeightsExtra) {
  33094. for (var j = 0; j < 4; j++) {
  33095. var w = matricesWeightsExtra[i + j];
  33096. weight += w;
  33097. if (w < epsilon && firstZeroWeight < 0) {
  33098. firstZeroWeight = j + 4;
  33099. }
  33100. }
  33101. }
  33102. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  33103. firstZeroWeight = influencers - 1;
  33104. }
  33105. if (weight > epsilon) {
  33106. var mweight = 1.0 / weight;
  33107. for (var j = 0; j < 4; j++) {
  33108. matricesWeights[i + j] *= mweight;
  33109. }
  33110. if (matricesWeightsExtra) {
  33111. for (var j = 0; j < 4; j++) {
  33112. matricesWeightsExtra[i + j] *= mweight;
  33113. }
  33114. }
  33115. }
  33116. else {
  33117. if (firstZeroWeight >= 4) {
  33118. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  33119. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  33120. }
  33121. else {
  33122. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  33123. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  33124. }
  33125. }
  33126. }
  33127. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  33128. if (matricesIndicesExtra) {
  33129. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  33130. }
  33131. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33132. if (matricesWeightsExtra) {
  33133. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  33134. }
  33135. };
  33136. /** @hidden */
  33137. Mesh.prototype._checkDelayState = function () {
  33138. var scene = this.getScene();
  33139. if (this._geometry) {
  33140. this._geometry.load(scene);
  33141. }
  33142. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33143. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33144. this._queueLoad(scene);
  33145. }
  33146. return this;
  33147. };
  33148. Mesh.prototype._queueLoad = function (scene) {
  33149. var _this = this;
  33150. scene._addPendingData(this);
  33151. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  33152. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33153. if (data instanceof ArrayBuffer) {
  33154. _this._delayLoadingFunction(data, _this);
  33155. }
  33156. else {
  33157. _this._delayLoadingFunction(JSON.parse(data), _this);
  33158. }
  33159. _this.instances.forEach(function (instance) {
  33160. instance._syncSubMeshes();
  33161. });
  33162. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33163. scene._removePendingData(_this);
  33164. }, function () { }, scene.database, getBinaryData);
  33165. return this;
  33166. };
  33167. /**
  33168. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  33169. * A mesh is in the frustum if its bounding box intersects the frustum
  33170. * @param frustumPlanes defines the frustum to test
  33171. * @returns true if the mesh is in the frustum planes
  33172. */
  33173. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  33174. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33175. return false;
  33176. }
  33177. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  33178. return false;
  33179. }
  33180. this._checkDelayState();
  33181. return true;
  33182. };
  33183. /**
  33184. * Sets the mesh material by the material or multiMaterial `id` property
  33185. * @param id is a string identifying the material or the multiMaterial
  33186. * @returns the current mesh
  33187. */
  33188. Mesh.prototype.setMaterialByID = function (id) {
  33189. var materials = this.getScene().materials;
  33190. var index;
  33191. for (index = materials.length - 1; index > -1; index--) {
  33192. if (materials[index].id === id) {
  33193. this.material = materials[index];
  33194. return this;
  33195. }
  33196. }
  33197. // Multi
  33198. var multiMaterials = this.getScene().multiMaterials;
  33199. for (index = multiMaterials.length - 1; index > -1; index--) {
  33200. if (multiMaterials[index].id === id) {
  33201. this.material = multiMaterials[index];
  33202. return this;
  33203. }
  33204. }
  33205. return this;
  33206. };
  33207. /**
  33208. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  33209. * @returns an array of IAnimatable
  33210. */
  33211. Mesh.prototype.getAnimatables = function () {
  33212. var results = new Array();
  33213. if (this.material) {
  33214. results.push(this.material);
  33215. }
  33216. if (this.skeleton) {
  33217. results.push(this.skeleton);
  33218. }
  33219. return results;
  33220. };
  33221. /**
  33222. * Modifies the mesh geometry according to the passed transformation matrix.
  33223. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  33224. * The mesh normals are modified using the same transformation.
  33225. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33226. * @param transform defines the transform matrix to use
  33227. * @see http://doc.babylonjs.com/resources/baking_transformations
  33228. * @returns the current mesh
  33229. */
  33230. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  33231. // Position
  33232. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33233. return this;
  33234. }
  33235. var submeshes = this.subMeshes.splice(0);
  33236. this._resetPointsArrayCache();
  33237. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33238. var temp = new Array();
  33239. var index;
  33240. for (index = 0; index < data.length; index += 3) {
  33241. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  33242. }
  33243. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  33244. // Normals
  33245. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33246. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33247. temp = [];
  33248. for (index = 0; index < data.length; index += 3) {
  33249. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  33250. }
  33251. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  33252. }
  33253. // flip faces?
  33254. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  33255. this.flipFaces();
  33256. }
  33257. // Restore submeshes
  33258. this.releaseSubMeshes();
  33259. this.subMeshes = submeshes;
  33260. return this;
  33261. };
  33262. /**
  33263. * Modifies the mesh geometry according to its own current World Matrix.
  33264. * The mesh World Matrix is then reset.
  33265. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  33266. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33267. * @see http://doc.babylonjs.com/resources/baking_transformations
  33268. * @returns the current mesh
  33269. */
  33270. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  33271. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  33272. this.scaling.copyFromFloats(1, 1, 1);
  33273. this.position.copyFromFloats(0, 0, 0);
  33274. this.rotation.copyFromFloats(0, 0, 0);
  33275. //only if quaternion is already set
  33276. if (this.rotationQuaternion) {
  33277. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  33278. }
  33279. this._worldMatrix = BABYLON.Matrix.Identity();
  33280. return this;
  33281. };
  33282. Object.defineProperty(Mesh.prototype, "_positions", {
  33283. // Cache
  33284. /** @hidden */
  33285. get: function () {
  33286. if (this._geometry) {
  33287. return this._geometry._positions;
  33288. }
  33289. return null;
  33290. },
  33291. enumerable: true,
  33292. configurable: true
  33293. });
  33294. /** @hidden */
  33295. Mesh.prototype._resetPointsArrayCache = function () {
  33296. if (this._geometry) {
  33297. this._geometry._resetPointsArrayCache();
  33298. }
  33299. return this;
  33300. };
  33301. /** @hidden */
  33302. Mesh.prototype._generatePointsArray = function () {
  33303. if (this._geometry) {
  33304. return this._geometry._generatePointsArray();
  33305. }
  33306. return false;
  33307. };
  33308. /**
  33309. * Returns a new Mesh object generated from the current mesh properties.
  33310. * This method must not get confused with createInstance()
  33311. * @param name is a string, the name given to the new mesh
  33312. * @param newParent can be any Node object (default `null`)
  33313. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  33314. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  33315. * @returns a new mesh
  33316. */
  33317. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  33318. if (name === void 0) { name = ""; }
  33319. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  33320. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  33321. };
  33322. /**
  33323. * Releases resources associated with this mesh.
  33324. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  33325. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  33326. */
  33327. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  33328. var _this = this;
  33329. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  33330. this.morphTargetManager = null;
  33331. if (this._geometry) {
  33332. this._geometry.releaseForMesh(this, true);
  33333. }
  33334. if (this._onBeforeDrawObservable) {
  33335. this._onBeforeDrawObservable.clear();
  33336. }
  33337. if (this._onBeforeRenderObservable) {
  33338. this._onBeforeRenderObservable.clear();
  33339. }
  33340. if (this._onAfterRenderObservable) {
  33341. this._onAfterRenderObservable.clear();
  33342. }
  33343. // Sources
  33344. var meshes = this.getScene().meshes;
  33345. meshes.forEach(function (abstractMesh) {
  33346. var mesh = abstractMesh;
  33347. if (mesh._source && mesh._source === _this) {
  33348. mesh._source = null;
  33349. }
  33350. });
  33351. this._source = null;
  33352. // Instances
  33353. if (this._instanceDataStorage.instancesBuffer) {
  33354. this._instanceDataStorage.instancesBuffer.dispose();
  33355. this._instanceDataStorage.instancesBuffer = null;
  33356. }
  33357. while (this.instances.length) {
  33358. this.instances[0].dispose();
  33359. }
  33360. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  33361. };
  33362. /**
  33363. * Modifies the mesh geometry according to a displacement map.
  33364. * 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.
  33365. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33366. * @param url is a string, the URL from the image file is to be downloaded.
  33367. * @param minHeight is the lower limit of the displacement.
  33368. * @param maxHeight is the upper limit of the displacement.
  33369. * @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.
  33370. * @param uvOffset is an optional vector2 used to offset UV.
  33371. * @param uvScale is an optional vector2 used to scale UV.
  33372. * @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.
  33373. * @returns the Mesh.
  33374. */
  33375. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  33376. var _this = this;
  33377. if (forceUpdate === void 0) { forceUpdate = false; }
  33378. var scene = this.getScene();
  33379. var onload = function (img) {
  33380. // Getting height map data
  33381. var canvas = document.createElement("canvas");
  33382. var context = canvas.getContext("2d");
  33383. var heightMapWidth = img.width;
  33384. var heightMapHeight = img.height;
  33385. canvas.width = heightMapWidth;
  33386. canvas.height = heightMapHeight;
  33387. context.drawImage(img, 0, 0);
  33388. // Create VertexData from map data
  33389. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33390. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33391. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  33392. //execute success callback, if set
  33393. if (onSuccess) {
  33394. onSuccess(_this);
  33395. }
  33396. };
  33397. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33398. return this;
  33399. };
  33400. /**
  33401. * Modifies the mesh geometry according to a displacementMap buffer.
  33402. * 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.
  33403. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33404. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  33405. * @param heightMapWidth is the width of the buffer image.
  33406. * @param heightMapHeight is the height of the buffer image.
  33407. * @param minHeight is the lower limit of the displacement.
  33408. * @param maxHeight is the upper limit of the displacement.
  33409. * @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.
  33410. * @param uvOffset is an optional vector2 used to offset UV.
  33411. * @param uvScale is an optional vector2 used to scale UV.
  33412. * @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.
  33413. * @returns the Mesh.
  33414. */
  33415. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  33416. if (forceUpdate === void 0) { forceUpdate = false; }
  33417. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33418. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33419. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33420. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33421. return this;
  33422. }
  33423. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  33424. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33425. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33426. var position = BABYLON.Vector3.Zero();
  33427. var normal = BABYLON.Vector3.Zero();
  33428. var uv = BABYLON.Vector2.Zero();
  33429. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33430. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33431. for (var index = 0; index < positions.length; index += 3) {
  33432. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33433. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33434. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33435. // Compute height
  33436. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33437. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33438. var pos = (u + v * heightMapWidth) * 4;
  33439. var r = buffer[pos] / 255.0;
  33440. var g = buffer[pos + 1] / 255.0;
  33441. var b = buffer[pos + 2] / 255.0;
  33442. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33443. normal.normalize();
  33444. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33445. position = position.add(normal);
  33446. position.toArray(positions, index);
  33447. }
  33448. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33449. if (forceUpdate) {
  33450. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33451. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33452. }
  33453. else {
  33454. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33455. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33456. }
  33457. return this;
  33458. };
  33459. /**
  33460. * Modify the mesh to get a flat shading rendering.
  33461. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33462. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33463. * @returns current mesh
  33464. */
  33465. Mesh.prototype.convertToFlatShadedMesh = function () {
  33466. var kinds = this.getVerticesDataKinds();
  33467. var vbs = {};
  33468. var data = {};
  33469. var newdata = {};
  33470. var updatableNormals = false;
  33471. var kindIndex;
  33472. var kind;
  33473. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33474. kind = kinds[kindIndex];
  33475. var vertexBuffer = this.getVertexBuffer(kind);
  33476. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33477. updatableNormals = vertexBuffer.isUpdatable();
  33478. kinds.splice(kindIndex, 1);
  33479. kindIndex--;
  33480. continue;
  33481. }
  33482. vbs[kind] = vertexBuffer;
  33483. data[kind] = vbs[kind].getData();
  33484. newdata[kind] = [];
  33485. }
  33486. // Save previous submeshes
  33487. var previousSubmeshes = this.subMeshes.slice(0);
  33488. var indices = this.getIndices();
  33489. var totalIndices = this.getTotalIndices();
  33490. // Generating unique vertices per face
  33491. var index;
  33492. for (index = 0; index < totalIndices; index++) {
  33493. var vertexIndex = indices[index];
  33494. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33495. kind = kinds[kindIndex];
  33496. var stride = vbs[kind].getStrideSize();
  33497. for (var offset = 0; offset < stride; offset++) {
  33498. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33499. }
  33500. }
  33501. }
  33502. // Updating faces & normal
  33503. var normals = [];
  33504. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33505. for (index = 0; index < totalIndices; index += 3) {
  33506. indices[index] = index;
  33507. indices[index + 1] = index + 1;
  33508. indices[index + 2] = index + 2;
  33509. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33510. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33511. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33512. var p1p2 = p1.subtract(p2);
  33513. var p3p2 = p3.subtract(p2);
  33514. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33515. // Store same normals for every vertex
  33516. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33517. normals.push(normal.x);
  33518. normals.push(normal.y);
  33519. normals.push(normal.z);
  33520. }
  33521. }
  33522. this.setIndices(indices);
  33523. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33524. // Updating vertex buffers
  33525. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33526. kind = kinds[kindIndex];
  33527. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33528. }
  33529. // Updating submeshes
  33530. this.releaseSubMeshes();
  33531. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33532. var previousOne = previousSubmeshes[submeshIndex];
  33533. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33534. }
  33535. this.synchronizeInstances();
  33536. return this;
  33537. };
  33538. /**
  33539. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33540. * In other words, more vertices, no more indices and a single bigger VBO.
  33541. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33542. * @returns current mesh
  33543. */
  33544. Mesh.prototype.convertToUnIndexedMesh = function () {
  33545. var kinds = this.getVerticesDataKinds();
  33546. var vbs = {};
  33547. var data = {};
  33548. var newdata = {};
  33549. var kindIndex;
  33550. var kind;
  33551. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33552. kind = kinds[kindIndex];
  33553. var vertexBuffer = this.getVertexBuffer(kind);
  33554. vbs[kind] = vertexBuffer;
  33555. data[kind] = vbs[kind].getData();
  33556. newdata[kind] = [];
  33557. }
  33558. // Save previous submeshes
  33559. var previousSubmeshes = this.subMeshes.slice(0);
  33560. var indices = this.getIndices();
  33561. var totalIndices = this.getTotalIndices();
  33562. // Generating unique vertices per face
  33563. var index;
  33564. for (index = 0; index < totalIndices; index++) {
  33565. var vertexIndex = indices[index];
  33566. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33567. kind = kinds[kindIndex];
  33568. var stride = vbs[kind].getStrideSize();
  33569. for (var offset = 0; offset < stride; offset++) {
  33570. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33571. }
  33572. }
  33573. }
  33574. // Updating indices
  33575. for (index = 0; index < totalIndices; index += 3) {
  33576. indices[index] = index;
  33577. indices[index + 1] = index + 1;
  33578. indices[index + 2] = index + 2;
  33579. }
  33580. this.setIndices(indices);
  33581. // Updating vertex buffers
  33582. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33583. kind = kinds[kindIndex];
  33584. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33585. }
  33586. // Updating submeshes
  33587. this.releaseSubMeshes();
  33588. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33589. var previousOne = previousSubmeshes[submeshIndex];
  33590. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33591. }
  33592. this._unIndexed = true;
  33593. this.synchronizeInstances();
  33594. return this;
  33595. };
  33596. /**
  33597. * Inverses facet orientations.
  33598. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33599. * @param flipNormals will also inverts the normals
  33600. * @returns current mesh
  33601. */
  33602. Mesh.prototype.flipFaces = function (flipNormals) {
  33603. if (flipNormals === void 0) { flipNormals = false; }
  33604. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33605. var i;
  33606. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33607. for (i = 0; i < vertex_data.normals.length; i++) {
  33608. vertex_data.normals[i] *= -1;
  33609. }
  33610. }
  33611. if (vertex_data.indices) {
  33612. var temp;
  33613. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33614. // reassign indices
  33615. temp = vertex_data.indices[i + 1];
  33616. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33617. vertex_data.indices[i + 2] = temp;
  33618. }
  33619. }
  33620. vertex_data.applyToMesh(this);
  33621. return this;
  33622. };
  33623. // Instances
  33624. /**
  33625. * Creates a new InstancedMesh object from the mesh model.
  33626. * Warning : this method is not supported for Line mesh and LineSystem
  33627. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  33628. * @param name defines the name of the new instance
  33629. * @returns a new InstancedMesh
  33630. */
  33631. Mesh.prototype.createInstance = function (name) {
  33632. return new BABYLON.InstancedMesh(name, this);
  33633. };
  33634. /**
  33635. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33636. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33637. * @returns the current mesh
  33638. */
  33639. Mesh.prototype.synchronizeInstances = function () {
  33640. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33641. var instance = this.instances[instanceIndex];
  33642. instance._syncSubMeshes();
  33643. }
  33644. return this;
  33645. };
  33646. /**
  33647. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33648. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33649. * This should be used together with the simplification to avoid disappearing triangles.
  33650. * @param successCallback an optional success callback to be called after the optimization finished.
  33651. * @returns the current mesh
  33652. */
  33653. Mesh.prototype.optimizeIndices = function (successCallback) {
  33654. var _this = this;
  33655. var indices = this.getIndices();
  33656. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33657. if (!positions || !indices) {
  33658. return this;
  33659. }
  33660. var vectorPositions = new Array();
  33661. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33662. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33663. }
  33664. var dupes = new Array();
  33665. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33666. var realPos = vectorPositions.length - 1 - iteration;
  33667. var testedPosition = vectorPositions[realPos];
  33668. for (var j = 0; j < realPos; ++j) {
  33669. var againstPosition = vectorPositions[j];
  33670. if (testedPosition.equals(againstPosition)) {
  33671. dupes[realPos] = j;
  33672. break;
  33673. }
  33674. }
  33675. }, function () {
  33676. for (var i = 0; i < indices.length; ++i) {
  33677. indices[i] = dupes[indices[i]] || indices[i];
  33678. }
  33679. //indices are now reordered
  33680. var originalSubMeshes = _this.subMeshes.slice(0);
  33681. _this.setIndices(indices);
  33682. _this.subMeshes = originalSubMeshes;
  33683. if (successCallback) {
  33684. successCallback(_this);
  33685. }
  33686. });
  33687. return this;
  33688. };
  33689. /**
  33690. * Serialize current mesh
  33691. * @param serializationObject defines the object which will receive the serialization data
  33692. */
  33693. Mesh.prototype.serialize = function (serializationObject) {
  33694. serializationObject.name = this.name;
  33695. serializationObject.id = this.id;
  33696. serializationObject.type = this.getClassName();
  33697. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33698. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33699. }
  33700. serializationObject.position = this.position.asArray();
  33701. if (this.rotationQuaternion) {
  33702. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33703. }
  33704. else if (this.rotation) {
  33705. serializationObject.rotation = this.rotation.asArray();
  33706. }
  33707. serializationObject.scaling = this.scaling.asArray();
  33708. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33709. serializationObject.isEnabled = this.isEnabled(false);
  33710. serializationObject.isVisible = this.isVisible;
  33711. serializationObject.infiniteDistance = this.infiniteDistance;
  33712. serializationObject.pickable = this.isPickable;
  33713. serializationObject.receiveShadows = this.receiveShadows;
  33714. serializationObject.billboardMode = this.billboardMode;
  33715. serializationObject.visibility = this.visibility;
  33716. serializationObject.checkCollisions = this.checkCollisions;
  33717. serializationObject.isBlocker = this.isBlocker;
  33718. // Parent
  33719. if (this.parent) {
  33720. serializationObject.parentId = this.parent.id;
  33721. }
  33722. // Geometry
  33723. serializationObject.isUnIndexed = this.isUnIndexed;
  33724. var geometry = this._geometry;
  33725. if (geometry) {
  33726. var geometryId = geometry.id;
  33727. serializationObject.geometryId = geometryId;
  33728. // SubMeshes
  33729. serializationObject.subMeshes = [];
  33730. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33731. var subMesh = this.subMeshes[subIndex];
  33732. serializationObject.subMeshes.push({
  33733. materialIndex: subMesh.materialIndex,
  33734. verticesStart: subMesh.verticesStart,
  33735. verticesCount: subMesh.verticesCount,
  33736. indexStart: subMesh.indexStart,
  33737. indexCount: subMesh.indexCount
  33738. });
  33739. }
  33740. }
  33741. // Material
  33742. if (this.material) {
  33743. serializationObject.materialId = this.material.id;
  33744. }
  33745. else {
  33746. this.material = null;
  33747. }
  33748. // Morph targets
  33749. if (this.morphTargetManager) {
  33750. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33751. }
  33752. // Skeleton
  33753. if (this.skeleton) {
  33754. serializationObject.skeletonId = this.skeleton.id;
  33755. }
  33756. // Physics
  33757. //TODO implement correct serialization for physics impostors.
  33758. var impostor = this.getPhysicsImpostor();
  33759. if (impostor) {
  33760. serializationObject.physicsMass = impostor.getParam("mass");
  33761. serializationObject.physicsFriction = impostor.getParam("friction");
  33762. serializationObject.physicsRestitution = impostor.getParam("mass");
  33763. serializationObject.physicsImpostor = impostor.type;
  33764. }
  33765. // Metadata
  33766. if (this.metadata) {
  33767. serializationObject.metadata = this.metadata;
  33768. }
  33769. // Instances
  33770. serializationObject.instances = [];
  33771. for (var index = 0; index < this.instances.length; index++) {
  33772. var instance = this.instances[index];
  33773. if (instance.doNotSerialize) {
  33774. continue;
  33775. }
  33776. var serializationInstance = {
  33777. name: instance.name,
  33778. id: instance.id,
  33779. position: instance.position.asArray(),
  33780. scaling: instance.scaling.asArray()
  33781. };
  33782. if (instance.parent) {
  33783. serializationInstance.parentId = instance.parent.id;
  33784. }
  33785. if (instance.rotationQuaternion) {
  33786. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33787. }
  33788. else if (instance.rotation) {
  33789. serializationInstance.rotation = instance.rotation.asArray();
  33790. }
  33791. serializationObject.instances.push(serializationInstance);
  33792. // Animations
  33793. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33794. serializationInstance.ranges = instance.serializeAnimationRanges();
  33795. }
  33796. //
  33797. // Animations
  33798. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33799. serializationObject.ranges = this.serializeAnimationRanges();
  33800. // Layer mask
  33801. serializationObject.layerMask = this.layerMask;
  33802. // Alpha
  33803. serializationObject.alphaIndex = this.alphaIndex;
  33804. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33805. // Overlay
  33806. serializationObject.overlayAlpha = this.overlayAlpha;
  33807. serializationObject.overlayColor = this.overlayColor.asArray();
  33808. serializationObject.renderOverlay = this.renderOverlay;
  33809. // Fog
  33810. serializationObject.applyFog = this.applyFog;
  33811. // Action Manager
  33812. if (this.actionManager) {
  33813. serializationObject.actions = this.actionManager.serialize(this.name);
  33814. }
  33815. };
  33816. /** @hidden */
  33817. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33818. if (!this.geometry) {
  33819. return;
  33820. }
  33821. this._markSubMeshesAsAttributesDirty();
  33822. var morphTargetManager = this._morphTargetManager;
  33823. if (morphTargetManager && morphTargetManager.vertexCount) {
  33824. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33825. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33826. this.morphTargetManager = null;
  33827. return;
  33828. }
  33829. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33830. var morphTarget = morphTargetManager.getActiveTarget(index);
  33831. var positions = morphTarget.getPositions();
  33832. if (!positions) {
  33833. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33834. return;
  33835. }
  33836. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33837. var normals = morphTarget.getNormals();
  33838. if (normals) {
  33839. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33840. }
  33841. var tangents = morphTarget.getTangents();
  33842. if (tangents) {
  33843. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33844. }
  33845. }
  33846. }
  33847. else {
  33848. var index = 0;
  33849. // Positions
  33850. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33851. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33852. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33853. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33854. }
  33855. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33856. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33857. }
  33858. index++;
  33859. }
  33860. }
  33861. };
  33862. // Statics
  33863. /**
  33864. * Returns a new Mesh object parsed from the source provided.
  33865. * @param parsedMesh is the source
  33866. * @param scene defines the hosting scene
  33867. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  33868. * @returns a new Mesh
  33869. */
  33870. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33871. var mesh;
  33872. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33873. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33874. }
  33875. else {
  33876. mesh = new Mesh(parsedMesh.name, scene);
  33877. }
  33878. mesh.id = parsedMesh.id;
  33879. if (BABYLON.Tags) {
  33880. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33881. }
  33882. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33883. if (parsedMesh.metadata !== undefined) {
  33884. mesh.metadata = parsedMesh.metadata;
  33885. }
  33886. if (parsedMesh.rotationQuaternion) {
  33887. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33888. }
  33889. else if (parsedMesh.rotation) {
  33890. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33891. }
  33892. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33893. if (parsedMesh.localMatrix) {
  33894. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33895. }
  33896. else if (parsedMesh.pivotMatrix) {
  33897. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33898. }
  33899. mesh.setEnabled(parsedMesh.isEnabled);
  33900. mesh.isVisible = parsedMesh.isVisible;
  33901. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33902. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33903. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33904. if (parsedMesh.applyFog !== undefined) {
  33905. mesh.applyFog = parsedMesh.applyFog;
  33906. }
  33907. if (parsedMesh.pickable !== undefined) {
  33908. mesh.isPickable = parsedMesh.pickable;
  33909. }
  33910. if (parsedMesh.alphaIndex !== undefined) {
  33911. mesh.alphaIndex = parsedMesh.alphaIndex;
  33912. }
  33913. mesh.receiveShadows = parsedMesh.receiveShadows;
  33914. mesh.billboardMode = parsedMesh.billboardMode;
  33915. if (parsedMesh.visibility !== undefined) {
  33916. mesh.visibility = parsedMesh.visibility;
  33917. }
  33918. mesh.checkCollisions = parsedMesh.checkCollisions;
  33919. if (parsedMesh.isBlocker !== undefined) {
  33920. mesh.isBlocker = parsedMesh.isBlocker;
  33921. }
  33922. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33923. // freezeWorldMatrix
  33924. if (parsedMesh.freezeWorldMatrix) {
  33925. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33926. }
  33927. // Parent
  33928. if (parsedMesh.parentId) {
  33929. mesh._waitingParentId = parsedMesh.parentId;
  33930. }
  33931. // Actions
  33932. if (parsedMesh.actions !== undefined) {
  33933. mesh._waitingActions = parsedMesh.actions;
  33934. }
  33935. // Overlay
  33936. if (parsedMesh.overlayAlpha !== undefined) {
  33937. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33938. }
  33939. if (parsedMesh.overlayColor !== undefined) {
  33940. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33941. }
  33942. if (parsedMesh.renderOverlay !== undefined) {
  33943. mesh.renderOverlay = parsedMesh.renderOverlay;
  33944. }
  33945. // Geometry
  33946. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33947. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33948. if (parsedMesh.delayLoadingFile) {
  33949. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33950. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33951. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33952. if (parsedMesh._binaryInfo) {
  33953. mesh._binaryInfo = parsedMesh._binaryInfo;
  33954. }
  33955. mesh._delayInfo = [];
  33956. if (parsedMesh.hasUVs) {
  33957. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33958. }
  33959. if (parsedMesh.hasUVs2) {
  33960. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33961. }
  33962. if (parsedMesh.hasUVs3) {
  33963. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33964. }
  33965. if (parsedMesh.hasUVs4) {
  33966. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33967. }
  33968. if (parsedMesh.hasUVs5) {
  33969. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33970. }
  33971. if (parsedMesh.hasUVs6) {
  33972. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33973. }
  33974. if (parsedMesh.hasColors) {
  33975. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33976. }
  33977. if (parsedMesh.hasMatricesIndices) {
  33978. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33979. }
  33980. if (parsedMesh.hasMatricesWeights) {
  33981. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33982. }
  33983. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33984. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33985. mesh._checkDelayState();
  33986. }
  33987. }
  33988. else {
  33989. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33990. }
  33991. // Material
  33992. if (parsedMesh.materialId) {
  33993. mesh.setMaterialByID(parsedMesh.materialId);
  33994. }
  33995. else {
  33996. mesh.material = null;
  33997. }
  33998. // Morph targets
  33999. if (parsedMesh.morphTargetManagerId > -1) {
  34000. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  34001. }
  34002. // Skeleton
  34003. if (parsedMesh.skeletonId > -1) {
  34004. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  34005. if (parsedMesh.numBoneInfluencers) {
  34006. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  34007. }
  34008. }
  34009. // Animations
  34010. if (parsedMesh.animations) {
  34011. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  34012. var parsedAnimation = parsedMesh.animations[animationIndex];
  34013. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34014. }
  34015. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  34016. }
  34017. if (parsedMesh.autoAnimate) {
  34018. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  34019. }
  34020. // Layer Mask
  34021. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  34022. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  34023. }
  34024. else {
  34025. mesh.layerMask = 0x0FFFFFFF;
  34026. }
  34027. // Physics
  34028. if (parsedMesh.physicsImpostor) {
  34029. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  34030. mass: parsedMesh.physicsMass,
  34031. friction: parsedMesh.physicsFriction,
  34032. restitution: parsedMesh.physicsRestitution
  34033. }, scene);
  34034. }
  34035. // Instances
  34036. if (parsedMesh.instances) {
  34037. for (var index = 0; index < parsedMesh.instances.length; index++) {
  34038. var parsedInstance = parsedMesh.instances[index];
  34039. var instance = mesh.createInstance(parsedInstance.name);
  34040. if (parsedInstance.id) {
  34041. instance.id = parsedInstance.id;
  34042. }
  34043. if (BABYLON.Tags) {
  34044. if (parsedInstance.tags) {
  34045. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  34046. }
  34047. else {
  34048. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  34049. }
  34050. }
  34051. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  34052. if (parsedInstance.parentId) {
  34053. instance._waitingParentId = parsedInstance.parentId;
  34054. }
  34055. if (parsedInstance.rotationQuaternion) {
  34056. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  34057. }
  34058. else if (parsedInstance.rotation) {
  34059. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  34060. }
  34061. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  34062. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  34063. instance.checkCollisions = parsedInstance.checkCollisions;
  34064. }
  34065. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  34066. instance.isPickable = parsedInstance.pickable;
  34067. }
  34068. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  34069. instance.showBoundingBox = parsedInstance.showBoundingBox;
  34070. }
  34071. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34072. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  34073. }
  34074. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34075. instance.alphaIndex = parsedInstance.alphaIndex;
  34076. }
  34077. // Physics
  34078. if (parsedInstance.physicsImpostor) {
  34079. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  34080. mass: parsedInstance.physicsMass,
  34081. friction: parsedInstance.physicsFriction,
  34082. restitution: parsedInstance.physicsRestitution
  34083. }, scene);
  34084. }
  34085. // Animation
  34086. if (parsedInstance.animations) {
  34087. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  34088. parsedAnimation = parsedInstance.animations[animationIndex];
  34089. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34090. }
  34091. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  34092. if (parsedInstance.autoAnimate) {
  34093. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  34094. }
  34095. }
  34096. }
  34097. }
  34098. return mesh;
  34099. };
  34100. /**
  34101. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  34102. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34103. * @param name defines the name of the mesh to create
  34104. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  34105. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  34106. * @param closePath creates a seam between the first and the last points of each path of the path array
  34107. * @param offset is taken in account only if the `pathArray` is containing a single path
  34108. * @param scene defines the hosting scene
  34109. * @param updatable defines if the mesh must be flagged as updatable
  34110. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34111. * @param instance defines an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#ribbon)
  34112. * @returns a new Mesh
  34113. */
  34114. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  34115. if (closeArray === void 0) { closeArray = false; }
  34116. if (updatable === void 0) { updatable = false; }
  34117. return BABYLON.MeshBuilder.CreateRibbon(name, {
  34118. pathArray: pathArray,
  34119. closeArray: closeArray,
  34120. closePath: closePath,
  34121. offset: offset,
  34122. updatable: updatable,
  34123. sideOrientation: sideOrientation,
  34124. instance: instance
  34125. }, scene);
  34126. };
  34127. /**
  34128. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  34129. * @param name defines the name of the mesh to create
  34130. * @param radius sets the radius size (float) of the polygon (default 0.5)
  34131. * @param 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
  34132. * @param scene defines the hosting scene
  34133. * @param updatable defines if the mesh must be flagged as updatable
  34134. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34135. * @returns a new Mesh
  34136. */
  34137. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  34138. if (scene === void 0) { scene = null; }
  34139. var options = {
  34140. radius: radius,
  34141. tessellation: tessellation,
  34142. sideOrientation: sideOrientation,
  34143. updatable: updatable
  34144. };
  34145. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  34146. };
  34147. /**
  34148. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  34149. * @param name defines the name of the mesh to create
  34150. * @param size sets the size (float) of each box side (default 1)
  34151. * @param scene defines the hosting scene
  34152. * @param updatable defines if the mesh must be flagged as updatable
  34153. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34154. * @returns a new Mesh
  34155. */
  34156. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  34157. if (scene === void 0) { scene = null; }
  34158. var options = {
  34159. size: size,
  34160. sideOrientation: sideOrientation,
  34161. updatable: updatable
  34162. };
  34163. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  34164. };
  34165. /**
  34166. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  34167. * @param name defines the name of the mesh to create
  34168. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  34169. * @param diameter sets the diameter size (float) of the sphere (default 1)
  34170. * @param scene defines the hosting scene
  34171. * @param updatable defines if the mesh must be flagged as updatable
  34172. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34173. * @returns a new Mesh
  34174. */
  34175. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  34176. var options = {
  34177. segments: segments,
  34178. diameterX: diameter,
  34179. diameterY: diameter,
  34180. diameterZ: diameter,
  34181. sideOrientation: sideOrientation,
  34182. updatable: updatable
  34183. };
  34184. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  34185. };
  34186. /**
  34187. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  34188. * @param name defines the name of the mesh to create
  34189. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  34190. * @param diameterTop set the top cap diameter (floats, default 1)
  34191. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  34192. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  34193. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  34194. * @param scene defines the hosting scene
  34195. * @param updatable defines if the mesh must be flagged as updatable
  34196. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34197. * @returns a new Mesh
  34198. */
  34199. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  34200. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  34201. if (scene !== undefined) {
  34202. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  34203. updatable = scene;
  34204. }
  34205. scene = subdivisions;
  34206. subdivisions = 1;
  34207. }
  34208. var options = {
  34209. height: height,
  34210. diameterTop: diameterTop,
  34211. diameterBottom: diameterBottom,
  34212. tessellation: tessellation,
  34213. subdivisions: subdivisions,
  34214. sideOrientation: sideOrientation,
  34215. updatable: updatable
  34216. };
  34217. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  34218. };
  34219. // Torus (Code from SharpDX.org)
  34220. /**
  34221. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  34222. * @param name defines the name of the mesh to create
  34223. * @param diameter sets the diameter size (float) of the torus (default 1)
  34224. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  34225. * @param tessellation sets the number of torus sides (postive integer, default 16)
  34226. * @param scene defines the hosting scene
  34227. * @param updatable defines if the mesh must be flagged as updatable
  34228. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34229. * @returns a new Mesh
  34230. */
  34231. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  34232. var options = {
  34233. diameter: diameter,
  34234. thickness: thickness,
  34235. tessellation: tessellation,
  34236. sideOrientation: sideOrientation,
  34237. updatable: updatable
  34238. };
  34239. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  34240. };
  34241. /**
  34242. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  34243. * @param name defines the name of the mesh to create
  34244. * @param radius sets the global radius size (float) of the torus knot (default 2)
  34245. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  34246. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  34247. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  34248. * @param p the number of windings on X axis (positive integers, default 2)
  34249. * @param q the number of windings on Y axis (positive integers, default 3)
  34250. * @param scene defines the hosting scene
  34251. * @param updatable defines if the mesh must be flagged as updatable
  34252. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34253. * @returns a new Mesh
  34254. */
  34255. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  34256. var options = {
  34257. radius: radius,
  34258. tube: tube,
  34259. radialSegments: radialSegments,
  34260. tubularSegments: tubularSegments,
  34261. p: p,
  34262. q: q,
  34263. sideOrientation: sideOrientation,
  34264. updatable: updatable
  34265. };
  34266. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  34267. };
  34268. /**
  34269. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  34270. * @param name defines the name of the mesh to create
  34271. * @param points is an array successive Vector3
  34272. * @param scene defines the hosting scene
  34273. * @param updatable defines if the mesh must be flagged as updatable
  34274. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines).
  34275. * @returns a new Mesh
  34276. */
  34277. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  34278. if (scene === void 0) { scene = null; }
  34279. if (updatable === void 0) { updatable = false; }
  34280. if (instance === void 0) { instance = null; }
  34281. var options = {
  34282. points: points,
  34283. updatable: updatable,
  34284. instance: instance
  34285. };
  34286. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  34287. };
  34288. /**
  34289. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  34290. * @param name defines the name of the mesh to create
  34291. * @param points is an array successive Vector3
  34292. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  34293. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  34294. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  34295. * @param scene defines the hosting scene
  34296. * @param updatable defines if the mesh must be flagged as updatable
  34297. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines)
  34298. * @returns a new Mesh
  34299. */
  34300. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  34301. if (scene === void 0) { scene = null; }
  34302. var options = {
  34303. points: points,
  34304. dashSize: dashSize,
  34305. gapSize: gapSize,
  34306. dashNb: dashNb,
  34307. updatable: updatable,
  34308. instance: instance
  34309. };
  34310. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  34311. };
  34312. /**
  34313. * Creates a polygon mesh.
  34314. * Please consider using the same method from the MeshBuilder class instead.
  34315. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  34316. * 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.
  34317. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34318. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34319. * Remember you can only change the shape positions, not their number when updating a polygon.
  34320. */
  34321. /**
  34322. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  34323. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  34324. * @param name defines the name of the mesh to create
  34325. * @param 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
  34326. * @param scene defines the hosting scene
  34327. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34328. * @param updatable defines if the mesh must be flagged as updatable
  34329. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34330. * @returns a new Mesh
  34331. */
  34332. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  34333. var options = {
  34334. shape: shape,
  34335. holes: holes,
  34336. updatable: updatable,
  34337. sideOrientation: sideOrientation
  34338. };
  34339. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  34340. };
  34341. /**
  34342. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  34343. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  34344. * @param name defines the name of the mesh to create
  34345. * @param 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
  34346. * @param depth defines the height of extrusion
  34347. * @param scene defines the hosting scene
  34348. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34349. * @param updatable defines if the mesh must be flagged as updatable
  34350. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34351. * @returns a new Mesh
  34352. */
  34353. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  34354. var options = {
  34355. shape: shape,
  34356. holes: holes,
  34357. depth: depth,
  34358. updatable: updatable,
  34359. sideOrientation: sideOrientation
  34360. };
  34361. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  34362. };
  34363. /**
  34364. * Creates an extruded shape mesh.
  34365. * The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. Please consider using the same method from the MeshBuilder class instead
  34366. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34367. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34368. * @param name defines the name of the mesh to create
  34369. * @param 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
  34370. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34371. * @param scale is the value to scale the shape
  34372. * @param rotation 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
  34373. * @param 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
  34374. * @param scene defines the hosting scene
  34375. * @param updatable defines if the mesh must be flagged as updatable
  34376. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34377. * @param 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/how_to/How_to_dynamically_morph_a_mesh#extruded-shape)
  34378. * @returns a new Mesh
  34379. */
  34380. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  34381. if (scene === void 0) { scene = null; }
  34382. var options = {
  34383. shape: shape,
  34384. path: path,
  34385. scale: scale,
  34386. rotation: rotation,
  34387. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34388. sideOrientation: sideOrientation,
  34389. instance: instance,
  34390. updatable: updatable
  34391. };
  34392. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  34393. };
  34394. /**
  34395. * Creates an custom extruded shape mesh.
  34396. * The custom extrusion is a parametric shape.
  34397. * It has no predefined shape. Its final shape will depend on the input parameters.
  34398. * Please consider using the same method from the MeshBuilder class instead
  34399. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34400. * @param name defines the name of the mesh to create
  34401. * @param 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
  34402. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34403. * @param scaleFunction is a custom Javascript function called on each path point
  34404. * @param rotationFunction is a custom Javascript function called on each path point
  34405. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  34406. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  34407. * @param 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
  34408. * @param scene defines the hosting scene
  34409. * @param updatable defines if the mesh must be flagged as updatable
  34410. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34411. * @param 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/how_to/how_to_dynamically_morph_a_mesh#extruded-shape)
  34412. * @returns a new Mesh
  34413. */
  34414. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34415. var options = {
  34416. shape: shape,
  34417. path: path,
  34418. scaleFunction: scaleFunction,
  34419. rotationFunction: rotationFunction,
  34420. ribbonCloseArray: ribbonCloseArray,
  34421. ribbonClosePath: ribbonClosePath,
  34422. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34423. sideOrientation: sideOrientation,
  34424. instance: instance,
  34425. updatable: updatable
  34426. };
  34427. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34428. };
  34429. /**
  34430. * Creates lathe mesh.
  34431. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34432. * Please consider using the same method from the MeshBuilder class instead
  34433. * @param name defines the name of the mesh to create
  34434. * @param 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
  34435. * @param radius is the radius value of the lathe
  34436. * @param tessellation is the side number of the lathe.
  34437. * @param scene defines the hosting scene
  34438. * @param updatable defines if the mesh must be flagged as updatable
  34439. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34440. * @returns a new Mesh
  34441. */
  34442. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34443. var options = {
  34444. shape: shape,
  34445. radius: radius,
  34446. tessellation: tessellation,
  34447. sideOrientation: sideOrientation,
  34448. updatable: updatable
  34449. };
  34450. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34451. };
  34452. /**
  34453. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  34454. * @param name defines the name of the mesh to create
  34455. * @param size sets the size (float) of both sides of the plane at once (default 1)
  34456. * @param scene defines the hosting scene
  34457. * @param updatable defines if the mesh must be flagged as updatable
  34458. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34459. * @returns a new Mesh
  34460. */
  34461. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34462. var options = {
  34463. size: size,
  34464. width: size,
  34465. height: size,
  34466. sideOrientation: sideOrientation,
  34467. updatable: updatable
  34468. };
  34469. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34470. };
  34471. /**
  34472. * Creates a ground mesh.
  34473. * Please consider using the same method from the MeshBuilder class instead
  34474. * @param name defines the name of the mesh to create
  34475. * @param width set the width of the ground
  34476. * @param height set the height of the ground
  34477. * @param subdivisions sets the number of subdivisions per side
  34478. * @param scene defines the hosting scene
  34479. * @param updatable defines if the mesh must be flagged as updatable
  34480. * @returns a new Mesh
  34481. */
  34482. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34483. var options = {
  34484. width: width,
  34485. height: height,
  34486. subdivisions: subdivisions,
  34487. updatable: updatable
  34488. };
  34489. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34490. };
  34491. /**
  34492. * Creates a tiled ground mesh.
  34493. * Please consider using the same method from the MeshBuilder class instead
  34494. * @param name defines the name of the mesh to create
  34495. * @param xmin set the ground minimum X coordinate
  34496. * @param zmin set the ground minimum Y coordinate
  34497. * @param xmax set the ground maximum X coordinate
  34498. * @param zmax set the ground maximum Z coordinate
  34499. * @param subdivisions is an 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
  34500. * @param precision is an 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
  34501. * @param scene defines the hosting scene
  34502. * @param updatable defines if the mesh must be flagged as updatable
  34503. * @returns a new Mesh
  34504. */
  34505. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34506. var options = {
  34507. xmin: xmin,
  34508. zmin: zmin,
  34509. xmax: xmax,
  34510. zmax: zmax,
  34511. subdivisions: subdivisions,
  34512. precision: precision,
  34513. updatable: updatable
  34514. };
  34515. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34516. };
  34517. /**
  34518. * Creates a ground mesh from a height map.
  34519. * Please consider using the same method from the MeshBuilder class instead
  34520. * @see http://doc.babylonjs.com/babylon101/height_map
  34521. * @param name defines the name of the mesh to create
  34522. * @param url sets the URL of the height map image resource
  34523. * @param width set the ground width size
  34524. * @param height set the ground height size
  34525. * @param subdivisions sets the number of subdivision per side
  34526. * @param minHeight is the minimum altitude on the ground
  34527. * @param maxHeight is the maximum altitude on the ground
  34528. * @param scene defines the hosting scene
  34529. * @param updatable defines if the mesh must be flagged as updatable
  34530. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  34531. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  34532. * @returns a new Mesh
  34533. */
  34534. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  34535. var options = {
  34536. width: width,
  34537. height: height,
  34538. subdivisions: subdivisions,
  34539. minHeight: minHeight,
  34540. maxHeight: maxHeight,
  34541. updatable: updatable,
  34542. onReady: onReady,
  34543. alphaFilter: alphaFilter
  34544. };
  34545. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34546. };
  34547. /**
  34548. * Creates a tube mesh.
  34549. * The tube is a parametric shape.
  34550. * It has no predefined shape. Its final shape will depend on the input parameters.
  34551. * Please consider using the same method from the MeshBuilder class instead
  34552. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34553. * @param name defines the name of the mesh to create
  34554. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  34555. * @param radius sets the tube radius size
  34556. * @param tessellation is the number of sides on the tubular surface
  34557. * @param radiusFunction is a custom function. If it is not null, it overwrittes the parameter `radius`. 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
  34558. * @param 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
  34559. * @param scene defines the hosting scene
  34560. * @param updatable defines if the mesh must be flagged as updatable
  34561. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34562. * @param instance is an instance of an existing Tube object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#tube)
  34563. * @returns a new Mesh
  34564. */
  34565. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34566. var options = {
  34567. path: path,
  34568. radius: radius,
  34569. tessellation: tessellation,
  34570. radiusFunction: radiusFunction,
  34571. arc: 1,
  34572. cap: cap,
  34573. updatable: updatable,
  34574. sideOrientation: sideOrientation,
  34575. instance: instance
  34576. };
  34577. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34578. };
  34579. /**
  34580. * Creates a polyhedron mesh.
  34581. * Please consider using the same method from the MeshBuilder class instead.
  34582. * * 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
  34583. * * The parameter `size` (positive float, default 1) sets the polygon size
  34584. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  34585. * * 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`
  34586. * * 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
  34587. * * 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)`)
  34588. * * 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
  34589. * * 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
  34590. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34591. * * 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
  34592. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  34593. * @param name defines the name of the mesh to create
  34594. * @param options defines the options used to create the mesh
  34595. * @param scene defines the hosting scene
  34596. * @returns a new Mesh
  34597. */
  34598. Mesh.CreatePolyhedron = function (name, options, scene) {
  34599. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34600. };
  34601. /**
  34602. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  34603. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  34604. * * 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`)
  34605. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  34606. * * 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
  34607. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34608. * * 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
  34609. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  34610. * @param name defines the name of the mesh
  34611. * @param options defines the options used to create the mesh
  34612. * @param scene defines the hosting scene
  34613. * @returns a new Mesh
  34614. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  34615. */
  34616. Mesh.CreateIcoSphere = function (name, options, scene) {
  34617. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34618. };
  34619. /**
  34620. * Creates a decal mesh.
  34621. * Please consider using the same method from the MeshBuilder class instead.
  34622. * A decal is a mesh usually applied as a model onto the surface of another mesh
  34623. * @param name defines the name of the mesh
  34624. * @param sourceMesh defines the mesh receiving the decal
  34625. * @param position sets the position of the decal in world coordinates
  34626. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  34627. * @param size sets the decal scaling
  34628. * @param angle sets the angle to rotate the decal
  34629. * @returns a new Mesh
  34630. */
  34631. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34632. var options = {
  34633. position: position,
  34634. normal: normal,
  34635. size: size,
  34636. angle: angle
  34637. };
  34638. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34639. };
  34640. // Skeletons
  34641. /**
  34642. * Prepare internal position array for software CPU skinning
  34643. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  34644. */
  34645. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34646. if (!this._sourcePositions) {
  34647. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34648. if (!source) {
  34649. return this._sourcePositions;
  34650. }
  34651. this._sourcePositions = new Float32Array(source);
  34652. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34653. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34654. }
  34655. }
  34656. return this._sourcePositions;
  34657. };
  34658. /**
  34659. * Prepare internal normal array for software CPU skinning
  34660. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34661. */
  34662. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34663. if (!this._sourceNormals) {
  34664. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34665. if (!source) {
  34666. return this._sourceNormals;
  34667. }
  34668. this._sourceNormals = new Float32Array(source);
  34669. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34670. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34671. }
  34672. }
  34673. return this._sourceNormals;
  34674. };
  34675. /**
  34676. * Updates the vertex buffer by applying transformation from the bones
  34677. * @param skeleton defines the skeleton to apply to current mesh
  34678. * @returns the current mesh
  34679. */
  34680. Mesh.prototype.applySkeleton = function (skeleton) {
  34681. if (!this.geometry) {
  34682. return this;
  34683. }
  34684. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  34685. return this;
  34686. }
  34687. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  34688. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34689. return this;
  34690. }
  34691. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34692. return this;
  34693. }
  34694. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34695. return this;
  34696. }
  34697. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34698. return this;
  34699. }
  34700. if (!this._sourcePositions) {
  34701. var submeshes = this.subMeshes.slice();
  34702. this.setPositionsForCPUSkinning();
  34703. this.subMeshes = submeshes;
  34704. }
  34705. if (!this._sourceNormals) {
  34706. this.setNormalsForCPUSkinning();
  34707. }
  34708. // positionsData checks for not being Float32Array will only pass at most once
  34709. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34710. if (!positionsData) {
  34711. return this;
  34712. }
  34713. if (!(positionsData instanceof Float32Array)) {
  34714. positionsData = new Float32Array(positionsData);
  34715. }
  34716. // normalsData checks for not being Float32Array will only pass at most once
  34717. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34718. if (!normalsData) {
  34719. return this;
  34720. }
  34721. if (!(normalsData instanceof Float32Array)) {
  34722. normalsData = new Float32Array(normalsData);
  34723. }
  34724. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34725. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34726. if (!matricesWeightsData || !matricesIndicesData) {
  34727. return this;
  34728. }
  34729. var needExtras = this.numBoneInfluencers > 4;
  34730. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34731. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34732. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34733. var tempVector3 = BABYLON.Vector3.Zero();
  34734. var finalMatrix = new BABYLON.Matrix();
  34735. var tempMatrix = new BABYLON.Matrix();
  34736. var matWeightIdx = 0;
  34737. var inf;
  34738. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34739. var weight;
  34740. for (inf = 0; inf < 4; inf++) {
  34741. weight = matricesWeightsData[matWeightIdx + inf];
  34742. if (weight > 0) {
  34743. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34744. finalMatrix.addToSelf(tempMatrix);
  34745. }
  34746. }
  34747. if (needExtras) {
  34748. for (inf = 0; inf < 4; inf++) {
  34749. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34750. if (weight > 0) {
  34751. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34752. finalMatrix.addToSelf(tempMatrix);
  34753. }
  34754. }
  34755. }
  34756. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34757. tempVector3.toArray(positionsData, index);
  34758. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34759. tempVector3.toArray(normalsData, index);
  34760. finalMatrix.reset();
  34761. }
  34762. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34763. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34764. return this;
  34765. };
  34766. // Tools
  34767. /**
  34768. * Returns an object containing a min and max Vector3 which are the minimum and maximum vectors of each mesh bounding box from the passed array, in the world coordinates
  34769. * @param meshes defines the list of meshes to scan
  34770. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  34771. */
  34772. Mesh.MinMax = function (meshes) {
  34773. var minVector = null;
  34774. var maxVector = null;
  34775. meshes.forEach(function (mesh, index, array) {
  34776. var boundingInfo = mesh.getBoundingInfo();
  34777. var boundingBox = boundingInfo.boundingBox;
  34778. if (!minVector || !maxVector) {
  34779. minVector = boundingBox.minimumWorld;
  34780. maxVector = boundingBox.maximumWorld;
  34781. }
  34782. else {
  34783. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34784. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34785. }
  34786. });
  34787. if (!minVector || !maxVector) {
  34788. return {
  34789. min: BABYLON.Vector3.Zero(),
  34790. max: BABYLON.Vector3.Zero()
  34791. };
  34792. }
  34793. return {
  34794. min: minVector,
  34795. max: maxVector
  34796. };
  34797. };
  34798. /**
  34799. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  34800. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  34801. * @returns a vector3
  34802. */
  34803. Mesh.Center = function (meshesOrMinMaxVector) {
  34804. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34805. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34806. };
  34807. /**
  34808. * Merge the array of meshes into a single mesh for performance reasons.
  34809. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  34810. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  34811. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  34812. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34813. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  34814. * @returns a new mesh
  34815. */
  34816. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34817. if (disposeSource === void 0) { disposeSource = true; }
  34818. var index;
  34819. if (!allow32BitsIndices) {
  34820. var totalVertices = 0;
  34821. // Counting vertices
  34822. for (index = 0; index < meshes.length; index++) {
  34823. if (meshes[index]) {
  34824. totalVertices += meshes[index].getTotalVertices();
  34825. if (totalVertices > 65536) {
  34826. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34827. return null;
  34828. }
  34829. }
  34830. }
  34831. }
  34832. // Merge
  34833. var vertexData = null;
  34834. var otherVertexData;
  34835. var indiceArray = new Array();
  34836. var source = null;
  34837. for (index = 0; index < meshes.length; index++) {
  34838. if (meshes[index]) {
  34839. var wm = meshes[index].computeWorldMatrix(true);
  34840. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34841. otherVertexData.transform(wm);
  34842. if (vertexData) {
  34843. vertexData.merge(otherVertexData, allow32BitsIndices);
  34844. }
  34845. else {
  34846. vertexData = otherVertexData;
  34847. source = meshes[index];
  34848. }
  34849. if (subdivideWithSubMeshes) {
  34850. indiceArray.push(meshes[index].getTotalIndices());
  34851. }
  34852. }
  34853. }
  34854. source = source;
  34855. if (!meshSubclass) {
  34856. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34857. }
  34858. vertexData.applyToMesh(meshSubclass);
  34859. // Setting properties
  34860. meshSubclass.material = source.material;
  34861. meshSubclass.checkCollisions = source.checkCollisions;
  34862. // Cleaning
  34863. if (disposeSource) {
  34864. for (index = 0; index < meshes.length; index++) {
  34865. if (meshes[index]) {
  34866. meshes[index].dispose();
  34867. }
  34868. }
  34869. }
  34870. // Subdivide
  34871. if (subdivideWithSubMeshes) {
  34872. //-- removal of global submesh
  34873. meshSubclass.releaseSubMeshes();
  34874. index = 0;
  34875. var offset = 0;
  34876. //-- apply subdivision according to index table
  34877. while (index < indiceArray.length) {
  34878. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34879. offset += indiceArray[index];
  34880. index++;
  34881. }
  34882. }
  34883. return meshSubclass;
  34884. };
  34885. // Consts
  34886. /**
  34887. * Mesh side orientation : usually the external or front surface
  34888. */
  34889. Mesh.FRONTSIDE = 0;
  34890. /**
  34891. * Mesh side orientation : usually the internal or back surface
  34892. */
  34893. Mesh.BACKSIDE = 1;
  34894. /**
  34895. * Mesh side orientation : both internal and external or front and back surfaces
  34896. */
  34897. Mesh.DOUBLESIDE = 2;
  34898. /**
  34899. * Mesh side orientation : by default, `FRONTSIDE`
  34900. */
  34901. Mesh.DEFAULTSIDE = 0;
  34902. /**
  34903. * Mesh cap setting : no cap
  34904. */
  34905. Mesh.NO_CAP = 0;
  34906. /**
  34907. * Mesh cap setting : one cap at the beginning of the mesh
  34908. */
  34909. Mesh.CAP_START = 1;
  34910. /**
  34911. * Mesh cap setting : one cap at the end of the mesh
  34912. */
  34913. Mesh.CAP_END = 2;
  34914. /**
  34915. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  34916. */
  34917. Mesh.CAP_ALL = 3;
  34918. return Mesh;
  34919. }(BABYLON.AbstractMesh));
  34920. BABYLON.Mesh = Mesh;
  34921. })(BABYLON || (BABYLON = {}));
  34922. //# sourceMappingURL=babylon.mesh.js.map
  34923. var BABYLON;
  34924. (function (BABYLON) {
  34925. /**
  34926. * Base class for submeshes
  34927. */
  34928. var BaseSubMesh = /** @class */ (function () {
  34929. function BaseSubMesh() {
  34930. }
  34931. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34932. /**
  34933. * Gets associated effect
  34934. */
  34935. get: function () {
  34936. return this._materialEffect;
  34937. },
  34938. enumerable: true,
  34939. configurable: true
  34940. });
  34941. /**
  34942. * Sets associated effect (effect used to render this submesh)
  34943. * @param effect defines the effect to associate with
  34944. * @param defines defines the set of defines used to compile this effect
  34945. */
  34946. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34947. if (defines === void 0) { defines = null; }
  34948. if (this._materialEffect === effect) {
  34949. if (!effect) {
  34950. this._materialDefines = null;
  34951. }
  34952. return;
  34953. }
  34954. this._materialDefines = defines;
  34955. this._materialEffect = effect;
  34956. };
  34957. return BaseSubMesh;
  34958. }());
  34959. BABYLON.BaseSubMesh = BaseSubMesh;
  34960. /**
  34961. * Defines a subdivision inside a mesh
  34962. */
  34963. var SubMesh = /** @class */ (function (_super) {
  34964. __extends(SubMesh, _super);
  34965. /**
  34966. * Creates a new submesh
  34967. * @param materialIndex defines the material index to use
  34968. * @param verticesStart defines vertex index start
  34969. * @param verticesCount defines vertices count
  34970. * @param indexStart defines index start
  34971. * @param indexCount defines indices count
  34972. * @param mesh defines the parent mesh
  34973. * @param renderingMesh defines an optional rendering mesh
  34974. * @param createBoundingBox defines if bounding box should be created for this submesh
  34975. */
  34976. function SubMesh(
  34977. /** the material index to use */
  34978. materialIndex,
  34979. /** vertex index start */
  34980. verticesStart,
  34981. /** vertices count */
  34982. verticesCount,
  34983. /** index start */
  34984. indexStart,
  34985. /** indices count */
  34986. indexCount, mesh, renderingMesh, createBoundingBox) {
  34987. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34988. var _this = _super.call(this) || this;
  34989. _this.materialIndex = materialIndex;
  34990. _this.verticesStart = verticesStart;
  34991. _this.verticesCount = verticesCount;
  34992. _this.indexStart = indexStart;
  34993. _this.indexCount = indexCount;
  34994. /** @hidden */
  34995. _this._renderId = 0;
  34996. _this._mesh = mesh;
  34997. _this._renderingMesh = renderingMesh || mesh;
  34998. mesh.subMeshes.push(_this);
  34999. _this._trianglePlanes = [];
  35000. _this._id = mesh.subMeshes.length - 1;
  35001. if (createBoundingBox) {
  35002. _this.refreshBoundingInfo();
  35003. mesh.computeWorldMatrix(true);
  35004. }
  35005. return _this;
  35006. }
  35007. /**
  35008. * Add a new submesh to a mesh
  35009. * @param materialIndex defines the material index to use
  35010. * @param verticesStart defines vertex index start
  35011. * @param verticesCount defines vertices count
  35012. * @param indexStart defines index start
  35013. * @param indexCount defines indices count
  35014. * @param mesh defines the parent mesh
  35015. * @param renderingMesh defines an optional rendering mesh
  35016. * @param createBoundingBox defines if bounding box should be created for this submesh
  35017. * @returns the new submesh
  35018. */
  35019. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  35020. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35021. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  35022. };
  35023. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  35024. /**
  35025. * Returns true if this submesh covers the entire parent mesh
  35026. * @ignorenaming
  35027. */
  35028. get: function () {
  35029. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  35030. },
  35031. enumerable: true,
  35032. configurable: true
  35033. });
  35034. /**
  35035. * Returns the submesh BoudingInfo object
  35036. * @returns current bounding info (or mesh's one if the submesh is global)
  35037. */
  35038. SubMesh.prototype.getBoundingInfo = function () {
  35039. if (this.IsGlobal) {
  35040. return this._mesh.getBoundingInfo();
  35041. }
  35042. return this._boundingInfo;
  35043. };
  35044. /**
  35045. * Sets the submesh BoundingInfo
  35046. * @param boundingInfo defines the new bounding info to use
  35047. * @returns the SubMesh
  35048. */
  35049. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  35050. this._boundingInfo = boundingInfo;
  35051. return this;
  35052. };
  35053. /**
  35054. * Returns the mesh of the current submesh
  35055. * @return the parent mesh
  35056. */
  35057. SubMesh.prototype.getMesh = function () {
  35058. return this._mesh;
  35059. };
  35060. /**
  35061. * Returns the rendering mesh of the submesh
  35062. * @returns the rendering mesh (could be different from parent mesh)
  35063. */
  35064. SubMesh.prototype.getRenderingMesh = function () {
  35065. return this._renderingMesh;
  35066. };
  35067. /**
  35068. * Returns the submesh material
  35069. * @returns null or the current material
  35070. */
  35071. SubMesh.prototype.getMaterial = function () {
  35072. var rootMaterial = this._renderingMesh.material;
  35073. if (rootMaterial === null || rootMaterial === undefined) {
  35074. return this._mesh.getScene().defaultMaterial;
  35075. }
  35076. else if (rootMaterial.getSubMaterial) {
  35077. var multiMaterial = rootMaterial;
  35078. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  35079. if (this._currentMaterial !== effectiveMaterial) {
  35080. this._currentMaterial = effectiveMaterial;
  35081. this._materialDefines = null;
  35082. }
  35083. return effectiveMaterial;
  35084. }
  35085. return rootMaterial;
  35086. };
  35087. // Methods
  35088. /**
  35089. * Sets a new updated BoundingInfo object to the submesh
  35090. * @returns the SubMesh
  35091. */
  35092. SubMesh.prototype.refreshBoundingInfo = function () {
  35093. this._lastColliderWorldVertices = null;
  35094. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  35095. return this;
  35096. }
  35097. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35098. if (!data) {
  35099. this._boundingInfo = this._mesh.getBoundingInfo();
  35100. return this;
  35101. }
  35102. var indices = this._renderingMesh.getIndices();
  35103. var extend;
  35104. //is this the only submesh?
  35105. if (this.indexStart === 0 && this.indexCount === indices.length) {
  35106. var boundingInfo = this._renderingMesh.getBoundingInfo();
  35107. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  35108. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  35109. }
  35110. else {
  35111. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  35112. }
  35113. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  35114. return this;
  35115. };
  35116. /** @hidden */
  35117. SubMesh.prototype._checkCollision = function (collider) {
  35118. var boundingInfo = this.getBoundingInfo();
  35119. return boundingInfo._checkCollision(collider);
  35120. };
  35121. /**
  35122. * Updates the submesh BoundingInfo
  35123. * @param world defines the world matrix to use to update the bounding info
  35124. * @returns the submesh
  35125. */
  35126. SubMesh.prototype.updateBoundingInfo = function (world) {
  35127. var boundingInfo = this.getBoundingInfo();
  35128. if (!boundingInfo) {
  35129. this.refreshBoundingInfo();
  35130. boundingInfo = this.getBoundingInfo();
  35131. }
  35132. boundingInfo.update(world);
  35133. return this;
  35134. };
  35135. /**
  35136. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  35137. * @param frustumPlanes defines the frustum planes
  35138. * @returns true if the submesh is intersecting with the frustum
  35139. */
  35140. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  35141. var boundingInfo = this.getBoundingInfo();
  35142. if (!boundingInfo) {
  35143. return false;
  35144. }
  35145. return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);
  35146. };
  35147. /**
  35148. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  35149. * @param frustumPlanes defines the frustum planes
  35150. * @returns true if the submesh is inside the frustum
  35151. */
  35152. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  35153. var boundingInfo = this.getBoundingInfo();
  35154. if (!boundingInfo) {
  35155. return false;
  35156. }
  35157. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  35158. };
  35159. /**
  35160. * Renders the submesh
  35161. * @param enableAlphaMode defines if alpha needs to be used
  35162. * @returns the submesh
  35163. */
  35164. SubMesh.prototype.render = function (enableAlphaMode) {
  35165. this._renderingMesh.render(this, enableAlphaMode);
  35166. return this;
  35167. };
  35168. /**
  35169. * @hidden
  35170. */
  35171. SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
  35172. if (!this._linesIndexBuffer) {
  35173. var linesIndices = [];
  35174. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35175. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  35176. }
  35177. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  35178. this._linesIndexCount = linesIndices.length;
  35179. }
  35180. return this._linesIndexBuffer;
  35181. };
  35182. /**
  35183. * Checks if the submesh intersects with a ray
  35184. * @param ray defines the ray to test
  35185. * @returns true is the passed ray intersects the submesh bounding box
  35186. */
  35187. SubMesh.prototype.canIntersects = function (ray) {
  35188. var boundingInfo = this.getBoundingInfo();
  35189. if (!boundingInfo) {
  35190. return false;
  35191. }
  35192. return ray.intersectsBox(boundingInfo.boundingBox);
  35193. };
  35194. /**
  35195. * Intersects current submesh with a ray
  35196. * @param ray defines the ray to test
  35197. * @param positions defines mesh's positions array
  35198. * @param indices defines mesh's indices array
  35199. * @param fastCheck defines if only bounding info should be used
  35200. * @returns intersection info or null if no intersection
  35201. */
  35202. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  35203. var intersectInfo = null;
  35204. var material = this.getMaterial();
  35205. if (!material) {
  35206. return null;
  35207. }
  35208. switch (material.fillMode) {
  35209. case BABYLON.Material.PointListDrawMode:
  35210. case BABYLON.Material.LineListDrawMode:
  35211. case BABYLON.Material.LineLoopDrawMode:
  35212. case BABYLON.Material.LineStripDrawMode:
  35213. case BABYLON.Material.TriangleFanDrawMode:
  35214. case BABYLON.Material.TriangleStripDrawMode:
  35215. return null;
  35216. }
  35217. // LineMesh first as it's also a Mesh...
  35218. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  35219. var lineMesh = this._mesh;
  35220. // Line test
  35221. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  35222. var p0 = positions[indices[index]];
  35223. var p1 = positions[indices[index + 1]];
  35224. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  35225. if (length < 0) {
  35226. continue;
  35227. }
  35228. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  35229. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  35230. if (fastCheck) {
  35231. break;
  35232. }
  35233. }
  35234. }
  35235. }
  35236. else {
  35237. // Triangles test
  35238. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35239. var p0 = positions[indices[index]];
  35240. var p1 = positions[indices[index + 1]];
  35241. var p2 = positions[indices[index + 2]];
  35242. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  35243. if (currentIntersectInfo) {
  35244. if (currentIntersectInfo.distance < 0) {
  35245. continue;
  35246. }
  35247. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  35248. intersectInfo = currentIntersectInfo;
  35249. intersectInfo.faceId = index / 3;
  35250. if (fastCheck) {
  35251. break;
  35252. }
  35253. }
  35254. }
  35255. }
  35256. }
  35257. return intersectInfo;
  35258. };
  35259. /** @hidden */
  35260. SubMesh.prototype._rebuild = function () {
  35261. if (this._linesIndexBuffer) {
  35262. this._linesIndexBuffer = null;
  35263. }
  35264. };
  35265. // Clone
  35266. /**
  35267. * Creates a new submesh from the passed mesh
  35268. * @param newMesh defines the new hosting mesh
  35269. * @param newRenderingMesh defines an optional rendering mesh
  35270. * @returns the new submesh
  35271. */
  35272. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  35273. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  35274. if (!this.IsGlobal) {
  35275. var boundingInfo = this.getBoundingInfo();
  35276. if (!boundingInfo) {
  35277. return result;
  35278. }
  35279. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  35280. }
  35281. return result;
  35282. };
  35283. // Dispose
  35284. /**
  35285. * Release associated resources
  35286. */
  35287. SubMesh.prototype.dispose = function () {
  35288. if (this._linesIndexBuffer) {
  35289. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  35290. this._linesIndexBuffer = null;
  35291. }
  35292. // Remove from mesh
  35293. var index = this._mesh.subMeshes.indexOf(this);
  35294. this._mesh.subMeshes.splice(index, 1);
  35295. };
  35296. // Statics
  35297. /**
  35298. * Creates a new submesh from indices data
  35299. * @param materialIndex the index of the main mesh material
  35300. * @param startIndex the index where to start the copy in the mesh indices array
  35301. * @param indexCount the number of indices to copy then from the startIndex
  35302. * @param mesh the main mesh to create the submesh from
  35303. * @param renderingMesh the optional rendering mesh
  35304. * @returns a new submesh
  35305. */
  35306. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  35307. var minVertexIndex = Number.MAX_VALUE;
  35308. var maxVertexIndex = -Number.MAX_VALUE;
  35309. renderingMesh = (renderingMesh || mesh);
  35310. var indices = renderingMesh.getIndices();
  35311. for (var index = startIndex; index < startIndex + indexCount; index++) {
  35312. var vertexIndex = indices[index];
  35313. if (vertexIndex < minVertexIndex)
  35314. minVertexIndex = vertexIndex;
  35315. if (vertexIndex > maxVertexIndex)
  35316. maxVertexIndex = vertexIndex;
  35317. }
  35318. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  35319. };
  35320. return SubMesh;
  35321. }(BaseSubMesh));
  35322. BABYLON.SubMesh = SubMesh;
  35323. })(BABYLON || (BABYLON = {}));
  35324. //# sourceMappingURL=babylon.subMesh.js.map
  35325. var __assign = (this && this.__assign) || function () {
  35326. __assign = Object.assign || function(t) {
  35327. for (var s, i = 1, n = arguments.length; i < n; i++) {
  35328. s = arguments[i];
  35329. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  35330. t[p] = s[p];
  35331. }
  35332. return t;
  35333. };
  35334. return __assign.apply(this, arguments);
  35335. };
  35336. var BABYLON;
  35337. (function (BABYLON) {
  35338. /**
  35339. * Manages the defines for the Material
  35340. */
  35341. var MaterialDefines = /** @class */ (function () {
  35342. function MaterialDefines() {
  35343. this._isDirty = true;
  35344. /** @hidden */
  35345. this._areLightsDirty = true;
  35346. /** @hidden */
  35347. this._areAttributesDirty = true;
  35348. /** @hidden */
  35349. this._areTexturesDirty = true;
  35350. /** @hidden */
  35351. this._areFresnelDirty = true;
  35352. /** @hidden */
  35353. this._areMiscDirty = true;
  35354. /** @hidden */
  35355. this._areImageProcessingDirty = true;
  35356. /** @hidden */
  35357. this._normals = false;
  35358. /** @hidden */
  35359. this._uvs = false;
  35360. /** @hidden */
  35361. this._needNormals = false;
  35362. /** @hidden */
  35363. this._needUVs = false;
  35364. }
  35365. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  35366. /**
  35367. * Specifies if the material needs to be re-calculated
  35368. */
  35369. get: function () {
  35370. return this._isDirty;
  35371. },
  35372. enumerable: true,
  35373. configurable: true
  35374. });
  35375. /**
  35376. * Marks the material to indicate that it has been re-calculated
  35377. */
  35378. MaterialDefines.prototype.markAsProcessed = function () {
  35379. this._isDirty = false;
  35380. this._areAttributesDirty = false;
  35381. this._areTexturesDirty = false;
  35382. this._areFresnelDirty = false;
  35383. this._areLightsDirty = false;
  35384. this._areMiscDirty = false;
  35385. this._areImageProcessingDirty = false;
  35386. };
  35387. /**
  35388. * Marks the material to indicate that it needs to be re-calculated
  35389. */
  35390. MaterialDefines.prototype.markAsUnprocessed = function () {
  35391. this._isDirty = true;
  35392. };
  35393. /**
  35394. * Marks the material to indicate all of its defines need to be re-calculated
  35395. */
  35396. MaterialDefines.prototype.markAllAsDirty = function () {
  35397. this._areTexturesDirty = true;
  35398. this._areAttributesDirty = true;
  35399. this._areLightsDirty = true;
  35400. this._areFresnelDirty = true;
  35401. this._areMiscDirty = true;
  35402. this._areImageProcessingDirty = true;
  35403. this._isDirty = true;
  35404. };
  35405. /**
  35406. * Marks the material to indicate that image processing needs to be re-calculated
  35407. */
  35408. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  35409. this._areImageProcessingDirty = true;
  35410. this._isDirty = true;
  35411. };
  35412. /**
  35413. * Marks the material to indicate the lights need to be re-calculated
  35414. */
  35415. MaterialDefines.prototype.markAsLightDirty = function () {
  35416. this._areLightsDirty = true;
  35417. this._isDirty = true;
  35418. };
  35419. /**
  35420. * Marks the attribute state as changed
  35421. */
  35422. MaterialDefines.prototype.markAsAttributesDirty = function () {
  35423. this._areAttributesDirty = true;
  35424. this._isDirty = true;
  35425. };
  35426. /**
  35427. * Marks the texture state as changed
  35428. */
  35429. MaterialDefines.prototype.markAsTexturesDirty = function () {
  35430. this._areTexturesDirty = true;
  35431. this._isDirty = true;
  35432. };
  35433. /**
  35434. * Marks the fresnel state as changed
  35435. */
  35436. MaterialDefines.prototype.markAsFresnelDirty = function () {
  35437. this._areFresnelDirty = true;
  35438. this._isDirty = true;
  35439. };
  35440. /**
  35441. * Marks the misc state as changed
  35442. */
  35443. MaterialDefines.prototype.markAsMiscDirty = function () {
  35444. this._areMiscDirty = true;
  35445. this._isDirty = true;
  35446. };
  35447. /**
  35448. * Rebuilds the material defines
  35449. */
  35450. MaterialDefines.prototype.rebuild = function () {
  35451. if (this._keys) {
  35452. delete this._keys;
  35453. }
  35454. this._keys = [];
  35455. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  35456. var key = _a[_i];
  35457. if (key[0] === "_") {
  35458. continue;
  35459. }
  35460. this._keys.push(key);
  35461. }
  35462. };
  35463. /**
  35464. * Specifies if two material defines are equal
  35465. * @param other - A material define instance to compare to
  35466. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  35467. */
  35468. MaterialDefines.prototype.isEqual = function (other) {
  35469. if (this._keys.length !== other._keys.length) {
  35470. return false;
  35471. }
  35472. for (var index = 0; index < this._keys.length; index++) {
  35473. var prop = this._keys[index];
  35474. if (this[prop] !== other[prop]) {
  35475. return false;
  35476. }
  35477. }
  35478. return true;
  35479. };
  35480. /**
  35481. * Clones this instance's defines to another instance
  35482. * @param other - material defines to clone values to
  35483. */
  35484. MaterialDefines.prototype.cloneTo = function (other) {
  35485. if (this._keys.length !== other._keys.length) {
  35486. other._keys = this._keys.slice(0);
  35487. }
  35488. for (var index = 0; index < this._keys.length; index++) {
  35489. var prop = this._keys[index];
  35490. other[prop] = this[prop];
  35491. }
  35492. };
  35493. /**
  35494. * Resets the material define values
  35495. */
  35496. MaterialDefines.prototype.reset = function () {
  35497. for (var index = 0; index < this._keys.length; index++) {
  35498. var prop = this._keys[index];
  35499. var type = typeof this[prop];
  35500. switch (type) {
  35501. case "number":
  35502. this[prop] = 0;
  35503. break;
  35504. case "string":
  35505. this[prop] = "";
  35506. break;
  35507. default:
  35508. this[prop] = false;
  35509. break;
  35510. }
  35511. }
  35512. };
  35513. /**
  35514. * Converts the material define values to a string
  35515. * @returns - String of material define information
  35516. */
  35517. MaterialDefines.prototype.toString = function () {
  35518. var result = "";
  35519. for (var index = 0; index < this._keys.length; index++) {
  35520. var prop = this._keys[index];
  35521. var value = this[prop];
  35522. var type = typeof value;
  35523. switch (type) {
  35524. case "number":
  35525. case "string":
  35526. result += "#define " + prop + " " + value + "\n";
  35527. break;
  35528. default:
  35529. if (value) {
  35530. result += "#define " + prop + "\n";
  35531. }
  35532. break;
  35533. }
  35534. }
  35535. return result;
  35536. };
  35537. return MaterialDefines;
  35538. }());
  35539. BABYLON.MaterialDefines = MaterialDefines;
  35540. /**
  35541. * Base class for the main features of a material in Babylon.js
  35542. */
  35543. var Material = /** @class */ (function () {
  35544. /**
  35545. * Creates a material instance
  35546. * @param name defines the name of the material
  35547. * @param scene defines the scene to reference
  35548. * @param doNotAdd specifies if the material should be added to the scene
  35549. */
  35550. function Material(name, scene, doNotAdd) {
  35551. /**
  35552. * Specifies if the ready state should be checked on each call
  35553. */
  35554. this.checkReadyOnEveryCall = false;
  35555. /**
  35556. * Specifies if the ready state should be checked once
  35557. */
  35558. this.checkReadyOnlyOnce = false;
  35559. /**
  35560. * The state of the material
  35561. */
  35562. this.state = "";
  35563. /**
  35564. * The alpha value of the material
  35565. */
  35566. this._alpha = 1.0;
  35567. /**
  35568. * Specifies if back face culling is enabled
  35569. */
  35570. this._backFaceCulling = true;
  35571. /**
  35572. * Specifies if the material should be serialized
  35573. */
  35574. this.doNotSerialize = false;
  35575. /**
  35576. * Specifies if the effect should be stored on sub meshes
  35577. */
  35578. this.storeEffectOnSubMeshes = false;
  35579. /**
  35580. * An event triggered when the material is disposed
  35581. */
  35582. this.onDisposeObservable = new BABYLON.Observable();
  35583. /**
  35584. * Stores the value of the alpha mode
  35585. */
  35586. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35587. /**
  35588. * Stores the state of the need depth pre-pass value
  35589. */
  35590. this._needDepthPrePass = false;
  35591. /**
  35592. * Specifies if depth writing should be disabled
  35593. */
  35594. this.disableDepthWrite = false;
  35595. /**
  35596. * Specifies if depth writing should be forced
  35597. */
  35598. this.forceDepthWrite = false;
  35599. /**
  35600. * Specifies if there should be a separate pass for culling
  35601. */
  35602. this.separateCullingPass = false;
  35603. /**
  35604. * Stores the state specifing if fog should be enabled
  35605. */
  35606. this._fogEnabled = true;
  35607. /**
  35608. * Stores the size of points
  35609. */
  35610. this.pointSize = 1.0;
  35611. /**
  35612. * Stores the z offset value
  35613. */
  35614. this.zOffset = 0;
  35615. /**
  35616. * @hidden
  35617. * Specifies if the material was previously ready
  35618. */
  35619. this._wasPreviouslyReady = false;
  35620. /**
  35621. * Stores the fill mode state
  35622. */
  35623. this._fillMode = Material.TriangleFillMode;
  35624. this.name = name;
  35625. this.id = name || BABYLON.Tools.RandomId();
  35626. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35627. this.uniqueId = this._scene.getUniqueId();
  35628. if (this._scene.useRightHandedSystem) {
  35629. this.sideOrientation = Material.ClockWiseSideOrientation;
  35630. }
  35631. else {
  35632. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35633. }
  35634. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35635. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35636. if (!doNotAdd) {
  35637. this._scene.materials.push(this);
  35638. this._scene.onNewMaterialAddedObservable.notifyObservers(this);
  35639. }
  35640. }
  35641. Object.defineProperty(Material, "TriangleFillMode", {
  35642. /**
  35643. * Returns the triangle fill mode
  35644. */
  35645. get: function () {
  35646. return Material._TriangleFillMode;
  35647. },
  35648. enumerable: true,
  35649. configurable: true
  35650. });
  35651. Object.defineProperty(Material, "WireFrameFillMode", {
  35652. /**
  35653. * Returns the wireframe mode
  35654. */
  35655. get: function () {
  35656. return Material._WireFrameFillMode;
  35657. },
  35658. enumerable: true,
  35659. configurable: true
  35660. });
  35661. Object.defineProperty(Material, "PointFillMode", {
  35662. /**
  35663. * Returns the point fill mode
  35664. */
  35665. get: function () {
  35666. return Material._PointFillMode;
  35667. },
  35668. enumerable: true,
  35669. configurable: true
  35670. });
  35671. Object.defineProperty(Material, "PointListDrawMode", {
  35672. /**
  35673. * Returns the point list draw mode
  35674. */
  35675. get: function () {
  35676. return Material._PointListDrawMode;
  35677. },
  35678. enumerable: true,
  35679. configurable: true
  35680. });
  35681. Object.defineProperty(Material, "LineListDrawMode", {
  35682. /**
  35683. * Returns the line list draw mode
  35684. */
  35685. get: function () {
  35686. return Material._LineListDrawMode;
  35687. },
  35688. enumerable: true,
  35689. configurable: true
  35690. });
  35691. Object.defineProperty(Material, "LineLoopDrawMode", {
  35692. /**
  35693. * Returns the line loop draw mode
  35694. */
  35695. get: function () {
  35696. return Material._LineLoopDrawMode;
  35697. },
  35698. enumerable: true,
  35699. configurable: true
  35700. });
  35701. Object.defineProperty(Material, "LineStripDrawMode", {
  35702. /**
  35703. * Returns the line strip draw mode
  35704. */
  35705. get: function () {
  35706. return Material._LineStripDrawMode;
  35707. },
  35708. enumerable: true,
  35709. configurable: true
  35710. });
  35711. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35712. /**
  35713. * Returns the triangle strip draw mode
  35714. */
  35715. get: function () {
  35716. return Material._TriangleStripDrawMode;
  35717. },
  35718. enumerable: true,
  35719. configurable: true
  35720. });
  35721. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35722. /**
  35723. * Returns the triangle fan draw mode
  35724. */
  35725. get: function () {
  35726. return Material._TriangleFanDrawMode;
  35727. },
  35728. enumerable: true,
  35729. configurable: true
  35730. });
  35731. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35732. /**
  35733. * Returns the clock-wise side orientation
  35734. */
  35735. get: function () {
  35736. return Material._ClockWiseSideOrientation;
  35737. },
  35738. enumerable: true,
  35739. configurable: true
  35740. });
  35741. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35742. /**
  35743. * Returns the counter clock-wise side orientation
  35744. */
  35745. get: function () {
  35746. return Material._CounterClockWiseSideOrientation;
  35747. },
  35748. enumerable: true,
  35749. configurable: true
  35750. });
  35751. Object.defineProperty(Material.prototype, "alpha", {
  35752. /**
  35753. * Gets the alpha value of the material
  35754. */
  35755. get: function () {
  35756. return this._alpha;
  35757. },
  35758. /**
  35759. * Sets the alpha value of the material
  35760. */
  35761. set: function (value) {
  35762. if (this._alpha === value) {
  35763. return;
  35764. }
  35765. this._alpha = value;
  35766. this.markAsDirty(Material.MiscDirtyFlag);
  35767. },
  35768. enumerable: true,
  35769. configurable: true
  35770. });
  35771. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35772. /**
  35773. * Gets the back-face culling state
  35774. */
  35775. get: function () {
  35776. return this._backFaceCulling;
  35777. },
  35778. /**
  35779. * Sets the back-face culling state
  35780. */
  35781. set: function (value) {
  35782. if (this._backFaceCulling === value) {
  35783. return;
  35784. }
  35785. this._backFaceCulling = value;
  35786. this.markAsDirty(Material.TextureDirtyFlag);
  35787. },
  35788. enumerable: true,
  35789. configurable: true
  35790. });
  35791. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  35792. /**
  35793. * Gets a boolean indicating that current material needs to register RTT
  35794. */
  35795. get: function () {
  35796. return false;
  35797. },
  35798. enumerable: true,
  35799. configurable: true
  35800. });
  35801. Object.defineProperty(Material.prototype, "onDispose", {
  35802. /**
  35803. * Called during a dispose event
  35804. */
  35805. set: function (callback) {
  35806. if (this._onDisposeObserver) {
  35807. this.onDisposeObservable.remove(this._onDisposeObserver);
  35808. }
  35809. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35810. },
  35811. enumerable: true,
  35812. configurable: true
  35813. });
  35814. Object.defineProperty(Material.prototype, "onBindObservable", {
  35815. /**
  35816. * An event triggered when the material is bound
  35817. */
  35818. get: function () {
  35819. if (!this._onBindObservable) {
  35820. this._onBindObservable = new BABYLON.Observable();
  35821. }
  35822. return this._onBindObservable;
  35823. },
  35824. enumerable: true,
  35825. configurable: true
  35826. });
  35827. Object.defineProperty(Material.prototype, "onBind", {
  35828. /**
  35829. * Called during a bind event
  35830. */
  35831. set: function (callback) {
  35832. if (this._onBindObserver) {
  35833. this.onBindObservable.remove(this._onBindObserver);
  35834. }
  35835. this._onBindObserver = this.onBindObservable.add(callback);
  35836. },
  35837. enumerable: true,
  35838. configurable: true
  35839. });
  35840. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  35841. /**
  35842. * An event triggered when the material is unbound
  35843. */
  35844. get: function () {
  35845. if (!this._onUnBindObservable) {
  35846. this._onUnBindObservable = new BABYLON.Observable();
  35847. }
  35848. return this._onUnBindObservable;
  35849. },
  35850. enumerable: true,
  35851. configurable: true
  35852. });
  35853. Object.defineProperty(Material.prototype, "alphaMode", {
  35854. /**
  35855. * Gets the value of the alpha mode
  35856. */
  35857. get: function () {
  35858. return this._alphaMode;
  35859. },
  35860. /**
  35861. * Sets the value of the alpha mode.
  35862. *
  35863. * | Value | Type | Description |
  35864. * | --- | --- | --- |
  35865. * | 0 | ALPHA_DISABLE | |
  35866. * | 1 | ALPHA_ADD | |
  35867. * | 2 | ALPHA_COMBINE | |
  35868. * | 3 | ALPHA_SUBTRACT | |
  35869. * | 4 | ALPHA_MULTIPLY | |
  35870. * | 5 | ALPHA_MAXIMIZED | |
  35871. * | 6 | ALPHA_ONEONE | |
  35872. * | 7 | ALPHA_PREMULTIPLIED | |
  35873. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35874. * | 9 | ALPHA_INTERPOLATE | |
  35875. * | 10 | ALPHA_SCREENMODE | |
  35876. *
  35877. */
  35878. set: function (value) {
  35879. if (this._alphaMode === value) {
  35880. return;
  35881. }
  35882. this._alphaMode = value;
  35883. this.markAsDirty(Material.TextureDirtyFlag);
  35884. },
  35885. enumerable: true,
  35886. configurable: true
  35887. });
  35888. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35889. /**
  35890. * Gets the depth pre-pass value
  35891. */
  35892. get: function () {
  35893. return this._needDepthPrePass;
  35894. },
  35895. /**
  35896. * Sets the need depth pre-pass value
  35897. */
  35898. set: function (value) {
  35899. if (this._needDepthPrePass === value) {
  35900. return;
  35901. }
  35902. this._needDepthPrePass = value;
  35903. if (this._needDepthPrePass) {
  35904. this.checkReadyOnEveryCall = true;
  35905. }
  35906. },
  35907. enumerable: true,
  35908. configurable: true
  35909. });
  35910. Object.defineProperty(Material.prototype, "fogEnabled", {
  35911. /**
  35912. * Gets the value of the fog enabled state
  35913. */
  35914. get: function () {
  35915. return this._fogEnabled;
  35916. },
  35917. /**
  35918. * Sets the state for enabling fog
  35919. */
  35920. set: function (value) {
  35921. if (this._fogEnabled === value) {
  35922. return;
  35923. }
  35924. this._fogEnabled = value;
  35925. this.markAsDirty(Material.MiscDirtyFlag);
  35926. },
  35927. enumerable: true,
  35928. configurable: true
  35929. });
  35930. Object.defineProperty(Material.prototype, "wireframe", {
  35931. /**
  35932. * Gets a value specifying if wireframe mode is enabled
  35933. */
  35934. get: function () {
  35935. switch (this._fillMode) {
  35936. case Material.WireFrameFillMode:
  35937. case Material.LineListDrawMode:
  35938. case Material.LineLoopDrawMode:
  35939. case Material.LineStripDrawMode:
  35940. return true;
  35941. }
  35942. return this._scene.forceWireframe;
  35943. },
  35944. /**
  35945. * Sets the state of wireframe mode
  35946. */
  35947. set: function (value) {
  35948. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35949. },
  35950. enumerable: true,
  35951. configurable: true
  35952. });
  35953. Object.defineProperty(Material.prototype, "pointsCloud", {
  35954. /**
  35955. * Gets the value specifying if point clouds are enabled
  35956. */
  35957. get: function () {
  35958. switch (this._fillMode) {
  35959. case Material.PointFillMode:
  35960. case Material.PointListDrawMode:
  35961. return true;
  35962. }
  35963. return this._scene.forcePointsCloud;
  35964. },
  35965. /**
  35966. * Sets the state of point cloud mode
  35967. */
  35968. set: function (value) {
  35969. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35970. },
  35971. enumerable: true,
  35972. configurable: true
  35973. });
  35974. Object.defineProperty(Material.prototype, "fillMode", {
  35975. /**
  35976. * Gets the material fill mode
  35977. */
  35978. get: function () {
  35979. return this._fillMode;
  35980. },
  35981. /**
  35982. * Sets the material fill mode
  35983. */
  35984. set: function (value) {
  35985. if (this._fillMode === value) {
  35986. return;
  35987. }
  35988. this._fillMode = value;
  35989. this.markAsDirty(Material.MiscDirtyFlag);
  35990. },
  35991. enumerable: true,
  35992. configurable: true
  35993. });
  35994. /**
  35995. * Returns a string representation of the current material
  35996. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35997. * @returns a string with material information
  35998. */
  35999. Material.prototype.toString = function (fullDetails) {
  36000. var ret = "Name: " + this.name;
  36001. if (fullDetails) {
  36002. }
  36003. return ret;
  36004. };
  36005. /**
  36006. * Gets the class name of the material
  36007. * @returns a string with the class name of the material
  36008. */
  36009. Material.prototype.getClassName = function () {
  36010. return "Material";
  36011. };
  36012. Object.defineProperty(Material.prototype, "isFrozen", {
  36013. /**
  36014. * Specifies if updates for the material been locked
  36015. */
  36016. get: function () {
  36017. return this.checkReadyOnlyOnce;
  36018. },
  36019. enumerable: true,
  36020. configurable: true
  36021. });
  36022. /**
  36023. * Locks updates for the material
  36024. */
  36025. Material.prototype.freeze = function () {
  36026. this.checkReadyOnlyOnce = true;
  36027. };
  36028. /**
  36029. * Unlocks updates for the material
  36030. */
  36031. Material.prototype.unfreeze = function () {
  36032. this.checkReadyOnlyOnce = false;
  36033. };
  36034. /**
  36035. * Specifies if the material is ready to be used
  36036. * @param mesh defines the mesh to check
  36037. * @param useInstances specifies if instances should be used
  36038. * @returns a boolean indicating if the material is ready to be used
  36039. */
  36040. Material.prototype.isReady = function (mesh, useInstances) {
  36041. return true;
  36042. };
  36043. /**
  36044. * Specifies that the submesh is ready to be used
  36045. * @param mesh defines the mesh to check
  36046. * @param subMesh defines which submesh to check
  36047. * @param useInstances specifies that instances should be used
  36048. * @returns a boolean indicating that the submesh is ready or not
  36049. */
  36050. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36051. return false;
  36052. };
  36053. /**
  36054. * Returns the material effect
  36055. * @returns the effect associated with the material
  36056. */
  36057. Material.prototype.getEffect = function () {
  36058. return this._effect;
  36059. };
  36060. /**
  36061. * Returns the current scene
  36062. * @returns a Scene
  36063. */
  36064. Material.prototype.getScene = function () {
  36065. return this._scene;
  36066. };
  36067. /**
  36068. * Specifies if the material will require alpha blending
  36069. * @returns a boolean specifying if alpha blending is needed
  36070. */
  36071. Material.prototype.needAlphaBlending = function () {
  36072. return (this.alpha < 1.0);
  36073. };
  36074. /**
  36075. * Specifies if the mesh will require alpha blending
  36076. * @param mesh defines the mesh to check
  36077. * @returns a boolean specifying if alpha blending is needed for the mesh
  36078. */
  36079. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  36080. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  36081. };
  36082. /**
  36083. * Specifies if this material should be rendered in alpha test mode
  36084. * @returns a boolean specifying if an alpha test is needed.
  36085. */
  36086. Material.prototype.needAlphaTesting = function () {
  36087. return false;
  36088. };
  36089. /**
  36090. * Gets the texture used for the alpha test
  36091. * @returns the texture to use for alpha testing
  36092. */
  36093. Material.prototype.getAlphaTestTexture = function () {
  36094. return null;
  36095. };
  36096. /**
  36097. * Marks the material to indicate that it needs to be re-calculated
  36098. */
  36099. Material.prototype.markDirty = function () {
  36100. this._wasPreviouslyReady = false;
  36101. };
  36102. /** @hidden */
  36103. Material.prototype._preBind = function (effect, overrideOrientation) {
  36104. if (overrideOrientation === void 0) { overrideOrientation = null; }
  36105. var engine = this._scene.getEngine();
  36106. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  36107. var reverse = orientation === Material.ClockWiseSideOrientation;
  36108. engine.enableEffect(effect ? effect : this._effect);
  36109. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  36110. return reverse;
  36111. };
  36112. /**
  36113. * Binds the material to the mesh
  36114. * @param world defines the world transformation matrix
  36115. * @param mesh defines the mesh to bind the material to
  36116. */
  36117. Material.prototype.bind = function (world, mesh) {
  36118. };
  36119. /**
  36120. * Binds the submesh to the material
  36121. * @param world defines the world transformation matrix
  36122. * @param mesh defines the mesh containing the submesh
  36123. * @param subMesh defines the submesh to bind the material to
  36124. */
  36125. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36126. };
  36127. /**
  36128. * Binds the world matrix to the material
  36129. * @param world defines the world transformation matrix
  36130. */
  36131. Material.prototype.bindOnlyWorldMatrix = function (world) {
  36132. };
  36133. /**
  36134. * Binds the scene's uniform buffer to the effect.
  36135. * @param effect defines the effect to bind to the scene uniform buffer
  36136. * @param sceneUbo defines the uniform buffer storing scene data
  36137. */
  36138. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  36139. sceneUbo.bindToEffect(effect, "Scene");
  36140. };
  36141. /**
  36142. * Binds the view matrix to the effect
  36143. * @param effect defines the effect to bind the view matrix to
  36144. */
  36145. Material.prototype.bindView = function (effect) {
  36146. if (!this._useUBO) {
  36147. effect.setMatrix("view", this.getScene().getViewMatrix());
  36148. }
  36149. else {
  36150. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36151. }
  36152. };
  36153. /**
  36154. * Binds the view projection matrix to the effect
  36155. * @param effect defines the effect to bind the view projection matrix to
  36156. */
  36157. Material.prototype.bindViewProjection = function (effect) {
  36158. if (!this._useUBO) {
  36159. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  36160. }
  36161. else {
  36162. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36163. }
  36164. };
  36165. /**
  36166. * Specifies if material alpha testing should be turned on for the mesh
  36167. * @param mesh defines the mesh to check
  36168. */
  36169. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  36170. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  36171. };
  36172. /**
  36173. * Processes to execute after binding the material to a mesh
  36174. * @param mesh defines the rendered mesh
  36175. */
  36176. Material.prototype._afterBind = function (mesh) {
  36177. this._scene._cachedMaterial = this;
  36178. if (mesh) {
  36179. this._scene._cachedVisibility = mesh.visibility;
  36180. }
  36181. else {
  36182. this._scene._cachedVisibility = 1;
  36183. }
  36184. if (this._onBindObservable && mesh) {
  36185. this._onBindObservable.notifyObservers(mesh);
  36186. }
  36187. if (this.disableDepthWrite) {
  36188. var engine = this._scene.getEngine();
  36189. this._cachedDepthWriteState = engine.getDepthWrite();
  36190. engine.setDepthWrite(false);
  36191. }
  36192. };
  36193. /**
  36194. * Unbinds the material from the mesh
  36195. */
  36196. Material.prototype.unbind = function () {
  36197. if (this._onUnBindObservable) {
  36198. this._onUnBindObservable.notifyObservers(this);
  36199. }
  36200. if (this.disableDepthWrite) {
  36201. var engine = this._scene.getEngine();
  36202. engine.setDepthWrite(this._cachedDepthWriteState);
  36203. }
  36204. };
  36205. /**
  36206. * Gets the active textures from the material
  36207. * @returns an array of textures
  36208. */
  36209. Material.prototype.getActiveTextures = function () {
  36210. return [];
  36211. };
  36212. /**
  36213. * Specifies if the material uses a texture
  36214. * @param texture defines the texture to check against the material
  36215. * @returns a boolean specifying if the material uses the texture
  36216. */
  36217. Material.prototype.hasTexture = function (texture) {
  36218. return false;
  36219. };
  36220. /**
  36221. * Makes a duplicate of the material, and gives it a new name
  36222. * @param name defines the new name for the duplicated material
  36223. * @returns the cloned material
  36224. */
  36225. Material.prototype.clone = function (name) {
  36226. return null;
  36227. };
  36228. /**
  36229. * Gets the meshes bound to the material
  36230. * @returns an array of meshes bound to the material
  36231. */
  36232. Material.prototype.getBindedMeshes = function () {
  36233. var result = new Array();
  36234. for (var index = 0; index < this._scene.meshes.length; index++) {
  36235. var mesh = this._scene.meshes[index];
  36236. if (mesh.material === this) {
  36237. result.push(mesh);
  36238. }
  36239. }
  36240. return result;
  36241. };
  36242. /**
  36243. * Force shader compilation
  36244. * @param mesh defines the mesh associated with this material
  36245. * @param onCompiled defines a function to execute once the material is compiled
  36246. * @param options defines the options to configure the compilation
  36247. */
  36248. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  36249. var _this = this;
  36250. var localOptions = __assign({ clipPlane: false }, options);
  36251. var subMesh = new BABYLON.BaseSubMesh();
  36252. var scene = this.getScene();
  36253. var checkReady = function () {
  36254. if (!_this._scene || !_this._scene.getEngine()) {
  36255. return;
  36256. }
  36257. if (subMesh._materialDefines) {
  36258. subMesh._materialDefines._renderId = -1;
  36259. }
  36260. var clipPlaneState = scene.clipPlane;
  36261. if (localOptions.clipPlane) {
  36262. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  36263. }
  36264. if (_this.storeEffectOnSubMeshes) {
  36265. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  36266. if (onCompiled) {
  36267. onCompiled(_this);
  36268. }
  36269. }
  36270. else {
  36271. setTimeout(checkReady, 16);
  36272. }
  36273. }
  36274. else {
  36275. if (_this.isReady(mesh)) {
  36276. if (onCompiled) {
  36277. onCompiled(_this);
  36278. }
  36279. }
  36280. else {
  36281. setTimeout(checkReady, 16);
  36282. }
  36283. }
  36284. if (localOptions.clipPlane) {
  36285. scene.clipPlane = clipPlaneState;
  36286. }
  36287. };
  36288. checkReady();
  36289. };
  36290. /**
  36291. * Force shader compilation
  36292. * @param mesh defines the mesh that will use this material
  36293. * @param options defines additional options for compiling the shaders
  36294. * @returns a promise that resolves when the compilation completes
  36295. */
  36296. Material.prototype.forceCompilationAsync = function (mesh, options) {
  36297. var _this = this;
  36298. return new Promise(function (resolve) {
  36299. _this.forceCompilation(mesh, function () {
  36300. resolve();
  36301. }, options);
  36302. });
  36303. };
  36304. /**
  36305. * Marks a define in the material to indicate that it needs to be re-computed
  36306. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  36307. */
  36308. Material.prototype.markAsDirty = function (flag) {
  36309. if (flag & Material.TextureDirtyFlag) {
  36310. this._markAllSubMeshesAsTexturesDirty();
  36311. }
  36312. if (flag & Material.LightDirtyFlag) {
  36313. this._markAllSubMeshesAsLightsDirty();
  36314. }
  36315. if (flag & Material.FresnelDirtyFlag) {
  36316. this._markAllSubMeshesAsFresnelDirty();
  36317. }
  36318. if (flag & Material.AttributesDirtyFlag) {
  36319. this._markAllSubMeshesAsAttributesDirty();
  36320. }
  36321. if (flag & Material.MiscDirtyFlag) {
  36322. this._markAllSubMeshesAsMiscDirty();
  36323. }
  36324. this.getScene().resetCachedMaterial();
  36325. };
  36326. /**
  36327. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  36328. * @param func defines a function which checks material defines against the submeshes
  36329. */
  36330. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  36331. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  36332. var mesh = _a[_i];
  36333. if (!mesh.subMeshes) {
  36334. continue;
  36335. }
  36336. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  36337. var subMesh = _c[_b];
  36338. if (subMesh.getMaterial() !== this) {
  36339. continue;
  36340. }
  36341. if (!subMesh._materialDefines) {
  36342. continue;
  36343. }
  36344. func(subMesh._materialDefines);
  36345. }
  36346. }
  36347. };
  36348. /**
  36349. * Indicates that image processing needs to be re-calculated for all submeshes
  36350. */
  36351. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  36352. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  36353. };
  36354. /**
  36355. * Indicates that textures need to be re-calculated for all submeshes
  36356. */
  36357. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  36358. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  36359. };
  36360. /**
  36361. * Indicates that fresnel needs to be re-calculated for all submeshes
  36362. */
  36363. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  36364. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  36365. };
  36366. /**
  36367. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  36368. */
  36369. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  36370. this._markAllSubMeshesAsDirty(function (defines) {
  36371. defines.markAsFresnelDirty();
  36372. defines.markAsMiscDirty();
  36373. });
  36374. };
  36375. /**
  36376. * Indicates that lights need to be re-calculated for all submeshes
  36377. */
  36378. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  36379. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  36380. };
  36381. /**
  36382. * Indicates that attributes need to be re-calculated for all submeshes
  36383. */
  36384. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  36385. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  36386. };
  36387. /**
  36388. * Indicates that misc needs to be re-calculated for all submeshes
  36389. */
  36390. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  36391. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  36392. };
  36393. /**
  36394. * Indicates that textures and misc need to be re-calculated for all submeshes
  36395. */
  36396. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  36397. this._markAllSubMeshesAsDirty(function (defines) {
  36398. defines.markAsTexturesDirty();
  36399. defines.markAsMiscDirty();
  36400. });
  36401. };
  36402. /**
  36403. * Disposes the material
  36404. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  36405. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  36406. */
  36407. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36408. // Animations
  36409. this.getScene().stopAnimation(this);
  36410. this.getScene().freeProcessedMaterials();
  36411. // Remove from scene
  36412. var index = this._scene.materials.indexOf(this);
  36413. if (index >= 0) {
  36414. this._scene.materials.splice(index, 1);
  36415. }
  36416. this._scene.onMaterialRemovedObservable.notifyObservers(this);
  36417. // Remove from meshes
  36418. for (index = 0; index < this._scene.meshes.length; index++) {
  36419. var mesh = this._scene.meshes[index];
  36420. if (mesh.material === this) {
  36421. mesh.material = null;
  36422. if (mesh.geometry) {
  36423. var geometry = (mesh.geometry);
  36424. if (this.storeEffectOnSubMeshes) {
  36425. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  36426. var subMesh = _a[_i];
  36427. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  36428. if (forceDisposeEffect && subMesh._materialEffect) {
  36429. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  36430. }
  36431. }
  36432. }
  36433. else {
  36434. geometry._releaseVertexArrayObject(this._effect);
  36435. }
  36436. }
  36437. }
  36438. }
  36439. this._uniformBuffer.dispose();
  36440. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  36441. if (forceDisposeEffect && this._effect) {
  36442. if (!this.storeEffectOnSubMeshes) {
  36443. this._scene.getEngine()._releaseEffect(this._effect);
  36444. }
  36445. this._effect = null;
  36446. }
  36447. // Callback
  36448. this.onDisposeObservable.notifyObservers(this);
  36449. this.onDisposeObservable.clear();
  36450. if (this._onBindObservable) {
  36451. this._onBindObservable.clear();
  36452. }
  36453. if (this._onUnBindObservable) {
  36454. this._onUnBindObservable.clear();
  36455. }
  36456. };
  36457. /**
  36458. * Serializes this material
  36459. * @returns the serialized material object
  36460. */
  36461. Material.prototype.serialize = function () {
  36462. return BABYLON.SerializationHelper.Serialize(this);
  36463. };
  36464. /**
  36465. * Creates a MultiMaterial from parsed MultiMaterial data.
  36466. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  36467. * @param scene defines the hosting scene
  36468. * @returns a new MultiMaterial
  36469. */
  36470. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  36471. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  36472. multiMaterial.id = parsedMultiMaterial.id;
  36473. if (BABYLON.Tags) {
  36474. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  36475. }
  36476. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  36477. var subMatId = parsedMultiMaterial.materials[matIndex];
  36478. if (subMatId) {
  36479. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  36480. }
  36481. else {
  36482. multiMaterial.subMaterials.push(null);
  36483. }
  36484. }
  36485. return multiMaterial;
  36486. };
  36487. /**
  36488. * Creates a material from parsed material data
  36489. * @param parsedMaterial defines parsed material data
  36490. * @param scene defines the hosting scene
  36491. * @param rootUrl defines the root URL to use to load textures
  36492. * @returns a new material
  36493. */
  36494. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  36495. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  36496. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  36497. }
  36498. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  36499. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  36500. if (!BABYLON.LegacyPBRMaterial) {
  36501. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  36502. return;
  36503. }
  36504. }
  36505. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  36506. return materialType.Parse(parsedMaterial, scene, rootUrl);
  36507. };
  36508. // Triangle views
  36509. Material._TriangleFillMode = 0;
  36510. Material._WireFrameFillMode = 1;
  36511. Material._PointFillMode = 2;
  36512. // Draw modes
  36513. Material._PointListDrawMode = 3;
  36514. Material._LineListDrawMode = 4;
  36515. Material._LineLoopDrawMode = 5;
  36516. Material._LineStripDrawMode = 6;
  36517. Material._TriangleStripDrawMode = 7;
  36518. Material._TriangleFanDrawMode = 8;
  36519. /**
  36520. * Stores the clock-wise side orientation
  36521. */
  36522. Material._ClockWiseSideOrientation = 0;
  36523. /**
  36524. * Stores the counter clock-wise side orientation
  36525. */
  36526. Material._CounterClockWiseSideOrientation = 1;
  36527. /**
  36528. * The dirty texture flag value
  36529. */
  36530. Material.TextureDirtyFlag = 1;
  36531. /**
  36532. * The dirty light flag value
  36533. */
  36534. Material.LightDirtyFlag = 2;
  36535. /**
  36536. * The dirty fresnel flag value
  36537. */
  36538. Material.FresnelDirtyFlag = 4;
  36539. /**
  36540. * The dirty attribute flag value
  36541. */
  36542. Material.AttributesDirtyFlag = 8;
  36543. /**
  36544. * The dirty misc flag value
  36545. */
  36546. Material.MiscDirtyFlag = 16;
  36547. /**
  36548. * The all dirty flag value
  36549. */
  36550. Material.AllDirtyFlag = 31;
  36551. __decorate([
  36552. BABYLON.serialize()
  36553. ], Material.prototype, "id", void 0);
  36554. __decorate([
  36555. BABYLON.serialize()
  36556. ], Material.prototype, "uniqueId", void 0);
  36557. __decorate([
  36558. BABYLON.serialize()
  36559. ], Material.prototype, "name", void 0);
  36560. __decorate([
  36561. BABYLON.serialize()
  36562. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36563. __decorate([
  36564. BABYLON.serialize()
  36565. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36566. __decorate([
  36567. BABYLON.serialize()
  36568. ], Material.prototype, "state", void 0);
  36569. __decorate([
  36570. BABYLON.serialize("alpha")
  36571. ], Material.prototype, "_alpha", void 0);
  36572. __decorate([
  36573. BABYLON.serialize("backFaceCulling")
  36574. ], Material.prototype, "_backFaceCulling", void 0);
  36575. __decorate([
  36576. BABYLON.serialize()
  36577. ], Material.prototype, "sideOrientation", void 0);
  36578. __decorate([
  36579. BABYLON.serialize("alphaMode")
  36580. ], Material.prototype, "_alphaMode", void 0);
  36581. __decorate([
  36582. BABYLON.serialize()
  36583. ], Material.prototype, "_needDepthPrePass", void 0);
  36584. __decorate([
  36585. BABYLON.serialize()
  36586. ], Material.prototype, "disableDepthWrite", void 0);
  36587. __decorate([
  36588. BABYLON.serialize()
  36589. ], Material.prototype, "forceDepthWrite", void 0);
  36590. __decorate([
  36591. BABYLON.serialize()
  36592. ], Material.prototype, "separateCullingPass", void 0);
  36593. __decorate([
  36594. BABYLON.serialize("fogEnabled")
  36595. ], Material.prototype, "_fogEnabled", void 0);
  36596. __decorate([
  36597. BABYLON.serialize()
  36598. ], Material.prototype, "pointSize", void 0);
  36599. __decorate([
  36600. BABYLON.serialize()
  36601. ], Material.prototype, "zOffset", void 0);
  36602. __decorate([
  36603. BABYLON.serialize()
  36604. ], Material.prototype, "wireframe", null);
  36605. __decorate([
  36606. BABYLON.serialize()
  36607. ], Material.prototype, "pointsCloud", null);
  36608. __decorate([
  36609. BABYLON.serialize()
  36610. ], Material.prototype, "fillMode", null);
  36611. return Material;
  36612. }());
  36613. BABYLON.Material = Material;
  36614. })(BABYLON || (BABYLON = {}));
  36615. //# sourceMappingURL=babylon.material.js.map
  36616. var BABYLON;
  36617. (function (BABYLON) {
  36618. /**
  36619. * Uniform buffer objects.
  36620. *
  36621. * Handles blocks of uniform on the GPU.
  36622. *
  36623. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36624. *
  36625. * For more information, please refer to :
  36626. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36627. */
  36628. var UniformBuffer = /** @class */ (function () {
  36629. /**
  36630. * Instantiates a new Uniform buffer objects.
  36631. *
  36632. * Handles blocks of uniform on the GPU.
  36633. *
  36634. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36635. *
  36636. * For more information, please refer to :
  36637. * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36638. * @param engine Define the engine the buffer is associated with
  36639. * @param data Define the data contained in the buffer
  36640. * @param dynamic Define if the buffer is updatable
  36641. */
  36642. function UniformBuffer(engine, data, dynamic) {
  36643. this._engine = engine;
  36644. this._noUBO = !engine.supportsUniformBuffers;
  36645. this._dynamic = dynamic;
  36646. this._data = data || [];
  36647. this._uniformLocations = {};
  36648. this._uniformSizes = {};
  36649. this._uniformLocationPointer = 0;
  36650. this._needSync = false;
  36651. if (this._noUBO) {
  36652. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36653. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36654. this.updateFloat = this._updateFloatForEffect;
  36655. this.updateFloat2 = this._updateFloat2ForEffect;
  36656. this.updateFloat3 = this._updateFloat3ForEffect;
  36657. this.updateFloat4 = this._updateFloat4ForEffect;
  36658. this.updateMatrix = this._updateMatrixForEffect;
  36659. this.updateVector3 = this._updateVector3ForEffect;
  36660. this.updateVector4 = this._updateVector4ForEffect;
  36661. this.updateColor3 = this._updateColor3ForEffect;
  36662. this.updateColor4 = this._updateColor4ForEffect;
  36663. }
  36664. else {
  36665. this._engine._uniformBuffers.push(this);
  36666. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36667. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36668. this.updateFloat = this._updateFloatForUniform;
  36669. this.updateFloat2 = this._updateFloat2ForUniform;
  36670. this.updateFloat3 = this._updateFloat3ForUniform;
  36671. this.updateFloat4 = this._updateFloat4ForUniform;
  36672. this.updateMatrix = this._updateMatrixForUniform;
  36673. this.updateVector3 = this._updateVector3ForUniform;
  36674. this.updateVector4 = this._updateVector4ForUniform;
  36675. this.updateColor3 = this._updateColor3ForUniform;
  36676. this.updateColor4 = this._updateColor4ForUniform;
  36677. }
  36678. }
  36679. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36680. /**
  36681. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36682. * or just falling back on setUniformXXX calls.
  36683. */
  36684. get: function () {
  36685. return !this._noUBO;
  36686. },
  36687. enumerable: true,
  36688. configurable: true
  36689. });
  36690. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36691. /**
  36692. * Indicates if the WebGL underlying uniform buffer is in sync
  36693. * with the javascript cache data.
  36694. */
  36695. get: function () {
  36696. return !this._needSync;
  36697. },
  36698. enumerable: true,
  36699. configurable: true
  36700. });
  36701. /**
  36702. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36703. * Also, a dynamic UniformBuffer will disable cache verification and always
  36704. * update the underlying WebGL uniform buffer to the GPU.
  36705. * @returns if Dynamic, otherwise false
  36706. */
  36707. UniformBuffer.prototype.isDynamic = function () {
  36708. return this._dynamic !== undefined;
  36709. };
  36710. /**
  36711. * The data cache on JS side.
  36712. * @returns the underlying data as a float array
  36713. */
  36714. UniformBuffer.prototype.getData = function () {
  36715. return this._bufferData;
  36716. };
  36717. /**
  36718. * The underlying WebGL Uniform buffer.
  36719. * @returns the webgl buffer
  36720. */
  36721. UniformBuffer.prototype.getBuffer = function () {
  36722. return this._buffer;
  36723. };
  36724. /**
  36725. * std140 layout specifies how to align data within an UBO structure.
  36726. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36727. * for specs.
  36728. */
  36729. UniformBuffer.prototype._fillAlignment = function (size) {
  36730. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36731. // and 4x4 matrices
  36732. // TODO : change if other types are used
  36733. var alignment;
  36734. if (size <= 2) {
  36735. alignment = size;
  36736. }
  36737. else {
  36738. alignment = 4;
  36739. }
  36740. if ((this._uniformLocationPointer % alignment) !== 0) {
  36741. var oldPointer = this._uniformLocationPointer;
  36742. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36743. var diff = this._uniformLocationPointer - oldPointer;
  36744. for (var i = 0; i < diff; i++) {
  36745. this._data.push(0);
  36746. }
  36747. }
  36748. };
  36749. /**
  36750. * Adds an uniform in the buffer.
  36751. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36752. * for the layout to be correct !
  36753. * @param name Name of the uniform, as used in the uniform block in the shader.
  36754. * @param size Data size, or data directly.
  36755. */
  36756. UniformBuffer.prototype.addUniform = function (name, size) {
  36757. if (this._noUBO) {
  36758. return;
  36759. }
  36760. if (this._uniformLocations[name] !== undefined) {
  36761. // Already existing uniform
  36762. return;
  36763. }
  36764. // This function must be called in the order of the shader layout !
  36765. // size can be the size of the uniform, or data directly
  36766. var data;
  36767. if (size instanceof Array) {
  36768. data = size;
  36769. size = data.length;
  36770. }
  36771. else {
  36772. size = size;
  36773. data = [];
  36774. // Fill with zeros
  36775. for (var i = 0; i < size; i++) {
  36776. data.push(0);
  36777. }
  36778. }
  36779. this._fillAlignment(size);
  36780. this._uniformSizes[name] = size;
  36781. this._uniformLocations[name] = this._uniformLocationPointer;
  36782. this._uniformLocationPointer += size;
  36783. for (var i = 0; i < size; i++) {
  36784. this._data.push(data[i]);
  36785. }
  36786. this._needSync = true;
  36787. };
  36788. /**
  36789. * Adds a Matrix 4x4 to the uniform buffer.
  36790. * @param name Name of the uniform, as used in the uniform block in the shader.
  36791. * @param mat A 4x4 matrix.
  36792. */
  36793. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36794. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36795. };
  36796. /**
  36797. * Adds a vec2 to the uniform buffer.
  36798. * @param name Name of the uniform, as used in the uniform block in the shader.
  36799. * @param x Define the x component value of the vec2
  36800. * @param y Define the y component value of the vec2
  36801. */
  36802. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36803. var temp = [x, y];
  36804. this.addUniform(name, temp);
  36805. };
  36806. /**
  36807. * Adds a vec3 to the uniform buffer.
  36808. * @param name Name of the uniform, as used in the uniform block in the shader.
  36809. * @param x Define the x component value of the vec3
  36810. * @param y Define the y component value of the vec3
  36811. * @param z Define the z component value of the vec3
  36812. */
  36813. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36814. var temp = [x, y, z];
  36815. this.addUniform(name, temp);
  36816. };
  36817. /**
  36818. * Adds a vec3 to the uniform buffer.
  36819. * @param name Name of the uniform, as used in the uniform block in the shader.
  36820. * @param color Define the vec3 from a Color
  36821. */
  36822. UniformBuffer.prototype.addColor3 = function (name, color) {
  36823. var temp = new Array();
  36824. color.toArray(temp);
  36825. this.addUniform(name, temp);
  36826. };
  36827. /**
  36828. * Adds a vec4 to the uniform buffer.
  36829. * @param name Name of the uniform, as used in the uniform block in the shader.
  36830. * @param color Define the rgb components from a Color
  36831. * @param alpha Define the a component of the vec4
  36832. */
  36833. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36834. var temp = new Array();
  36835. color.toArray(temp);
  36836. temp.push(alpha);
  36837. this.addUniform(name, temp);
  36838. };
  36839. /**
  36840. * Adds a vec3 to the uniform buffer.
  36841. * @param name Name of the uniform, as used in the uniform block in the shader.
  36842. * @param vector Define the vec3 components from a Vector
  36843. */
  36844. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36845. var temp = new Array();
  36846. vector.toArray(temp);
  36847. this.addUniform(name, temp);
  36848. };
  36849. /**
  36850. * Adds a Matrix 3x3 to the uniform buffer.
  36851. * @param name Name of the uniform, as used in the uniform block in the shader.
  36852. */
  36853. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36854. this.addUniform(name, 12);
  36855. };
  36856. /**
  36857. * Adds a Matrix 2x2 to the uniform buffer.
  36858. * @param name Name of the uniform, as used in the uniform block in the shader.
  36859. */
  36860. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36861. this.addUniform(name, 8);
  36862. };
  36863. /**
  36864. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36865. */
  36866. UniformBuffer.prototype.create = function () {
  36867. if (this._noUBO) {
  36868. return;
  36869. }
  36870. if (this._buffer) {
  36871. return; // nothing to do
  36872. }
  36873. // See spec, alignment must be filled as a vec4
  36874. this._fillAlignment(4);
  36875. this._bufferData = new Float32Array(this._data);
  36876. this._rebuild();
  36877. this._needSync = true;
  36878. };
  36879. /** @hidden */
  36880. UniformBuffer.prototype._rebuild = function () {
  36881. if (this._noUBO) {
  36882. return;
  36883. }
  36884. if (this._dynamic) {
  36885. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36886. }
  36887. else {
  36888. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36889. }
  36890. };
  36891. /**
  36892. * Updates the WebGL Uniform Buffer on the GPU.
  36893. * If the `dynamic` flag is set to true, no cache comparison is done.
  36894. * Otherwise, the buffer will be updated only if the cache differs.
  36895. */
  36896. UniformBuffer.prototype.update = function () {
  36897. if (!this._buffer) {
  36898. this.create();
  36899. return;
  36900. }
  36901. if (!this._dynamic && !this._needSync) {
  36902. return;
  36903. }
  36904. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36905. this._needSync = false;
  36906. };
  36907. /**
  36908. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36909. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  36910. * @param data Define the flattened data
  36911. * @param size Define the size of the data.
  36912. */
  36913. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36914. var location = this._uniformLocations[uniformName];
  36915. if (location === undefined) {
  36916. if (this._buffer) {
  36917. // Cannot add an uniform if the buffer is already created
  36918. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36919. return;
  36920. }
  36921. this.addUniform(uniformName, size);
  36922. location = this._uniformLocations[uniformName];
  36923. }
  36924. if (!this._buffer) {
  36925. this.create();
  36926. }
  36927. if (!this._dynamic) {
  36928. // Cache for static uniform buffers
  36929. var changed = false;
  36930. for (var i = 0; i < size; i++) {
  36931. if (this._bufferData[location + i] !== data[i]) {
  36932. changed = true;
  36933. this._bufferData[location + i] = data[i];
  36934. }
  36935. }
  36936. this._needSync = this._needSync || changed;
  36937. }
  36938. else {
  36939. // No cache for dynamic
  36940. for (var i = 0; i < size; i++) {
  36941. this._bufferData[location + i] = data[i];
  36942. }
  36943. }
  36944. };
  36945. // Update methods
  36946. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36947. // To match std140, matrix must be realigned
  36948. for (var i = 0; i < 3; i++) {
  36949. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36950. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36951. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36952. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36953. }
  36954. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36955. };
  36956. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36957. this._currentEffect.setMatrix3x3(name, matrix);
  36958. };
  36959. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36960. this._currentEffect.setMatrix2x2(name, matrix);
  36961. };
  36962. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36963. // To match std140, matrix must be realigned
  36964. for (var i = 0; i < 2; i++) {
  36965. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36966. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36967. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36968. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36969. }
  36970. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36971. };
  36972. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36973. this._currentEffect.setFloat(name, x);
  36974. };
  36975. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36976. UniformBuffer._tempBuffer[0] = x;
  36977. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36978. };
  36979. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36980. if (suffix === void 0) { suffix = ""; }
  36981. this._currentEffect.setFloat2(name + suffix, x, y);
  36982. };
  36983. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36984. if (suffix === void 0) { suffix = ""; }
  36985. UniformBuffer._tempBuffer[0] = x;
  36986. UniformBuffer._tempBuffer[1] = y;
  36987. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36988. };
  36989. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36990. if (suffix === void 0) { suffix = ""; }
  36991. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36992. };
  36993. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36994. if (suffix === void 0) { suffix = ""; }
  36995. UniformBuffer._tempBuffer[0] = x;
  36996. UniformBuffer._tempBuffer[1] = y;
  36997. UniformBuffer._tempBuffer[2] = z;
  36998. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36999. };
  37000. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  37001. if (suffix === void 0) { suffix = ""; }
  37002. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  37003. };
  37004. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  37005. if (suffix === void 0) { suffix = ""; }
  37006. UniformBuffer._tempBuffer[0] = x;
  37007. UniformBuffer._tempBuffer[1] = y;
  37008. UniformBuffer._tempBuffer[2] = z;
  37009. UniformBuffer._tempBuffer[3] = w;
  37010. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37011. };
  37012. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  37013. this._currentEffect.setMatrix(name, mat);
  37014. };
  37015. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  37016. this.updateUniform(name, mat.toArray(), 16);
  37017. };
  37018. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  37019. this._currentEffect.setVector3(name, vector);
  37020. };
  37021. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  37022. vector.toArray(UniformBuffer._tempBuffer);
  37023. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37024. };
  37025. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  37026. this._currentEffect.setVector4(name, vector);
  37027. };
  37028. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  37029. vector.toArray(UniformBuffer._tempBuffer);
  37030. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37031. };
  37032. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  37033. if (suffix === void 0) { suffix = ""; }
  37034. this._currentEffect.setColor3(name + suffix, color);
  37035. };
  37036. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  37037. if (suffix === void 0) { suffix = ""; }
  37038. color.toArray(UniformBuffer._tempBuffer);
  37039. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37040. };
  37041. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  37042. if (suffix === void 0) { suffix = ""; }
  37043. this._currentEffect.setColor4(name + suffix, color, alpha);
  37044. };
  37045. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  37046. if (suffix === void 0) { suffix = ""; }
  37047. color.toArray(UniformBuffer._tempBuffer);
  37048. UniformBuffer._tempBuffer[3] = alpha;
  37049. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37050. };
  37051. /**
  37052. * Sets a sampler uniform on the effect.
  37053. * @param name Define the name of the sampler.
  37054. * @param texture Define the texture to set in the sampler
  37055. */
  37056. UniformBuffer.prototype.setTexture = function (name, texture) {
  37057. this._currentEffect.setTexture(name, texture);
  37058. };
  37059. /**
  37060. * Directly updates the value of the uniform in the cache AND on the GPU.
  37061. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37062. * @param data Define the flattened data
  37063. */
  37064. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  37065. this.updateUniform(uniformName, data, data.length);
  37066. this.update();
  37067. };
  37068. /**
  37069. * Binds this uniform buffer to an effect.
  37070. * @param effect Define the effect to bind the buffer to
  37071. * @param name Name of the uniform block in the shader.
  37072. */
  37073. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  37074. this._currentEffect = effect;
  37075. if (this._noUBO || !this._buffer) {
  37076. return;
  37077. }
  37078. effect.bindUniformBuffer(this._buffer, name);
  37079. };
  37080. /**
  37081. * Disposes the uniform buffer.
  37082. */
  37083. UniformBuffer.prototype.dispose = function () {
  37084. if (this._noUBO) {
  37085. return;
  37086. }
  37087. var index = this._engine._uniformBuffers.indexOf(this);
  37088. if (index !== -1) {
  37089. this._engine._uniformBuffers.splice(index, 1);
  37090. }
  37091. if (!this._buffer) {
  37092. return;
  37093. }
  37094. if (this._engine._releaseBuffer(this._buffer)) {
  37095. this._buffer = null;
  37096. }
  37097. };
  37098. // Pool for avoiding memory leaks
  37099. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  37100. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  37101. return UniformBuffer;
  37102. }());
  37103. BABYLON.UniformBuffer = UniformBuffer;
  37104. })(BABYLON || (BABYLON = {}));
  37105. //# sourceMappingURL=babylon.uniformBuffer.js.map
  37106. var BABYLON;
  37107. (function (BABYLON) {
  37108. /**
  37109. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  37110. */
  37111. var VertexData = /** @class */ (function () {
  37112. function VertexData() {
  37113. }
  37114. /**
  37115. * Uses the passed data array to set the set the values for the specified kind of data
  37116. * @param data a linear array of floating numbers
  37117. * @param kind the type of data that is being set, eg positions, colors etc
  37118. */
  37119. VertexData.prototype.set = function (data, kind) {
  37120. switch (kind) {
  37121. case BABYLON.VertexBuffer.PositionKind:
  37122. this.positions = data;
  37123. break;
  37124. case BABYLON.VertexBuffer.NormalKind:
  37125. this.normals = data;
  37126. break;
  37127. case BABYLON.VertexBuffer.TangentKind:
  37128. this.tangents = data;
  37129. break;
  37130. case BABYLON.VertexBuffer.UVKind:
  37131. this.uvs = data;
  37132. break;
  37133. case BABYLON.VertexBuffer.UV2Kind:
  37134. this.uvs2 = data;
  37135. break;
  37136. case BABYLON.VertexBuffer.UV3Kind:
  37137. this.uvs3 = data;
  37138. break;
  37139. case BABYLON.VertexBuffer.UV4Kind:
  37140. this.uvs4 = data;
  37141. break;
  37142. case BABYLON.VertexBuffer.UV5Kind:
  37143. this.uvs5 = data;
  37144. break;
  37145. case BABYLON.VertexBuffer.UV6Kind:
  37146. this.uvs6 = data;
  37147. break;
  37148. case BABYLON.VertexBuffer.ColorKind:
  37149. this.colors = data;
  37150. break;
  37151. case BABYLON.VertexBuffer.MatricesIndicesKind:
  37152. this.matricesIndices = data;
  37153. break;
  37154. case BABYLON.VertexBuffer.MatricesWeightsKind:
  37155. this.matricesWeights = data;
  37156. break;
  37157. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  37158. this.matricesIndicesExtra = data;
  37159. break;
  37160. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  37161. this.matricesWeightsExtra = data;
  37162. break;
  37163. }
  37164. };
  37165. /**
  37166. * Associates the vertexData to the passed Mesh.
  37167. * Sets it as updatable or not (default `false`)
  37168. * @param mesh the mesh the vertexData is applied to
  37169. * @param updatable when used and having the value true allows new data to update the vertexData
  37170. * @returns the VertexData
  37171. */
  37172. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  37173. this._applyTo(mesh, updatable);
  37174. return this;
  37175. };
  37176. /**
  37177. * Associates the vertexData to the passed Geometry.
  37178. * Sets it as updatable or not (default `false`)
  37179. * @param geometry the geometry the vertexData is applied to
  37180. * @param updatable when used and having the value true allows new data to update the vertexData
  37181. * @returns VertexData
  37182. */
  37183. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  37184. this._applyTo(geometry, updatable);
  37185. return this;
  37186. };
  37187. /**
  37188. * Updates the associated mesh
  37189. * @param mesh the mesh to be updated
  37190. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37191. * @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
  37192. * @returns VertexData
  37193. */
  37194. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  37195. this._update(mesh);
  37196. return this;
  37197. };
  37198. /**
  37199. * Updates the associated geometry
  37200. * @param geometry the geometry to be updated
  37201. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37202. * @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
  37203. * @returns VertexData.
  37204. */
  37205. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  37206. this._update(geometry);
  37207. return this;
  37208. };
  37209. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  37210. if (updatable === void 0) { updatable = false; }
  37211. if (this.positions) {
  37212. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  37213. }
  37214. if (this.normals) {
  37215. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  37216. }
  37217. if (this.tangents) {
  37218. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  37219. }
  37220. if (this.uvs) {
  37221. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  37222. }
  37223. if (this.uvs2) {
  37224. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  37225. }
  37226. if (this.uvs3) {
  37227. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  37228. }
  37229. if (this.uvs4) {
  37230. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  37231. }
  37232. if (this.uvs5) {
  37233. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  37234. }
  37235. if (this.uvs6) {
  37236. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  37237. }
  37238. if (this.colors) {
  37239. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  37240. }
  37241. if (this.matricesIndices) {
  37242. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  37243. }
  37244. if (this.matricesWeights) {
  37245. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  37246. }
  37247. if (this.matricesIndicesExtra) {
  37248. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  37249. }
  37250. if (this.matricesWeightsExtra) {
  37251. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  37252. }
  37253. if (this.indices) {
  37254. meshOrGeometry.setIndices(this.indices, null, updatable);
  37255. }
  37256. else {
  37257. meshOrGeometry.setIndices([], null);
  37258. }
  37259. return this;
  37260. };
  37261. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  37262. if (this.positions) {
  37263. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  37264. }
  37265. if (this.normals) {
  37266. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  37267. }
  37268. if (this.tangents) {
  37269. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  37270. }
  37271. if (this.uvs) {
  37272. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  37273. }
  37274. if (this.uvs2) {
  37275. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  37276. }
  37277. if (this.uvs3) {
  37278. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  37279. }
  37280. if (this.uvs4) {
  37281. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  37282. }
  37283. if (this.uvs5) {
  37284. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  37285. }
  37286. if (this.uvs6) {
  37287. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  37288. }
  37289. if (this.colors) {
  37290. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  37291. }
  37292. if (this.matricesIndices) {
  37293. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  37294. }
  37295. if (this.matricesWeights) {
  37296. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  37297. }
  37298. if (this.matricesIndicesExtra) {
  37299. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  37300. }
  37301. if (this.matricesWeightsExtra) {
  37302. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  37303. }
  37304. if (this.indices) {
  37305. meshOrGeometry.setIndices(this.indices, null);
  37306. }
  37307. return this;
  37308. };
  37309. /**
  37310. * Transforms each position and each normal of the vertexData according to the passed Matrix
  37311. * @param matrix the transforming matrix
  37312. * @returns the VertexData
  37313. */
  37314. VertexData.prototype.transform = function (matrix) {
  37315. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  37316. var transformed = BABYLON.Vector3.Zero();
  37317. var index;
  37318. if (this.positions) {
  37319. var position = BABYLON.Vector3.Zero();
  37320. for (index = 0; index < this.positions.length; index += 3) {
  37321. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  37322. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  37323. this.positions[index] = transformed.x;
  37324. this.positions[index + 1] = transformed.y;
  37325. this.positions[index + 2] = transformed.z;
  37326. }
  37327. }
  37328. if (this.normals) {
  37329. var normal = BABYLON.Vector3.Zero();
  37330. for (index = 0; index < this.normals.length; index += 3) {
  37331. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  37332. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  37333. this.normals[index] = transformed.x;
  37334. this.normals[index + 1] = transformed.y;
  37335. this.normals[index + 2] = transformed.z;
  37336. }
  37337. }
  37338. if (this.tangents) {
  37339. var tangent = BABYLON.Vector4.Zero();
  37340. var tangentTransformed = BABYLON.Vector4.Zero();
  37341. for (index = 0; index < this.tangents.length; index += 4) {
  37342. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  37343. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  37344. this.tangents[index] = tangentTransformed.x;
  37345. this.tangents[index + 1] = tangentTransformed.y;
  37346. this.tangents[index + 2] = tangentTransformed.z;
  37347. this.tangents[index + 3] = tangentTransformed.w;
  37348. }
  37349. }
  37350. if (flip && this.indices) {
  37351. for (index = 0; index < this.indices.length; index += 3) {
  37352. var tmp = this.indices[index + 1];
  37353. this.indices[index + 1] = this.indices[index + 2];
  37354. this.indices[index + 2] = tmp;
  37355. }
  37356. }
  37357. return this;
  37358. };
  37359. /**
  37360. * Merges the passed VertexData into the current one
  37361. * @param other the VertexData to be merged into the current one
  37362. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  37363. * @returns the modified VertexData
  37364. */
  37365. VertexData.prototype.merge = function (other, use32BitsIndices) {
  37366. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  37367. this._validate();
  37368. other._validate();
  37369. if (!this.normals !== !other.normals ||
  37370. !this.tangents !== !other.tangents ||
  37371. !this.uvs !== !other.uvs ||
  37372. !this.uvs2 !== !other.uvs2 ||
  37373. !this.uvs3 !== !other.uvs3 ||
  37374. !this.uvs4 !== !other.uvs4 ||
  37375. !this.uvs5 !== !other.uvs5 ||
  37376. !this.uvs6 !== !other.uvs6 ||
  37377. !this.colors !== !other.colors ||
  37378. !this.matricesIndices !== !other.matricesIndices ||
  37379. !this.matricesWeights !== !other.matricesWeights ||
  37380. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  37381. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  37382. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  37383. }
  37384. if (other.indices) {
  37385. if (!this.indices) {
  37386. this.indices = [];
  37387. }
  37388. var offset = this.positions ? this.positions.length / 3 : 0;
  37389. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  37390. if (isSrcTypedArray) {
  37391. var len = this.indices.length + other.indices.length;
  37392. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  37393. temp.set(this.indices);
  37394. var decal = this.indices.length;
  37395. for (var index = 0; index < other.indices.length; index++) {
  37396. temp[decal + index] = other.indices[index] + offset;
  37397. }
  37398. this.indices = temp;
  37399. }
  37400. else {
  37401. for (var index = 0; index < other.indices.length; index++) {
  37402. this.indices.push(other.indices[index] + offset);
  37403. }
  37404. }
  37405. }
  37406. this.positions = this._mergeElement(this.positions, other.positions);
  37407. this.normals = this._mergeElement(this.normals, other.normals);
  37408. this.tangents = this._mergeElement(this.tangents, other.tangents);
  37409. this.uvs = this._mergeElement(this.uvs, other.uvs);
  37410. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  37411. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  37412. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  37413. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  37414. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  37415. this.colors = this._mergeElement(this.colors, other.colors);
  37416. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  37417. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  37418. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  37419. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  37420. return this;
  37421. };
  37422. VertexData.prototype._mergeElement = function (source, other) {
  37423. if (!source) {
  37424. return other;
  37425. }
  37426. if (!other) {
  37427. return source;
  37428. }
  37429. var len = other.length + source.length;
  37430. var isSrcTypedArray = source instanceof Float32Array;
  37431. var isOthTypedArray = other instanceof Float32Array;
  37432. // use non-loop method when the source is Float32Array
  37433. if (isSrcTypedArray) {
  37434. var ret32 = new Float32Array(len);
  37435. ret32.set(source);
  37436. ret32.set(other, source.length);
  37437. return ret32;
  37438. // source is number[], when other is also use concat
  37439. }
  37440. else if (!isOthTypedArray) {
  37441. return source.concat(other);
  37442. // source is a number[], but other is a Float32Array, loop required
  37443. }
  37444. else {
  37445. var ret = source.slice(0); // copy source to a separate array
  37446. for (var i = 0, len = other.length; i < len; i++) {
  37447. ret.push(other[i]);
  37448. }
  37449. return ret;
  37450. }
  37451. };
  37452. VertexData.prototype._validate = function () {
  37453. if (!this.positions) {
  37454. throw new Error("Positions are required");
  37455. }
  37456. var getElementCount = function (kind, values) {
  37457. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  37458. if ((values.length % stride) !== 0) {
  37459. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  37460. }
  37461. return values.length / stride;
  37462. };
  37463. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  37464. var validateElementCount = function (kind, values) {
  37465. var elementCount = getElementCount(kind, values);
  37466. if (elementCount !== positionsElementCount) {
  37467. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  37468. }
  37469. };
  37470. if (this.normals)
  37471. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  37472. if (this.tangents)
  37473. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  37474. if (this.uvs)
  37475. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  37476. if (this.uvs2)
  37477. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  37478. if (this.uvs3)
  37479. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  37480. if (this.uvs4)
  37481. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  37482. if (this.uvs5)
  37483. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  37484. if (this.uvs6)
  37485. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  37486. if (this.colors)
  37487. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  37488. if (this.matricesIndices)
  37489. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  37490. if (this.matricesWeights)
  37491. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  37492. if (this.matricesIndicesExtra)
  37493. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  37494. if (this.matricesWeightsExtra)
  37495. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  37496. };
  37497. /**
  37498. * Serializes the VertexData
  37499. * @returns a serialized object
  37500. */
  37501. VertexData.prototype.serialize = function () {
  37502. var serializationObject = this.serialize();
  37503. if (this.positions) {
  37504. serializationObject.positions = this.positions;
  37505. }
  37506. if (this.normals) {
  37507. serializationObject.normals = this.normals;
  37508. }
  37509. if (this.tangents) {
  37510. serializationObject.tangents = this.tangents;
  37511. }
  37512. if (this.uvs) {
  37513. serializationObject.uvs = this.uvs;
  37514. }
  37515. if (this.uvs2) {
  37516. serializationObject.uvs2 = this.uvs2;
  37517. }
  37518. if (this.uvs3) {
  37519. serializationObject.uvs3 = this.uvs3;
  37520. }
  37521. if (this.uvs4) {
  37522. serializationObject.uvs4 = this.uvs4;
  37523. }
  37524. if (this.uvs5) {
  37525. serializationObject.uvs5 = this.uvs5;
  37526. }
  37527. if (this.uvs6) {
  37528. serializationObject.uvs6 = this.uvs6;
  37529. }
  37530. if (this.colors) {
  37531. serializationObject.colors = this.colors;
  37532. }
  37533. if (this.matricesIndices) {
  37534. serializationObject.matricesIndices = this.matricesIndices;
  37535. serializationObject.matricesIndices._isExpanded = true;
  37536. }
  37537. if (this.matricesWeights) {
  37538. serializationObject.matricesWeights = this.matricesWeights;
  37539. }
  37540. if (this.matricesIndicesExtra) {
  37541. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37542. serializationObject.matricesIndicesExtra._isExpanded = true;
  37543. }
  37544. if (this.matricesWeightsExtra) {
  37545. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37546. }
  37547. serializationObject.indices = this.indices;
  37548. return serializationObject;
  37549. };
  37550. // Statics
  37551. /**
  37552. * Extracts the vertexData from a mesh
  37553. * @param mesh the mesh from which to extract the VertexData
  37554. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  37555. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37556. * @returns the object VertexData associated to the passed mesh
  37557. */
  37558. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37559. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37560. };
  37561. /**
  37562. * Extracts the vertexData from the geometry
  37563. * @param geometry the geometry from which to extract the VertexData
  37564. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37565. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37566. * @returns the object VertexData associated to the passed mesh
  37567. */
  37568. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37569. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37570. };
  37571. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37572. var result = new VertexData();
  37573. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37574. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37575. }
  37576. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37577. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37578. }
  37579. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37580. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37581. }
  37582. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37583. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37584. }
  37585. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37586. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37587. }
  37588. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37589. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37590. }
  37591. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37592. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37593. }
  37594. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37595. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37596. }
  37597. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37598. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37599. }
  37600. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37601. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37602. }
  37603. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37604. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37605. }
  37606. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37607. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37608. }
  37609. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37610. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37611. }
  37612. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37613. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37614. }
  37615. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  37616. return result;
  37617. };
  37618. /**
  37619. * Creates the VertexData for a Ribbon
  37620. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37621. * * pathArray array of paths, each of which an array of successive Vector3
  37622. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37623. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37624. * * 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
  37625. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37626. * * 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)
  37627. * * 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)
  37628. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37629. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37630. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37631. * @returns the VertexData of the ribbon
  37632. */
  37633. VertexData.CreateRibbon = function (options) {
  37634. var pathArray = options.pathArray;
  37635. var closeArray = options.closeArray || false;
  37636. var closePath = options.closePath || false;
  37637. var invertUV = options.invertUV || false;
  37638. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37639. var offset = options.offset || defaultOffset;
  37640. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37641. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37642. var customUV = options.uvs;
  37643. var customColors = options.colors;
  37644. var positions = [];
  37645. var indices = [];
  37646. var normals = [];
  37647. var uvs = [];
  37648. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37649. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37650. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37651. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37652. var minlg; // minimal length among all paths from pathArray
  37653. var lg = []; // array of path lengths : nb of vertex per path
  37654. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37655. var p; // path iterator
  37656. var i; // point iterator
  37657. var j; // point iterator
  37658. // if single path in pathArray
  37659. if (pathArray.length < 2) {
  37660. var ar1 = [];
  37661. var ar2 = [];
  37662. for (i = 0; i < pathArray[0].length - offset; i++) {
  37663. ar1.push(pathArray[0][i]);
  37664. ar2.push(pathArray[0][i + offset]);
  37665. }
  37666. pathArray = [ar1, ar2];
  37667. }
  37668. // positions and horizontal distances (u)
  37669. var idc = 0;
  37670. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37671. var path;
  37672. var l;
  37673. minlg = pathArray[0].length;
  37674. var vectlg;
  37675. var dist;
  37676. for (p = 0; p < pathArray.length; p++) {
  37677. uTotalDistance[p] = 0;
  37678. us[p] = [0];
  37679. path = pathArray[p];
  37680. l = path.length;
  37681. minlg = (minlg < l) ? minlg : l;
  37682. j = 0;
  37683. while (j < l) {
  37684. positions.push(path[j].x, path[j].y, path[j].z);
  37685. if (j > 0) {
  37686. vectlg = path[j].subtract(path[j - 1]).length();
  37687. dist = vectlg + uTotalDistance[p];
  37688. us[p].push(dist);
  37689. uTotalDistance[p] = dist;
  37690. }
  37691. j++;
  37692. }
  37693. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37694. j--;
  37695. positions.push(path[0].x, path[0].y, path[0].z);
  37696. vectlg = path[j].subtract(path[0]).length();
  37697. dist = vectlg + uTotalDistance[p];
  37698. us[p].push(dist);
  37699. uTotalDistance[p] = dist;
  37700. }
  37701. lg[p] = l + closePathCorr;
  37702. idx[p] = idc;
  37703. idc += (l + closePathCorr);
  37704. }
  37705. // vertical distances (v)
  37706. var path1;
  37707. var path2;
  37708. var vertex1 = null;
  37709. var vertex2 = null;
  37710. for (i = 0; i < minlg + closePathCorr; i++) {
  37711. vTotalDistance[i] = 0;
  37712. vs[i] = [0];
  37713. for (p = 0; p < pathArray.length - 1; p++) {
  37714. path1 = pathArray[p];
  37715. path2 = pathArray[p + 1];
  37716. if (i === minlg) { // closePath
  37717. vertex1 = path1[0];
  37718. vertex2 = path2[0];
  37719. }
  37720. else {
  37721. vertex1 = path1[i];
  37722. vertex2 = path2[i];
  37723. }
  37724. vectlg = vertex2.subtract(vertex1).length();
  37725. dist = vectlg + vTotalDistance[i];
  37726. vs[i].push(dist);
  37727. vTotalDistance[i] = dist;
  37728. }
  37729. if (closeArray && vertex2 && vertex1) {
  37730. path1 = pathArray[p];
  37731. path2 = pathArray[0];
  37732. if (i === minlg) { // closePath
  37733. vertex2 = path2[0];
  37734. }
  37735. vectlg = vertex2.subtract(vertex1).length();
  37736. dist = vectlg + vTotalDistance[i];
  37737. vTotalDistance[i] = dist;
  37738. }
  37739. }
  37740. // uvs
  37741. var u;
  37742. var v;
  37743. if (customUV) {
  37744. for (p = 0; p < customUV.length; p++) {
  37745. uvs.push(customUV[p].x, customUV[p].y);
  37746. }
  37747. }
  37748. else {
  37749. for (p = 0; p < pathArray.length; p++) {
  37750. for (i = 0; i < minlg + closePathCorr; i++) {
  37751. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37752. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37753. if (invertUV) {
  37754. uvs.push(v, u);
  37755. }
  37756. else {
  37757. uvs.push(u, v);
  37758. }
  37759. }
  37760. }
  37761. }
  37762. // indices
  37763. p = 0; // path index
  37764. var pi = 0; // positions array index
  37765. var l1 = lg[p] - 1; // path1 length
  37766. var l2 = lg[p + 1] - 1; // path2 length
  37767. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37768. var shft = idx[1] - idx[0]; // shift
  37769. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37770. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37771. // 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
  37772. indices.push(pi, pi + shft, pi + 1);
  37773. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37774. pi += 1;
  37775. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37776. p++;
  37777. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37778. shft = idx[0] - idx[p];
  37779. l1 = lg[p] - 1;
  37780. l2 = lg[0] - 1;
  37781. }
  37782. else {
  37783. shft = idx[p + 1] - idx[p];
  37784. l1 = lg[p] - 1;
  37785. l2 = lg[p + 1] - 1;
  37786. }
  37787. pi = idx[p];
  37788. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37789. }
  37790. }
  37791. // normals
  37792. VertexData.ComputeNormals(positions, indices, normals);
  37793. if (closePath) { // update both the first and last vertex normals to their average value
  37794. var indexFirst = 0;
  37795. var indexLast = 0;
  37796. for (p = 0; p < pathArray.length; p++) {
  37797. indexFirst = idx[p] * 3;
  37798. if (p + 1 < pathArray.length) {
  37799. indexLast = (idx[p + 1] - 1) * 3;
  37800. }
  37801. else {
  37802. indexLast = normals.length - 3;
  37803. }
  37804. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37805. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37806. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37807. normals[indexLast] = normals[indexFirst];
  37808. normals[indexLast + 1] = normals[indexFirst + 1];
  37809. normals[indexLast + 2] = normals[indexFirst + 2];
  37810. }
  37811. }
  37812. // sides
  37813. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37814. // Colors
  37815. var colors = null;
  37816. if (customColors) {
  37817. colors = new Float32Array(customColors.length * 4);
  37818. for (var c = 0; c < customColors.length; c++) {
  37819. colors[c * 4] = customColors[c].r;
  37820. colors[c * 4 + 1] = customColors[c].g;
  37821. colors[c * 4 + 2] = customColors[c].b;
  37822. colors[c * 4 + 3] = customColors[c].a;
  37823. }
  37824. }
  37825. // Result
  37826. var vertexData = new VertexData();
  37827. var positions32 = new Float32Array(positions);
  37828. var normals32 = new Float32Array(normals);
  37829. var uvs32 = new Float32Array(uvs);
  37830. vertexData.indices = indices;
  37831. vertexData.positions = positions32;
  37832. vertexData.normals = normals32;
  37833. vertexData.uvs = uvs32;
  37834. if (colors) {
  37835. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37836. }
  37837. if (closePath) {
  37838. vertexData._idx = idx;
  37839. }
  37840. return vertexData;
  37841. };
  37842. /**
  37843. * Creates the VertexData for a box
  37844. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37845. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37846. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37847. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37848. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37849. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37850. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37851. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37852. * * 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)
  37853. * * 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)
  37854. * @returns the VertexData of the box
  37855. */
  37856. VertexData.CreateBox = function (options) {
  37857. var normalsSource = [
  37858. new BABYLON.Vector3(0, 0, 1),
  37859. new BABYLON.Vector3(0, 0, -1),
  37860. new BABYLON.Vector3(1, 0, 0),
  37861. new BABYLON.Vector3(-1, 0, 0),
  37862. new BABYLON.Vector3(0, 1, 0),
  37863. new BABYLON.Vector3(0, -1, 0)
  37864. ];
  37865. var indices = [];
  37866. var positions = [];
  37867. var normals = [];
  37868. var uvs = [];
  37869. var width = options.width || options.size || 1;
  37870. var height = options.height || options.size || 1;
  37871. var depth = options.depth || options.size || 1;
  37872. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37873. var faceUV = options.faceUV || new Array(6);
  37874. var faceColors = options.faceColors;
  37875. var colors = [];
  37876. // default face colors and UV if undefined
  37877. for (var f = 0; f < 6; f++) {
  37878. if (faceUV[f] === undefined) {
  37879. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37880. }
  37881. if (faceColors && faceColors[f] === undefined) {
  37882. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37883. }
  37884. }
  37885. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37886. // Create each face in turn.
  37887. for (var index = 0; index < normalsSource.length; index++) {
  37888. var normal = normalsSource[index];
  37889. // Get two vectors perpendicular to the face normal and to each other.
  37890. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37891. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37892. // Six indices (two triangles) per face.
  37893. var verticesLength = positions.length / 3;
  37894. indices.push(verticesLength);
  37895. indices.push(verticesLength + 1);
  37896. indices.push(verticesLength + 2);
  37897. indices.push(verticesLength);
  37898. indices.push(verticesLength + 2);
  37899. indices.push(verticesLength + 3);
  37900. // Four vertices per face.
  37901. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37902. positions.push(vertex.x, vertex.y, vertex.z);
  37903. normals.push(normal.x, normal.y, normal.z);
  37904. uvs.push(faceUV[index].z, faceUV[index].w);
  37905. if (faceColors) {
  37906. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37907. }
  37908. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37909. positions.push(vertex.x, vertex.y, vertex.z);
  37910. normals.push(normal.x, normal.y, normal.z);
  37911. uvs.push(faceUV[index].x, faceUV[index].w);
  37912. if (faceColors) {
  37913. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37914. }
  37915. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37916. positions.push(vertex.x, vertex.y, vertex.z);
  37917. normals.push(normal.x, normal.y, normal.z);
  37918. uvs.push(faceUV[index].x, faceUV[index].y);
  37919. if (faceColors) {
  37920. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37921. }
  37922. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37923. positions.push(vertex.x, vertex.y, vertex.z);
  37924. normals.push(normal.x, normal.y, normal.z);
  37925. uvs.push(faceUV[index].z, faceUV[index].y);
  37926. if (faceColors) {
  37927. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37928. }
  37929. }
  37930. // sides
  37931. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37932. // Result
  37933. var vertexData = new VertexData();
  37934. vertexData.indices = indices;
  37935. vertexData.positions = positions;
  37936. vertexData.normals = normals;
  37937. vertexData.uvs = uvs;
  37938. if (faceColors) {
  37939. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37940. vertexData.colors = totalColors;
  37941. }
  37942. return vertexData;
  37943. };
  37944. /**
  37945. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37946. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37947. * * segments sets the number of horizontal strips optional, default 32
  37948. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37949. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37950. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37951. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37952. * * 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
  37953. * * 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
  37954. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37955. * * 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)
  37956. * * 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)
  37957. * @returns the VertexData of the ellipsoid
  37958. */
  37959. VertexData.CreateSphere = function (options) {
  37960. var segments = options.segments || 32;
  37961. var diameterX = options.diameterX || options.diameter || 1;
  37962. var diameterY = options.diameterY || options.diameter || 1;
  37963. var diameterZ = options.diameterZ || options.diameter || 1;
  37964. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37965. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37966. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37967. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37968. var totalZRotationSteps = 2 + segments;
  37969. var totalYRotationSteps = 2 * totalZRotationSteps;
  37970. var indices = [];
  37971. var positions = [];
  37972. var normals = [];
  37973. var uvs = [];
  37974. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37975. var normalizedZ = zRotationStep / totalZRotationSteps;
  37976. var angleZ = normalizedZ * Math.PI * slice;
  37977. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37978. var normalizedY = yRotationStep / totalYRotationSteps;
  37979. var angleY = normalizedY * Math.PI * 2 * arc;
  37980. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37981. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37982. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37983. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37984. var vertex = complete.multiply(radius);
  37985. var normal = complete.divide(radius).normalize();
  37986. positions.push(vertex.x, vertex.y, vertex.z);
  37987. normals.push(normal.x, normal.y, normal.z);
  37988. uvs.push(normalizedY, normalizedZ);
  37989. }
  37990. if (zRotationStep > 0) {
  37991. var verticesCount = positions.length / 3;
  37992. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37993. indices.push((firstIndex));
  37994. indices.push((firstIndex + 1));
  37995. indices.push(firstIndex + totalYRotationSteps + 1);
  37996. indices.push((firstIndex + totalYRotationSteps + 1));
  37997. indices.push((firstIndex + 1));
  37998. indices.push((firstIndex + totalYRotationSteps + 2));
  37999. }
  38000. }
  38001. }
  38002. // Sides
  38003. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38004. // Result
  38005. var vertexData = new VertexData();
  38006. vertexData.indices = indices;
  38007. vertexData.positions = positions;
  38008. vertexData.normals = normals;
  38009. vertexData.uvs = uvs;
  38010. return vertexData;
  38011. };
  38012. /**
  38013. * Creates the VertexData for a cylinder, cone or prism
  38014. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38015. * * height sets the height (y direction) of the cylinder, optional, default 2
  38016. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  38017. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  38018. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  38019. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38020. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  38021. * * 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
  38022. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38023. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38024. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  38025. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  38026. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38027. * * 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)
  38028. * * 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)
  38029. * @returns the VertexData of the cylinder, cone or prism
  38030. */
  38031. VertexData.CreateCylinder = function (options) {
  38032. var height = options.height || 2;
  38033. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  38034. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  38035. var tessellation = options.tessellation || 24;
  38036. var subdivisions = options.subdivisions || 1;
  38037. var hasRings = options.hasRings ? true : false;
  38038. var enclose = options.enclose ? true : false;
  38039. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38040. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38041. var faceUV = options.faceUV || new Array(3);
  38042. var faceColors = options.faceColors;
  38043. // default face colors and UV if undefined
  38044. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  38045. var ringNb = (hasRings) ? subdivisions : 1;
  38046. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  38047. var f;
  38048. for (f = 0; f < surfaceNb; f++) {
  38049. if (faceColors && faceColors[f] === undefined) {
  38050. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38051. }
  38052. }
  38053. for (f = 0; f < surfaceNb; f++) {
  38054. if (faceUV && faceUV[f] === undefined) {
  38055. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38056. }
  38057. }
  38058. var indices = new Array();
  38059. var positions = new Array();
  38060. var normals = new Array();
  38061. var uvs = new Array();
  38062. var colors = new Array();
  38063. var angle_step = Math.PI * 2 * arc / tessellation;
  38064. var angle;
  38065. var h;
  38066. var radius;
  38067. var tan = (diameterBottom - diameterTop) / 2 / height;
  38068. var ringVertex = BABYLON.Vector3.Zero();
  38069. var ringNormal = BABYLON.Vector3.Zero();
  38070. var ringFirstVertex = BABYLON.Vector3.Zero();
  38071. var ringFirstNormal = BABYLON.Vector3.Zero();
  38072. var quadNormal = BABYLON.Vector3.Zero();
  38073. var Y = BABYLON.Axis.Y;
  38074. // positions, normals, uvs
  38075. var i;
  38076. var j;
  38077. var r;
  38078. var ringIdx = 1;
  38079. var s = 1; // surface index
  38080. var cs = 0;
  38081. var v = 0;
  38082. for (i = 0; i <= subdivisions; i++) {
  38083. h = i / subdivisions;
  38084. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  38085. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  38086. for (r = 0; r < ringIdx; r++) {
  38087. if (hasRings) {
  38088. s += r;
  38089. }
  38090. if (enclose) {
  38091. s += 2 * r;
  38092. }
  38093. for (j = 0; j <= tessellation; j++) {
  38094. angle = j * angle_step;
  38095. // position
  38096. ringVertex.x = Math.cos(-angle) * radius;
  38097. ringVertex.y = -height / 2 + h * height;
  38098. ringVertex.z = Math.sin(-angle) * radius;
  38099. // normal
  38100. if (diameterTop === 0 && i === subdivisions) {
  38101. // if no top cap, reuse former normals
  38102. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  38103. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  38104. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  38105. }
  38106. else {
  38107. ringNormal.x = ringVertex.x;
  38108. ringNormal.z = ringVertex.z;
  38109. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  38110. ringNormal.normalize();
  38111. }
  38112. // keep first ring vertex values for enclose
  38113. if (j === 0) {
  38114. ringFirstVertex.copyFrom(ringVertex);
  38115. ringFirstNormal.copyFrom(ringNormal);
  38116. }
  38117. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38118. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  38119. if (hasRings) {
  38120. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  38121. }
  38122. else {
  38123. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  38124. }
  38125. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  38126. if (faceColors) {
  38127. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  38128. }
  38129. }
  38130. // if enclose, add four vertices and their dedicated normals
  38131. if (arc !== 1 && enclose) {
  38132. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38133. positions.push(0, ringVertex.y, 0);
  38134. positions.push(0, ringVertex.y, 0);
  38135. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  38136. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  38137. quadNormal.normalize();
  38138. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38139. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  38140. quadNormal.normalize();
  38141. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38142. if (hasRings) {
  38143. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  38144. }
  38145. else {
  38146. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  38147. }
  38148. uvs.push(faceUV[s + 1].x, v);
  38149. uvs.push(faceUV[s + 1].z, v);
  38150. if (hasRings) {
  38151. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  38152. }
  38153. else {
  38154. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  38155. }
  38156. uvs.push(faceUV[s + 2].x, v);
  38157. uvs.push(faceUV[s + 2].z, v);
  38158. if (faceColors) {
  38159. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38160. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38161. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38162. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38163. }
  38164. }
  38165. if (cs !== s) {
  38166. cs = s;
  38167. }
  38168. }
  38169. }
  38170. // indices
  38171. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  38172. var s;
  38173. i = 0;
  38174. for (s = 0; s < subdivisions; s++) {
  38175. var i0 = 0;
  38176. var i1 = 0;
  38177. var i2 = 0;
  38178. var i3 = 0;
  38179. for (j = 0; j < tessellation; j++) {
  38180. i0 = i * (e + 1) + j;
  38181. i1 = (i + 1) * (e + 1) + j;
  38182. i2 = i * (e + 1) + (j + 1);
  38183. i3 = (i + 1) * (e + 1) + (j + 1);
  38184. indices.push(i0, i1, i2);
  38185. indices.push(i3, i2, i1);
  38186. }
  38187. if (arc !== 1 && enclose) { // if enclose, add two quads
  38188. indices.push(i0 + 2, i1 + 2, i2 + 2);
  38189. indices.push(i3 + 2, i2 + 2, i1 + 2);
  38190. indices.push(i0 + 4, i1 + 4, i2 + 4);
  38191. indices.push(i3 + 4, i2 + 4, i1 + 4);
  38192. }
  38193. i = (hasRings) ? (i + 2) : (i + 1);
  38194. }
  38195. // Caps
  38196. var createCylinderCap = function (isTop) {
  38197. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  38198. if (radius === 0) {
  38199. return;
  38200. }
  38201. // Cap positions, normals & uvs
  38202. var angle;
  38203. var circleVector;
  38204. var i;
  38205. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  38206. var c = null;
  38207. if (faceColors) {
  38208. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  38209. }
  38210. // cap center
  38211. var vbase = positions.length / 3;
  38212. var offset = isTop ? height / 2 : -height / 2;
  38213. var center = new BABYLON.Vector3(0, offset, 0);
  38214. positions.push(center.x, center.y, center.z);
  38215. normals.push(0, isTop ? 1 : -1, 0);
  38216. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  38217. if (c) {
  38218. colors.push(c.r, c.g, c.b, c.a);
  38219. }
  38220. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  38221. for (i = 0; i <= tessellation; i++) {
  38222. angle = Math.PI * 2 * i * arc / tessellation;
  38223. var cos = Math.cos(-angle);
  38224. var sin = Math.sin(-angle);
  38225. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  38226. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  38227. positions.push(circleVector.x, circleVector.y, circleVector.z);
  38228. normals.push(0, isTop ? 1 : -1, 0);
  38229. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  38230. if (c) {
  38231. colors.push(c.r, c.g, c.b, c.a);
  38232. }
  38233. }
  38234. // Cap indices
  38235. for (i = 0; i < tessellation; i++) {
  38236. if (!isTop) {
  38237. indices.push(vbase);
  38238. indices.push(vbase + (i + 1));
  38239. indices.push(vbase + (i + 2));
  38240. }
  38241. else {
  38242. indices.push(vbase);
  38243. indices.push(vbase + (i + 2));
  38244. indices.push(vbase + (i + 1));
  38245. }
  38246. }
  38247. };
  38248. // add caps to geometry
  38249. createCylinderCap(false);
  38250. createCylinderCap(true);
  38251. // Sides
  38252. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38253. var vertexData = new VertexData();
  38254. vertexData.indices = indices;
  38255. vertexData.positions = positions;
  38256. vertexData.normals = normals;
  38257. vertexData.uvs = uvs;
  38258. if (faceColors) {
  38259. vertexData.colors = colors;
  38260. }
  38261. return vertexData;
  38262. };
  38263. /**
  38264. * Creates the VertexData for a torus
  38265. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38266. * * diameter the diameter of the torus, optional default 1
  38267. * * thickness the diameter of the tube forming the torus, optional default 0.5
  38268. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38269. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38270. * * 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)
  38271. * * 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)
  38272. * @returns the VertexData of the torus
  38273. */
  38274. VertexData.CreateTorus = function (options) {
  38275. var indices = [];
  38276. var positions = [];
  38277. var normals = [];
  38278. var uvs = [];
  38279. var diameter = options.diameter || 1;
  38280. var thickness = options.thickness || 0.5;
  38281. var tessellation = options.tessellation || 16;
  38282. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38283. var stride = tessellation + 1;
  38284. for (var i = 0; i <= tessellation; i++) {
  38285. var u = i / tessellation;
  38286. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  38287. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  38288. for (var j = 0; j <= tessellation; j++) {
  38289. var v = 1 - j / tessellation;
  38290. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  38291. var dx = Math.cos(innerAngle);
  38292. var dy = Math.sin(innerAngle);
  38293. // Create a vertex.
  38294. var normal = new BABYLON.Vector3(dx, dy, 0);
  38295. var position = normal.scale(thickness / 2);
  38296. var textureCoordinate = new BABYLON.Vector2(u, v);
  38297. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  38298. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  38299. positions.push(position.x, position.y, position.z);
  38300. normals.push(normal.x, normal.y, normal.z);
  38301. uvs.push(textureCoordinate.x, textureCoordinate.y);
  38302. // And create indices for two triangles.
  38303. var nextI = (i + 1) % stride;
  38304. var nextJ = (j + 1) % stride;
  38305. indices.push(i * stride + j);
  38306. indices.push(i * stride + nextJ);
  38307. indices.push(nextI * stride + j);
  38308. indices.push(i * stride + nextJ);
  38309. indices.push(nextI * stride + nextJ);
  38310. indices.push(nextI * stride + j);
  38311. }
  38312. }
  38313. // Sides
  38314. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38315. // Result
  38316. var vertexData = new VertexData();
  38317. vertexData.indices = indices;
  38318. vertexData.positions = positions;
  38319. vertexData.normals = normals;
  38320. vertexData.uvs = uvs;
  38321. return vertexData;
  38322. };
  38323. /**
  38324. * Creates the VertexData of the LineSystem
  38325. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  38326. * - lines an array of lines, each line being an array of successive Vector3
  38327. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  38328. * @returns the VertexData of the LineSystem
  38329. */
  38330. VertexData.CreateLineSystem = function (options) {
  38331. var indices = [];
  38332. var positions = [];
  38333. var lines = options.lines;
  38334. var colors = options.colors;
  38335. var vertexColors = [];
  38336. var idx = 0;
  38337. for (var l = 0; l < lines.length; l++) {
  38338. var points = lines[l];
  38339. for (var index = 0; index < points.length; index++) {
  38340. positions.push(points[index].x, points[index].y, points[index].z);
  38341. if (colors) {
  38342. var color = colors[l];
  38343. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  38344. }
  38345. if (index > 0) {
  38346. indices.push(idx - 1);
  38347. indices.push(idx);
  38348. }
  38349. idx++;
  38350. }
  38351. }
  38352. var vertexData = new VertexData();
  38353. vertexData.indices = indices;
  38354. vertexData.positions = positions;
  38355. if (colors) {
  38356. vertexData.colors = vertexColors;
  38357. }
  38358. return vertexData;
  38359. };
  38360. /**
  38361. * Create the VertexData for a DashedLines
  38362. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  38363. * - points an array successive Vector3
  38364. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  38365. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  38366. * - dashNb the intended total number of dashes, optional, default 200
  38367. * @returns the VertexData for the DashedLines
  38368. */
  38369. VertexData.CreateDashedLines = function (options) {
  38370. var dashSize = options.dashSize || 3;
  38371. var gapSize = options.gapSize || 1;
  38372. var dashNb = options.dashNb || 200;
  38373. var points = options.points;
  38374. var positions = new Array();
  38375. var indices = new Array();
  38376. var curvect = BABYLON.Vector3.Zero();
  38377. var lg = 0;
  38378. var nb = 0;
  38379. var shft = 0;
  38380. var dashshft = 0;
  38381. var curshft = 0;
  38382. var idx = 0;
  38383. var i = 0;
  38384. for (i = 0; i < points.length - 1; i++) {
  38385. points[i + 1].subtractToRef(points[i], curvect);
  38386. lg += curvect.length();
  38387. }
  38388. shft = lg / dashNb;
  38389. dashshft = dashSize * shft / (dashSize + gapSize);
  38390. for (i = 0; i < points.length - 1; i++) {
  38391. points[i + 1].subtractToRef(points[i], curvect);
  38392. nb = Math.floor(curvect.length() / shft);
  38393. curvect.normalize();
  38394. for (var j = 0; j < nb; j++) {
  38395. curshft = shft * j;
  38396. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  38397. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  38398. indices.push(idx, idx + 1);
  38399. idx += 2;
  38400. }
  38401. }
  38402. // Result
  38403. var vertexData = new VertexData();
  38404. vertexData.positions = positions;
  38405. vertexData.indices = indices;
  38406. return vertexData;
  38407. };
  38408. /**
  38409. * Creates the VertexData for a Ground
  38410. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38411. * - width the width (x direction) of the ground, optional, default 1
  38412. * - height the height (z direction) of the ground, optional, default 1
  38413. * - subdivisions the number of subdivisions per side, optional, default 1
  38414. * @returns the VertexData of the Ground
  38415. */
  38416. VertexData.CreateGround = function (options) {
  38417. var indices = [];
  38418. var positions = [];
  38419. var normals = [];
  38420. var uvs = [];
  38421. var row, col;
  38422. var width = options.width || 1;
  38423. var height = options.height || 1;
  38424. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  38425. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  38426. for (row = 0; row <= subdivisionsY; row++) {
  38427. for (col = 0; col <= subdivisionsX; col++) {
  38428. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  38429. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38430. positions.push(position.x, position.y, position.z);
  38431. normals.push(normal.x, normal.y, normal.z);
  38432. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  38433. }
  38434. }
  38435. for (row = 0; row < subdivisionsY; row++) {
  38436. for (col = 0; col < subdivisionsX; col++) {
  38437. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38438. indices.push(col + 1 + row * (subdivisionsX + 1));
  38439. indices.push(col + row * (subdivisionsX + 1));
  38440. indices.push(col + (row + 1) * (subdivisionsX + 1));
  38441. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38442. indices.push(col + row * (subdivisionsX + 1));
  38443. }
  38444. }
  38445. // Result
  38446. var vertexData = new VertexData();
  38447. vertexData.indices = indices;
  38448. vertexData.positions = positions;
  38449. vertexData.normals = normals;
  38450. vertexData.uvs = uvs;
  38451. return vertexData;
  38452. };
  38453. /**
  38454. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  38455. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38456. * * xmin the ground minimum X coordinate, optional, default -1
  38457. * * zmin the ground minimum Z coordinate, optional, default -1
  38458. * * xmax the ground maximum X coordinate, optional, default 1
  38459. * * zmax the ground maximum Z coordinate, optional, default 1
  38460. * * 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}
  38461. * * 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}
  38462. * @returns the VertexData of the TiledGround
  38463. */
  38464. VertexData.CreateTiledGround = function (options) {
  38465. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  38466. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  38467. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  38468. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  38469. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  38470. var precision = options.precision || { w: 1, h: 1 };
  38471. var indices = new Array();
  38472. var positions = new Array();
  38473. var normals = new Array();
  38474. var uvs = new Array();
  38475. var row, col, tileRow, tileCol;
  38476. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  38477. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  38478. precision.w = (precision.w < 1) ? 1 : precision.w;
  38479. precision.h = (precision.h < 1) ? 1 : precision.h;
  38480. var tileSize = {
  38481. 'w': (xmax - xmin) / subdivisions.w,
  38482. 'h': (zmax - zmin) / subdivisions.h
  38483. };
  38484. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  38485. // Indices
  38486. var base = positions.length / 3;
  38487. var rowLength = precision.w + 1;
  38488. for (row = 0; row < precision.h; row++) {
  38489. for (col = 0; col < precision.w; col++) {
  38490. var square = [
  38491. base + col + row * rowLength,
  38492. base + (col + 1) + row * rowLength,
  38493. base + (col + 1) + (row + 1) * rowLength,
  38494. base + col + (row + 1) * rowLength
  38495. ];
  38496. indices.push(square[1]);
  38497. indices.push(square[2]);
  38498. indices.push(square[3]);
  38499. indices.push(square[0]);
  38500. indices.push(square[1]);
  38501. indices.push(square[3]);
  38502. }
  38503. }
  38504. // Position, normals and uvs
  38505. var position = BABYLON.Vector3.Zero();
  38506. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38507. for (row = 0; row <= precision.h; row++) {
  38508. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  38509. for (col = 0; col <= precision.w; col++) {
  38510. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  38511. position.y = 0;
  38512. positions.push(position.x, position.y, position.z);
  38513. normals.push(normal.x, normal.y, normal.z);
  38514. uvs.push(col / precision.w, row / precision.h);
  38515. }
  38516. }
  38517. }
  38518. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  38519. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  38520. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  38521. }
  38522. }
  38523. // Result
  38524. var vertexData = new VertexData();
  38525. vertexData.indices = indices;
  38526. vertexData.positions = positions;
  38527. vertexData.normals = normals;
  38528. vertexData.uvs = uvs;
  38529. return vertexData;
  38530. };
  38531. /**
  38532. * Creates the VertexData of the Ground designed from a heightmap
  38533. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  38534. * * width the width (x direction) of the ground
  38535. * * height the height (z direction) of the ground
  38536. * * subdivisions the number of subdivisions per side
  38537. * * minHeight the minimum altitude on the ground, optional, default 0
  38538. * * maxHeight the maximum altitude on the ground, optional default 1
  38539. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  38540. * * buffer the array holding the image color data
  38541. * * bufferWidth the width of image
  38542. * * bufferHeight the height of image
  38543. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  38544. * @returns the VertexData of the Ground designed from a heightmap
  38545. */
  38546. VertexData.CreateGroundFromHeightMap = function (options) {
  38547. var indices = [];
  38548. var positions = [];
  38549. var normals = [];
  38550. var uvs = [];
  38551. var row, col;
  38552. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38553. var alphaFilter = options.alphaFilter || 0.0;
  38554. // Vertices
  38555. for (row = 0; row <= options.subdivisions; row++) {
  38556. for (col = 0; col <= options.subdivisions; col++) {
  38557. 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));
  38558. // Compute height
  38559. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38560. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38561. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38562. var r = options.buffer[pos] / 255.0;
  38563. var g = options.buffer[pos + 1] / 255.0;
  38564. var b = options.buffer[pos + 2] / 255.0;
  38565. var a = options.buffer[pos + 3] / 255.0;
  38566. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38567. // If our alpha channel is not within our filter then we will assign a 'special' height
  38568. // Then when building the indices, we will ignore any vertex that is using the special height
  38569. if (a >= alphaFilter)
  38570. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38571. else {
  38572. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  38573. }
  38574. // Add vertex
  38575. positions.push(position.x, position.y, position.z);
  38576. normals.push(0, 0, 0);
  38577. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38578. }
  38579. }
  38580. // Indices
  38581. for (row = 0; row < options.subdivisions; row++) {
  38582. for (col = 0; col < options.subdivisions; col++) {
  38583. // Calculate Indices
  38584. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  38585. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  38586. var idx3 = (col + row * (options.subdivisions + 1));
  38587. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  38588. // Check that all indices are visible (based on our special height)
  38589. // Only display the vertex if all Indices are visible
  38590. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  38591. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  38592. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  38593. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  38594. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  38595. indices.push(idx1);
  38596. indices.push(idx2);
  38597. indices.push(idx3);
  38598. }
  38599. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  38600. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  38601. indices.push(idx4);
  38602. indices.push(idx1);
  38603. indices.push(idx3);
  38604. }
  38605. }
  38606. }
  38607. // Normals
  38608. VertexData.ComputeNormals(positions, indices, normals);
  38609. // Result
  38610. var vertexData = new VertexData();
  38611. vertexData.indices = indices;
  38612. vertexData.positions = positions;
  38613. vertexData.normals = normals;
  38614. vertexData.uvs = uvs;
  38615. return vertexData;
  38616. };
  38617. /**
  38618. * Creates the VertexData for a Plane
  38619. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38620. * * size sets the width and height of the plane to the value of size, optional default 1
  38621. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38622. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38623. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38624. * * 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)
  38625. * * 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)
  38626. * @returns the VertexData of the box
  38627. */
  38628. VertexData.CreatePlane = function (options) {
  38629. var indices = [];
  38630. var positions = [];
  38631. var normals = [];
  38632. var uvs = [];
  38633. var width = options.width || options.size || 1;
  38634. var height = options.height || options.size || 1;
  38635. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38636. // Vertices
  38637. var halfWidth = width / 2.0;
  38638. var halfHeight = height / 2.0;
  38639. positions.push(-halfWidth, -halfHeight, 0);
  38640. normals.push(0, 0, -1.0);
  38641. uvs.push(0.0, 0.0);
  38642. positions.push(halfWidth, -halfHeight, 0);
  38643. normals.push(0, 0, -1.0);
  38644. uvs.push(1.0, 0.0);
  38645. positions.push(halfWidth, halfHeight, 0);
  38646. normals.push(0, 0, -1.0);
  38647. uvs.push(1.0, 1.0);
  38648. positions.push(-halfWidth, halfHeight, 0);
  38649. normals.push(0, 0, -1.0);
  38650. uvs.push(0.0, 1.0);
  38651. // Indices
  38652. indices.push(0);
  38653. indices.push(1);
  38654. indices.push(2);
  38655. indices.push(0);
  38656. indices.push(2);
  38657. indices.push(3);
  38658. // Sides
  38659. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38660. // Result
  38661. var vertexData = new VertexData();
  38662. vertexData.indices = indices;
  38663. vertexData.positions = positions;
  38664. vertexData.normals = normals;
  38665. vertexData.uvs = uvs;
  38666. return vertexData;
  38667. };
  38668. /**
  38669. * Creates the VertexData of the Disc or regular Polygon
  38670. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38671. * * radius the radius of the disc, optional default 0.5
  38672. * * tessellation the number of polygon sides, optional, default 64
  38673. * * 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
  38674. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38675. * * 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)
  38676. * * 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)
  38677. * @returns the VertexData of the box
  38678. */
  38679. VertexData.CreateDisc = function (options) {
  38680. var positions = new Array();
  38681. var indices = new Array();
  38682. var normals = new Array();
  38683. var uvs = new Array();
  38684. var radius = options.radius || 0.5;
  38685. var tessellation = options.tessellation || 64;
  38686. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38687. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38688. // positions and uvs
  38689. positions.push(0, 0, 0); // disc center first
  38690. uvs.push(0.5, 0.5);
  38691. var theta = Math.PI * 2 * arc;
  38692. var step = theta / tessellation;
  38693. for (var a = 0; a < theta; a += step) {
  38694. var x = Math.cos(a);
  38695. var y = Math.sin(a);
  38696. var u = (x + 1) / 2;
  38697. var v = (1 - y) / 2;
  38698. positions.push(radius * x, radius * y, 0);
  38699. uvs.push(u, v);
  38700. }
  38701. if (arc === 1) {
  38702. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38703. uvs.push(uvs[2], uvs[3]);
  38704. }
  38705. //indices
  38706. var vertexNb = positions.length / 3;
  38707. for (var i = 1; i < vertexNb - 1; i++) {
  38708. indices.push(i + 1, 0, i);
  38709. }
  38710. // result
  38711. VertexData.ComputeNormals(positions, indices, normals);
  38712. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38713. var vertexData = new VertexData();
  38714. vertexData.indices = indices;
  38715. vertexData.positions = positions;
  38716. vertexData.normals = normals;
  38717. vertexData.uvs = uvs;
  38718. return vertexData;
  38719. };
  38720. /**
  38721. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38722. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38723. * @param polygon a mesh built from polygonTriangulation.build()
  38724. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38725. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38726. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38727. * @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)
  38728. * @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)
  38729. * @returns the VertexData of the Polygon
  38730. */
  38731. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38732. var faceUV = fUV || new Array(3);
  38733. var faceColors = fColors;
  38734. var colors = [];
  38735. // default face colors and UV if undefined
  38736. for (var f = 0; f < 3; f++) {
  38737. if (faceUV[f] === undefined) {
  38738. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38739. }
  38740. if (faceColors && faceColors[f] === undefined) {
  38741. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38742. }
  38743. }
  38744. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38745. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38746. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38747. var indices = polygon.getIndices();
  38748. // set face colours and textures
  38749. var idx = 0;
  38750. var face = 0;
  38751. for (var index = 0; index < normals.length; index += 3) {
  38752. //Edge Face no. 1
  38753. if (Math.abs(normals[index + 1]) < 0.001) {
  38754. face = 1;
  38755. }
  38756. //Top Face no. 0
  38757. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38758. face = 0;
  38759. }
  38760. //Bottom Face no. 2
  38761. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38762. face = 2;
  38763. }
  38764. idx = index / 3;
  38765. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38766. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38767. if (faceColors) {
  38768. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38769. }
  38770. }
  38771. // sides
  38772. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38773. // Result
  38774. var vertexData = new VertexData();
  38775. vertexData.indices = indices;
  38776. vertexData.positions = positions;
  38777. vertexData.normals = normals;
  38778. vertexData.uvs = uvs;
  38779. if (faceColors) {
  38780. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38781. vertexData.colors = totalColors;
  38782. }
  38783. return vertexData;
  38784. };
  38785. /**
  38786. * Creates the VertexData of the IcoSphere
  38787. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38788. * * radius the radius of the IcoSphere, optional default 1
  38789. * * radiusX allows stretching in the x direction, optional, default radius
  38790. * * radiusY allows stretching in the y direction, optional, default radius
  38791. * * radiusZ allows stretching in the z direction, optional, default radius
  38792. * * flat when true creates a flat shaded mesh, optional, default true
  38793. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38794. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38795. * * 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)
  38796. * * 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)
  38797. * @returns the VertexData of the IcoSphere
  38798. */
  38799. VertexData.CreateIcoSphere = function (options) {
  38800. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38801. var radius = options.radius || 1;
  38802. var flat = (options.flat === undefined) ? true : options.flat;
  38803. var subdivisions = options.subdivisions || 4;
  38804. var radiusX = options.radiusX || radius;
  38805. var radiusY = options.radiusY || radius;
  38806. var radiusZ = options.radiusZ || radius;
  38807. var t = (1 + Math.sqrt(5)) / 2;
  38808. // 12 vertex x,y,z
  38809. var ico_vertices = [
  38810. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38811. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38812. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38813. ];
  38814. // index of 3 vertex makes a face of icopshere
  38815. var ico_indices = [
  38816. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38817. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38818. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38819. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38820. ];
  38821. // vertex for uv have aliased position, not for UV
  38822. var vertices_unalias_id = [
  38823. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38824. // vertex alias
  38825. 0,
  38826. 2,
  38827. 3,
  38828. 3,
  38829. 3,
  38830. 4,
  38831. 7,
  38832. 8,
  38833. 9,
  38834. 9,
  38835. 10,
  38836. 11 // 23: B + 12
  38837. ];
  38838. // uv as integer step (not pixels !)
  38839. var ico_vertexuv = [
  38840. 5, 1, 3, 1, 6, 4, 0, 0,
  38841. 5, 3, 4, 2, 2, 2, 4, 0,
  38842. 2, 0, 1, 1, 6, 0, 6, 2,
  38843. // vertex alias (for same vertex on different faces)
  38844. 0, 4,
  38845. 3, 3,
  38846. 4, 4,
  38847. 3, 1,
  38848. 4, 2,
  38849. 4, 4,
  38850. 0, 2,
  38851. 1, 1,
  38852. 2, 2,
  38853. 3, 3,
  38854. 1, 3,
  38855. 2, 4 // 23: B + 12
  38856. ];
  38857. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38858. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38859. // First island of uv mapping
  38860. // v = 4h 3+ 2
  38861. // v = 3h 9+ 4
  38862. // v = 2h 9+ 5 B
  38863. // v = 1h 9 1 0
  38864. // v = 0h 3 8 7 A
  38865. // u = 0 1 2 3 4 5 6 *a
  38866. // Second island of uv mapping
  38867. // v = 4h 0+ B+ 4+
  38868. // v = 3h A+ 2+
  38869. // v = 2h 7+ 6 3+
  38870. // v = 1h 8+ 3+
  38871. // v = 0h
  38872. // u = 0 1 2 3 4 5 6 *a
  38873. // Face layout on texture UV mapping
  38874. // ============
  38875. // \ 4 /\ 16 / ======
  38876. // \ / \ / /\ 11 /
  38877. // \/ 7 \/ / \ /
  38878. // ======= / 10 \/
  38879. // /\ 17 /\ =======
  38880. // / \ / \ \ 15 /\
  38881. // / 8 \/ 12 \ \ / \
  38882. // ============ \/ 6 \
  38883. // \ 18 /\ ============
  38884. // \ / \ \ 5 /\ 0 /
  38885. // \/ 13 \ \ / \ /
  38886. // ======= \/ 1 \/
  38887. // =============
  38888. // /\ 19 /\ 2 /\
  38889. // / \ / \ / \
  38890. // / 14 \/ 9 \/ 3 \
  38891. // ===================
  38892. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38893. var ustep = 138 / 1024;
  38894. var vstep = 239 / 1024;
  38895. var uoffset = 60 / 1024;
  38896. var voffset = 26 / 1024;
  38897. // Second island should have margin, not to touch the first island
  38898. // avoid any borderline artefact in pixel rounding
  38899. var island_u_offset = -40 / 1024;
  38900. var island_v_offset = +20 / 1024;
  38901. // face is either island 0 or 1 :
  38902. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38903. var island = [
  38904. 0, 0, 0, 0, 1,
  38905. 0, 0, 1, 1, 0,
  38906. 0, 0, 1, 1, 0,
  38907. 0, 1, 1, 1, 0 // 15 - 19
  38908. ];
  38909. var indices = new Array();
  38910. var positions = new Array();
  38911. var normals = new Array();
  38912. var uvs = new Array();
  38913. var current_indice = 0;
  38914. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38915. var face_vertex_pos = new Array(3);
  38916. var face_vertex_uv = new Array(3);
  38917. var v012;
  38918. for (v012 = 0; v012 < 3; v012++) {
  38919. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38920. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38921. }
  38922. // create all with normals
  38923. for (var face = 0; face < 20; face++) {
  38924. // 3 vertex per face
  38925. for (v012 = 0; v012 < 3; v012++) {
  38926. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38927. var v_id = ico_indices[3 * face + v012];
  38928. // vertex have 3D position (x,y,z)
  38929. 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]);
  38930. // Normalize to get normal, then scale to radius
  38931. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38932. // uv Coordinates from vertex ID
  38933. 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);
  38934. }
  38935. // Subdivide the face (interpolate pos, norm, uv)
  38936. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38937. // - norm is linear interpolation of vertex corner normal
  38938. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38939. // - uv is linear interpolation
  38940. //
  38941. // Topology is as below for sub-divide by 2
  38942. // vertex shown as v0,v1,v2
  38943. // interp index is i1 to progress in range [v0,v1[
  38944. // interp index is i2 to progress in range [v0,v2[
  38945. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38946. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38947. //
  38948. //
  38949. // i2 v2
  38950. // ^ ^
  38951. // / / \
  38952. // / / \
  38953. // / / \
  38954. // / / (0,1) \
  38955. // / #---------\
  38956. // / / \ (0,0)'/ \
  38957. // / / \ / \
  38958. // / / \ / \
  38959. // / / (0,0) \ / (1,0) \
  38960. // / #---------#---------\
  38961. // v0 v1
  38962. //
  38963. // --------------------> i1
  38964. //
  38965. // interp of (i1,i2):
  38966. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38967. // along i1 : lerp(x0,x1, i1/(S-i2))
  38968. //
  38969. // centroid of triangle is needed to get help normal computation
  38970. // (c1,c2) are used for centroid location
  38971. var interp_vertex = function (i1, i2, c1, c2) {
  38972. // vertex is interpolated from
  38973. // - face_vertex_pos[0..2]
  38974. // - face_vertex_uv[0..2]
  38975. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38976. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38977. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38978. pos_interp.normalize();
  38979. var vertex_normal;
  38980. if (flat) {
  38981. // in flat mode, recalculate normal as face centroid normal
  38982. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38983. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38984. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38985. }
  38986. else {
  38987. // in smooth mode, recalculate normal from each single vertex position
  38988. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38989. }
  38990. // Vertex normal need correction due to X,Y,Z radius scaling
  38991. vertex_normal.x /= radiusX;
  38992. vertex_normal.y /= radiusY;
  38993. vertex_normal.z /= radiusZ;
  38994. vertex_normal.normalize();
  38995. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38996. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38997. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38998. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38999. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  39000. uvs.push(uv_interp.x, uv_interp.y);
  39001. // push each vertex has member of a face
  39002. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  39003. indices.push(current_indice);
  39004. current_indice++;
  39005. };
  39006. for (var i2 = 0; i2 < subdivisions; i2++) {
  39007. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  39008. // face : (i1,i2) for /\ :
  39009. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  39010. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39011. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39012. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39013. if (i1 + i2 + 1 < subdivisions) {
  39014. // face : (i1,i2)' for \/ :
  39015. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39016. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39017. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39018. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39019. }
  39020. }
  39021. }
  39022. }
  39023. // Sides
  39024. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39025. // Result
  39026. var vertexData = new VertexData();
  39027. vertexData.indices = indices;
  39028. vertexData.positions = positions;
  39029. vertexData.normals = normals;
  39030. vertexData.uvs = uvs;
  39031. return vertexData;
  39032. };
  39033. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  39034. /**
  39035. * Creates the VertexData for a Polyhedron
  39036. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  39037. * * type provided types are:
  39038. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39039. * * 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)
  39040. * * size the size of the IcoSphere, optional default 1
  39041. * * sizeX allows stretching in the x direction, optional, default size
  39042. * * sizeY allows stretching in the y direction, optional, default size
  39043. * * sizeZ allows stretching in the z direction, optional, default size
  39044. * * 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
  39045. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39046. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39047. * * flat when true creates a flat shaded mesh, optional, default true
  39048. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39049. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39050. * * 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)
  39051. * * 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)
  39052. * @returns the VertexData of the Polyhedron
  39053. */
  39054. VertexData.CreatePolyhedron = function (options) {
  39055. // provided polyhedron types :
  39056. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39057. // 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)
  39058. var polyhedra = [];
  39059. 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]] };
  39060. 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]] };
  39061. polyhedra[2] = {
  39062. 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]],
  39063. 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]]
  39064. };
  39065. polyhedra[3] = {
  39066. 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]],
  39067. 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]]
  39068. };
  39069. polyhedra[4] = {
  39070. 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]],
  39071. 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]]
  39072. };
  39073. 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]] };
  39074. 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]] };
  39075. 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]] };
  39076. 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]] };
  39077. 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]] };
  39078. 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]] };
  39079. 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]] };
  39080. 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]] };
  39081. 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]] };
  39082. polyhedra[14] = {
  39083. 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]],
  39084. 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]]
  39085. };
  39086. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  39087. var size = options.size;
  39088. var sizeX = options.sizeX || size || 1;
  39089. var sizeY = options.sizeY || size || 1;
  39090. var sizeZ = options.sizeZ || size || 1;
  39091. var data = options.custom || polyhedra[type];
  39092. var nbfaces = data.face.length;
  39093. var faceUV = options.faceUV || new Array(nbfaces);
  39094. var faceColors = options.faceColors;
  39095. var flat = (options.flat === undefined) ? true : options.flat;
  39096. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39097. var positions = new Array();
  39098. var indices = new Array();
  39099. var normals = new Array();
  39100. var uvs = new Array();
  39101. var colors = new Array();
  39102. var index = 0;
  39103. var faceIdx = 0; // face cursor in the array "indexes"
  39104. var indexes = new Array();
  39105. var i = 0;
  39106. var f = 0;
  39107. var u, v, ang, x, y, tmp;
  39108. // default face colors and UV if undefined
  39109. if (flat) {
  39110. for (f = 0; f < nbfaces; f++) {
  39111. if (faceColors && faceColors[f] === undefined) {
  39112. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39113. }
  39114. if (faceUV && faceUV[f] === undefined) {
  39115. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39116. }
  39117. }
  39118. }
  39119. if (!flat) {
  39120. for (i = 0; i < data.vertex.length; i++) {
  39121. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  39122. uvs.push(0, 0);
  39123. }
  39124. for (f = 0; f < nbfaces; f++) {
  39125. for (i = 0; i < data.face[f].length - 2; i++) {
  39126. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  39127. }
  39128. }
  39129. }
  39130. else {
  39131. for (f = 0; f < nbfaces; f++) {
  39132. var fl = data.face[f].length; // number of vertices of the current face
  39133. ang = 2 * Math.PI / fl;
  39134. x = 0.5 * Math.tan(ang / 2);
  39135. y = 0.5;
  39136. // positions, uvs, colors
  39137. for (i = 0; i < fl; i++) {
  39138. // positions
  39139. 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);
  39140. indexes.push(index);
  39141. index++;
  39142. // uvs
  39143. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  39144. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  39145. uvs.push(u, v);
  39146. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  39147. y = x * Math.sin(ang) + y * Math.cos(ang);
  39148. x = tmp;
  39149. // colors
  39150. if (faceColors) {
  39151. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  39152. }
  39153. }
  39154. // indices from indexes
  39155. for (i = 0; i < fl - 2; i++) {
  39156. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  39157. }
  39158. faceIdx += fl;
  39159. }
  39160. }
  39161. VertexData.ComputeNormals(positions, indices, normals);
  39162. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39163. var vertexData = new VertexData();
  39164. vertexData.positions = positions;
  39165. vertexData.indices = indices;
  39166. vertexData.normals = normals;
  39167. vertexData.uvs = uvs;
  39168. if (faceColors && flat) {
  39169. vertexData.colors = colors;
  39170. }
  39171. return vertexData;
  39172. };
  39173. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  39174. /**
  39175. * Creates the VertexData for a TorusKnot
  39176. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  39177. * * radius the radius of the torus knot, optional, default 2
  39178. * * tube the thickness of the tube, optional, default 0.5
  39179. * * radialSegments the number of sides on each tube segments, optional, default 32
  39180. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  39181. * * p the number of windings around the z axis, optional, default 2
  39182. * * q the number of windings around the x axis, optional, default 3
  39183. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39184. * * 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)
  39185. * * 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)
  39186. * @returns the VertexData of the Torus Knot
  39187. */
  39188. VertexData.CreateTorusKnot = function (options) {
  39189. var indices = new Array();
  39190. var positions = new Array();
  39191. var normals = new Array();
  39192. var uvs = new Array();
  39193. var radius = options.radius || 2;
  39194. var tube = options.tube || 0.5;
  39195. var radialSegments = options.radialSegments || 32;
  39196. var tubularSegments = options.tubularSegments || 32;
  39197. var p = options.p || 2;
  39198. var q = options.q || 3;
  39199. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39200. // Helper
  39201. var getPos = function (angle) {
  39202. var cu = Math.cos(angle);
  39203. var su = Math.sin(angle);
  39204. var quOverP = q / p * angle;
  39205. var cs = Math.cos(quOverP);
  39206. var tx = radius * (2 + cs) * 0.5 * cu;
  39207. var ty = radius * (2 + cs) * su * 0.5;
  39208. var tz = radius * Math.sin(quOverP) * 0.5;
  39209. return new BABYLON.Vector3(tx, ty, tz);
  39210. };
  39211. // Vertices
  39212. var i;
  39213. var j;
  39214. for (i = 0; i <= radialSegments; i++) {
  39215. var modI = i % radialSegments;
  39216. var u = modI / radialSegments * 2 * p * Math.PI;
  39217. var p1 = getPos(u);
  39218. var p2 = getPos(u + 0.01);
  39219. var tang = p2.subtract(p1);
  39220. var n = p2.add(p1);
  39221. var bitan = BABYLON.Vector3.Cross(tang, n);
  39222. n = BABYLON.Vector3.Cross(bitan, tang);
  39223. bitan.normalize();
  39224. n.normalize();
  39225. for (j = 0; j < tubularSegments; j++) {
  39226. var modJ = j % tubularSegments;
  39227. var v = modJ / tubularSegments * 2 * Math.PI;
  39228. var cx = -tube * Math.cos(v);
  39229. var cy = tube * Math.sin(v);
  39230. positions.push(p1.x + cx * n.x + cy * bitan.x);
  39231. positions.push(p1.y + cx * n.y + cy * bitan.y);
  39232. positions.push(p1.z + cx * n.z + cy * bitan.z);
  39233. uvs.push(i / radialSegments);
  39234. uvs.push(j / tubularSegments);
  39235. }
  39236. }
  39237. for (i = 0; i < radialSegments; i++) {
  39238. for (j = 0; j < tubularSegments; j++) {
  39239. var jNext = (j + 1) % tubularSegments;
  39240. var a = i * tubularSegments + j;
  39241. var b = (i + 1) * tubularSegments + j;
  39242. var c = (i + 1) * tubularSegments + jNext;
  39243. var d = i * tubularSegments + jNext;
  39244. indices.push(d);
  39245. indices.push(b);
  39246. indices.push(a);
  39247. indices.push(d);
  39248. indices.push(c);
  39249. indices.push(b);
  39250. }
  39251. }
  39252. // Normals
  39253. VertexData.ComputeNormals(positions, indices, normals);
  39254. // Sides
  39255. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39256. // Result
  39257. var vertexData = new VertexData();
  39258. vertexData.indices = indices;
  39259. vertexData.positions = positions;
  39260. vertexData.normals = normals;
  39261. vertexData.uvs = uvs;
  39262. return vertexData;
  39263. };
  39264. // Tools
  39265. /**
  39266. * Compute normals for given positions and indices
  39267. * @param positions an array of vertex positions, [...., x, y, z, ......]
  39268. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  39269. * @param normals an array of vertex normals, [...., x, y, z, ......]
  39270. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  39271. * * facetNormals : optional array of facet normals (vector3)
  39272. * * facetPositions : optional array of facet positions (vector3)
  39273. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  39274. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  39275. * * bInfo : optional bounding info, required for facetPartitioning computation
  39276. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  39277. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  39278. * * useRightHandedSystem: optional boolean to for right handed system computation
  39279. * * depthSort : optional boolean to enable the facet depth sort computation
  39280. * * distanceTo : optional Vector3 to compute the facet depth from this location
  39281. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  39282. */
  39283. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  39284. // temporary scalar variables
  39285. var index = 0; // facet index
  39286. var p1p2x = 0.0; // p1p2 vector x coordinate
  39287. var p1p2y = 0.0; // p1p2 vector y coordinate
  39288. var p1p2z = 0.0; // p1p2 vector z coordinate
  39289. var p3p2x = 0.0; // p3p2 vector x coordinate
  39290. var p3p2y = 0.0; // p3p2 vector y coordinate
  39291. var p3p2z = 0.0; // p3p2 vector z coordinate
  39292. var faceNormalx = 0.0; // facet normal x coordinate
  39293. var faceNormaly = 0.0; // facet normal y coordinate
  39294. var faceNormalz = 0.0; // facet normal z coordinate
  39295. var length = 0.0; // facet normal length before normalization
  39296. var v1x = 0; // vector1 x index in the positions array
  39297. var v1y = 0; // vector1 y index in the positions array
  39298. var v1z = 0; // vector1 z index in the positions array
  39299. var v2x = 0; // vector2 x index in the positions array
  39300. var v2y = 0; // vector2 y index in the positions array
  39301. var v2z = 0; // vector2 z index in the positions array
  39302. var v3x = 0; // vector3 x index in the positions array
  39303. var v3y = 0; // vector3 y index in the positions array
  39304. var v3z = 0; // vector3 z index in the positions array
  39305. var computeFacetNormals = false;
  39306. var computeFacetPositions = false;
  39307. var computeFacetPartitioning = false;
  39308. var computeDepthSort = false;
  39309. var faceNormalSign = 1;
  39310. var ratio = 0;
  39311. var distanceTo = null;
  39312. if (options) {
  39313. computeFacetNormals = (options.facetNormals) ? true : false;
  39314. computeFacetPositions = (options.facetPositions) ? true : false;
  39315. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  39316. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  39317. ratio = options.ratio || 0;
  39318. computeDepthSort = (options.depthSort) ? true : false;
  39319. distanceTo = (options.distanceTo);
  39320. if (computeDepthSort) {
  39321. if (distanceTo === undefined) {
  39322. distanceTo = BABYLON.Vector3.Zero();
  39323. }
  39324. var depthSortedFacets = options.depthSortedFacets;
  39325. }
  39326. }
  39327. // facetPartitioning reinit if needed
  39328. var xSubRatio = 0;
  39329. var ySubRatio = 0;
  39330. var zSubRatio = 0;
  39331. var subSq = 0;
  39332. if (computeFacetPartitioning && options && options.bbSize) {
  39333. var ox = 0; // X partitioning index for facet position
  39334. var oy = 0; // Y partinioning index for facet position
  39335. var oz = 0; // Z partinioning index for facet position
  39336. var b1x = 0; // X partitioning index for facet v1 vertex
  39337. var b1y = 0; // Y partitioning index for facet v1 vertex
  39338. var b1z = 0; // z partitioning index for facet v1 vertex
  39339. var b2x = 0; // X partitioning index for facet v2 vertex
  39340. var b2y = 0; // Y partitioning index for facet v2 vertex
  39341. var b2z = 0; // Z partitioning index for facet v2 vertex
  39342. var b3x = 0; // X partitioning index for facet v3 vertex
  39343. var b3y = 0; // Y partitioning index for facet v3 vertex
  39344. var b3z = 0; // Z partitioning index for facet v3 vertex
  39345. var block_idx_o = 0; // facet barycenter block index
  39346. var block_idx_v1 = 0; // v1 vertex block index
  39347. var block_idx_v2 = 0; // v2 vertex block index
  39348. var block_idx_v3 = 0; // v3 vertex block index
  39349. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  39350. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  39351. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  39352. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  39353. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  39354. subSq = options.subDiv.max * options.subDiv.max;
  39355. options.facetPartitioning.length = 0;
  39356. }
  39357. // reset the normals
  39358. for (index = 0; index < positions.length; index++) {
  39359. normals[index] = 0.0;
  39360. }
  39361. // Loop : 1 indice triplet = 1 facet
  39362. var nbFaces = (indices.length / 3) | 0;
  39363. for (index = 0; index < nbFaces; index++) {
  39364. // get the indexes of the coordinates of each vertex of the facet
  39365. v1x = indices[index * 3] * 3;
  39366. v1y = v1x + 1;
  39367. v1z = v1x + 2;
  39368. v2x = indices[index * 3 + 1] * 3;
  39369. v2y = v2x + 1;
  39370. v2z = v2x + 2;
  39371. v3x = indices[index * 3 + 2] * 3;
  39372. v3y = v3x + 1;
  39373. v3z = v3x + 2;
  39374. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  39375. p1p2y = positions[v1y] - positions[v2y];
  39376. p1p2z = positions[v1z] - positions[v2z];
  39377. p3p2x = positions[v3x] - positions[v2x];
  39378. p3p2y = positions[v3y] - positions[v2y];
  39379. p3p2z = positions[v3z] - positions[v2z];
  39380. // compute the face normal with the cross product
  39381. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  39382. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  39383. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  39384. // normalize this normal and store it in the array facetData
  39385. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39386. length = (length === 0) ? 1.0 : length;
  39387. faceNormalx /= length;
  39388. faceNormaly /= length;
  39389. faceNormalz /= length;
  39390. if (computeFacetNormals && options) {
  39391. options.facetNormals[index].x = faceNormalx;
  39392. options.facetNormals[index].y = faceNormaly;
  39393. options.facetNormals[index].z = faceNormalz;
  39394. }
  39395. if (computeFacetPositions && options) {
  39396. // compute and the facet barycenter coordinates in the array facetPositions
  39397. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  39398. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  39399. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  39400. }
  39401. if (computeFacetPartitioning && options) {
  39402. // store the facet indexes in arrays in the main facetPartitioning array :
  39403. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  39404. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  39405. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  39406. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  39407. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39408. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39409. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39410. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39411. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39412. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39413. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39414. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39415. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39416. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  39417. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  39418. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  39419. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  39420. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  39421. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  39422. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  39423. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  39424. // push each facet index in each block containing the vertex
  39425. options.facetPartitioning[block_idx_v1].push(index);
  39426. if (block_idx_v2 != block_idx_v1) {
  39427. options.facetPartitioning[block_idx_v2].push(index);
  39428. }
  39429. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  39430. options.facetPartitioning[block_idx_v3].push(index);
  39431. }
  39432. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  39433. options.facetPartitioning[block_idx_o].push(index);
  39434. }
  39435. }
  39436. if (computeDepthSort && options && options.facetPositions) {
  39437. var dsf = depthSortedFacets[index];
  39438. dsf.ind = index * 3;
  39439. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  39440. }
  39441. // compute the normals anyway
  39442. normals[v1x] += faceNormalx; // accumulate all the normals per face
  39443. normals[v1y] += faceNormaly;
  39444. normals[v1z] += faceNormalz;
  39445. normals[v2x] += faceNormalx;
  39446. normals[v2y] += faceNormaly;
  39447. normals[v2z] += faceNormalz;
  39448. normals[v3x] += faceNormalx;
  39449. normals[v3y] += faceNormaly;
  39450. normals[v3z] += faceNormalz;
  39451. }
  39452. // last normalization of each normal
  39453. for (index = 0; index < normals.length / 3; index++) {
  39454. faceNormalx = normals[index * 3];
  39455. faceNormaly = normals[index * 3 + 1];
  39456. faceNormalz = normals[index * 3 + 2];
  39457. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39458. length = (length === 0) ? 1.0 : length;
  39459. faceNormalx /= length;
  39460. faceNormaly /= length;
  39461. faceNormalz /= length;
  39462. normals[index * 3] = faceNormalx;
  39463. normals[index * 3 + 1] = faceNormaly;
  39464. normals[index * 3 + 2] = faceNormalz;
  39465. }
  39466. };
  39467. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  39468. var li = indices.length;
  39469. var ln = normals.length;
  39470. var i;
  39471. var n;
  39472. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39473. switch (sideOrientation) {
  39474. case BABYLON.Mesh.FRONTSIDE:
  39475. // nothing changed
  39476. break;
  39477. case BABYLON.Mesh.BACKSIDE:
  39478. var tmp;
  39479. // indices
  39480. for (i = 0; i < li; i += 3) {
  39481. tmp = indices[i];
  39482. indices[i] = indices[i + 2];
  39483. indices[i + 2] = tmp;
  39484. }
  39485. // normals
  39486. for (n = 0; n < ln; n++) {
  39487. normals[n] = -normals[n];
  39488. }
  39489. break;
  39490. case BABYLON.Mesh.DOUBLESIDE:
  39491. // positions
  39492. var lp = positions.length;
  39493. var l = lp / 3;
  39494. for (var p = 0; p < lp; p++) {
  39495. positions[lp + p] = positions[p];
  39496. }
  39497. // indices
  39498. for (i = 0; i < li; i += 3) {
  39499. indices[i + li] = indices[i + 2] + l;
  39500. indices[i + 1 + li] = indices[i + 1] + l;
  39501. indices[i + 2 + li] = indices[i] + l;
  39502. }
  39503. // normals
  39504. for (n = 0; n < ln; n++) {
  39505. normals[ln + n] = -normals[n];
  39506. }
  39507. // uvs
  39508. var lu = uvs.length;
  39509. var u = 0;
  39510. for (u = 0; u < lu; u++) {
  39511. uvs[u + lu] = uvs[u];
  39512. }
  39513. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39514. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39515. u = 0;
  39516. for (i = 0; i < lu / 2; i++) {
  39517. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  39518. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  39519. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  39520. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  39521. u += 2;
  39522. }
  39523. break;
  39524. }
  39525. };
  39526. /**
  39527. * Applies VertexData created from the imported parameters to the geometry
  39528. * @param parsedVertexData the parsed data from an imported file
  39529. * @param geometry the geometry to apply the VertexData to
  39530. */
  39531. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  39532. var vertexData = new VertexData();
  39533. // positions
  39534. var positions = parsedVertexData.positions;
  39535. if (positions) {
  39536. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  39537. }
  39538. // normals
  39539. var normals = parsedVertexData.normals;
  39540. if (normals) {
  39541. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  39542. }
  39543. // tangents
  39544. var tangents = parsedVertexData.tangents;
  39545. if (tangents) {
  39546. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  39547. }
  39548. // uvs
  39549. var uvs = parsedVertexData.uvs;
  39550. if (uvs) {
  39551. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  39552. }
  39553. // uv2s
  39554. var uv2s = parsedVertexData.uv2s;
  39555. if (uv2s) {
  39556. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  39557. }
  39558. // uv3s
  39559. var uv3s = parsedVertexData.uv3s;
  39560. if (uv3s) {
  39561. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  39562. }
  39563. // uv4s
  39564. var uv4s = parsedVertexData.uv4s;
  39565. if (uv4s) {
  39566. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  39567. }
  39568. // uv5s
  39569. var uv5s = parsedVertexData.uv5s;
  39570. if (uv5s) {
  39571. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  39572. }
  39573. // uv6s
  39574. var uv6s = parsedVertexData.uv6s;
  39575. if (uv6s) {
  39576. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  39577. }
  39578. // colors
  39579. var colors = parsedVertexData.colors;
  39580. if (colors) {
  39581. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39582. }
  39583. // matricesIndices
  39584. var matricesIndices = parsedVertexData.matricesIndices;
  39585. if (matricesIndices) {
  39586. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39587. }
  39588. // matricesWeights
  39589. var matricesWeights = parsedVertexData.matricesWeights;
  39590. if (matricesWeights) {
  39591. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39592. }
  39593. // indices
  39594. var indices = parsedVertexData.indices;
  39595. if (indices) {
  39596. vertexData.indices = indices;
  39597. }
  39598. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39599. };
  39600. return VertexData;
  39601. }());
  39602. BABYLON.VertexData = VertexData;
  39603. })(BABYLON || (BABYLON = {}));
  39604. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39605. var BABYLON;
  39606. (function (BABYLON) {
  39607. /**
  39608. * Class used to store geometry data (vertex buffers + index buffer)
  39609. */
  39610. var Geometry = /** @class */ (function () {
  39611. /**
  39612. * Creates a new geometry
  39613. * @param id defines the unique ID
  39614. * @param scene defines the hosting scene
  39615. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39616. * @param updatable defines if geometry must be updatable (false by default)
  39617. * @param mesh defines the mesh that will be associated with the geometry
  39618. */
  39619. function Geometry(id, scene, vertexData, updatable, mesh) {
  39620. if (updatable === void 0) { updatable = false; }
  39621. if (mesh === void 0) { mesh = null; }
  39622. /**
  39623. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39624. */
  39625. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39626. this._totalVertices = 0;
  39627. this._isDisposed = false;
  39628. this._indexBufferIsUpdatable = false;
  39629. this.id = id;
  39630. this._engine = scene.getEngine();
  39631. this._meshes = [];
  39632. this._scene = scene;
  39633. //Init vertex buffer cache
  39634. this._vertexBuffers = {};
  39635. this._indices = [];
  39636. this._updatable = updatable;
  39637. // vertexData
  39638. if (vertexData) {
  39639. this.setAllVerticesData(vertexData, updatable);
  39640. }
  39641. else {
  39642. this._totalVertices = 0;
  39643. this._indices = [];
  39644. }
  39645. if (this._engine.getCaps().vertexArrayObject) {
  39646. this._vertexArrayObjects = {};
  39647. }
  39648. // applyToMesh
  39649. if (mesh) {
  39650. if (mesh.getClassName() === "LinesMesh") {
  39651. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39652. this._updateExtend();
  39653. }
  39654. this.applyToMesh(mesh);
  39655. mesh.computeWorldMatrix(true);
  39656. }
  39657. }
  39658. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39659. /**
  39660. * 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
  39661. */
  39662. get: function () {
  39663. return this._boundingBias;
  39664. },
  39665. /**
  39666. * 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
  39667. */
  39668. set: function (value) {
  39669. if (this._boundingBias) {
  39670. if (this._boundingBias.equals(value)) {
  39671. return;
  39672. }
  39673. this._boundingBias.copyFrom(value);
  39674. }
  39675. else {
  39676. this._boundingBias = value.clone();
  39677. }
  39678. this._updateBoundingInfo(true, null);
  39679. },
  39680. enumerable: true,
  39681. configurable: true
  39682. });
  39683. /**
  39684. * Static function used to attach a new empty geometry to a mesh
  39685. * @param mesh defines the mesh to attach the geometry to
  39686. * @returns the new {BABYLON.Geometry}
  39687. */
  39688. Geometry.CreateGeometryForMesh = function (mesh) {
  39689. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39690. geometry.applyToMesh(mesh);
  39691. return geometry;
  39692. };
  39693. Object.defineProperty(Geometry.prototype, "extend", {
  39694. /**
  39695. * Gets the current extend of the geometry
  39696. */
  39697. get: function () {
  39698. return this._extend;
  39699. },
  39700. enumerable: true,
  39701. configurable: true
  39702. });
  39703. /**
  39704. * Gets the hosting scene
  39705. * @returns the hosting {BABYLON.Scene}
  39706. */
  39707. Geometry.prototype.getScene = function () {
  39708. return this._scene;
  39709. };
  39710. /**
  39711. * Gets the hosting engine
  39712. * @returns the hosting {BABYLON.Engine}
  39713. */
  39714. Geometry.prototype.getEngine = function () {
  39715. return this._engine;
  39716. };
  39717. /**
  39718. * Defines if the geometry is ready to use
  39719. * @returns true if the geometry is ready to be used
  39720. */
  39721. Geometry.prototype.isReady = function () {
  39722. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39723. };
  39724. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39725. /**
  39726. * Gets a value indicating that the geometry should not be serialized
  39727. */
  39728. get: function () {
  39729. for (var index = 0; index < this._meshes.length; index++) {
  39730. if (!this._meshes[index].doNotSerialize) {
  39731. return false;
  39732. }
  39733. }
  39734. return true;
  39735. },
  39736. enumerable: true,
  39737. configurable: true
  39738. });
  39739. /** @hidden */
  39740. Geometry.prototype._rebuild = function () {
  39741. if (this._vertexArrayObjects) {
  39742. this._vertexArrayObjects = {};
  39743. }
  39744. // Index buffer
  39745. if (this._meshes.length !== 0 && this._indices) {
  39746. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39747. }
  39748. // Vertex buffers
  39749. for (var key in this._vertexBuffers) {
  39750. var vertexBuffer = this._vertexBuffers[key];
  39751. vertexBuffer._rebuild();
  39752. }
  39753. };
  39754. /**
  39755. * Affects all geometry data in one call
  39756. * @param vertexData defines the geometry data
  39757. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39758. */
  39759. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39760. vertexData.applyToGeometry(this, updatable);
  39761. this.notifyUpdate();
  39762. };
  39763. /**
  39764. * Set specific vertex data
  39765. * @param kind defines the data kind (Position, normal, etc...)
  39766. * @param data defines the vertex data to use
  39767. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39768. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39769. */
  39770. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39771. if (updatable === void 0) { updatable = false; }
  39772. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39773. this.setVerticesBuffer(buffer);
  39774. };
  39775. /**
  39776. * Removes a specific vertex data
  39777. * @param kind defines the data kind (Position, normal, etc...)
  39778. */
  39779. Geometry.prototype.removeVerticesData = function (kind) {
  39780. if (this._vertexBuffers[kind]) {
  39781. this._vertexBuffers[kind].dispose();
  39782. delete this._vertexBuffers[kind];
  39783. }
  39784. };
  39785. /**
  39786. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39787. * @param buffer defines the vertex buffer to use
  39788. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39789. */
  39790. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39791. if (totalVertices === void 0) { totalVertices = null; }
  39792. var kind = buffer.getKind();
  39793. if (this._vertexBuffers[kind]) {
  39794. this._vertexBuffers[kind].dispose();
  39795. }
  39796. this._vertexBuffers[kind] = buffer;
  39797. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39798. var data = buffer.getData();
  39799. if (totalVertices != null) {
  39800. this._totalVertices = totalVertices;
  39801. }
  39802. else {
  39803. if (data != null) {
  39804. this._totalVertices = data.length / (buffer.byteStride / 4);
  39805. }
  39806. }
  39807. this._updateExtend(data);
  39808. this._resetPointsArrayCache();
  39809. var meshes = this._meshes;
  39810. var numOfMeshes = meshes.length;
  39811. for (var index = 0; index < numOfMeshes; index++) {
  39812. var mesh = meshes[index];
  39813. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39814. mesh._createGlobalSubMesh(false);
  39815. mesh.computeWorldMatrix(true);
  39816. }
  39817. }
  39818. this.notifyUpdate(kind);
  39819. if (this._vertexArrayObjects) {
  39820. this._disposeVertexArrayObjects();
  39821. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39822. }
  39823. };
  39824. /**
  39825. * Update a specific vertex buffer
  39826. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39827. * It will do nothing if the buffer is not updatable
  39828. * @param kind defines the data kind (Position, normal, etc...)
  39829. * @param data defines the data to use
  39830. * @param offset defines the offset in the target buffer where to store the data
  39831. * @param useBytes set to true if the offset is in bytes
  39832. */
  39833. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39834. if (useBytes === void 0) { useBytes = false; }
  39835. var vertexBuffer = this.getVertexBuffer(kind);
  39836. if (!vertexBuffer) {
  39837. return;
  39838. }
  39839. vertexBuffer.updateDirectly(data, offset, useBytes);
  39840. this.notifyUpdate(kind);
  39841. };
  39842. /**
  39843. * Update a specific vertex buffer
  39844. * This function will create a new buffer if the current one is not updatable
  39845. * @param kind defines the data kind (Position, normal, etc...)
  39846. * @param data defines the data to use
  39847. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39848. */
  39849. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39850. if (updateExtends === void 0) { updateExtends = false; }
  39851. var vertexBuffer = this.getVertexBuffer(kind);
  39852. if (!vertexBuffer) {
  39853. return;
  39854. }
  39855. vertexBuffer.update(data);
  39856. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39857. this._updateBoundingInfo(updateExtends, data);
  39858. }
  39859. this.notifyUpdate(kind);
  39860. };
  39861. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39862. if (updateExtends) {
  39863. this._updateExtend(data);
  39864. }
  39865. var meshes = this._meshes;
  39866. var numOfMeshes = meshes.length;
  39867. this._resetPointsArrayCache();
  39868. for (var index = 0; index < numOfMeshes; index++) {
  39869. var mesh = meshes[index];
  39870. if (updateExtends) {
  39871. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39872. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39873. var subMesh = mesh.subMeshes[subIndex];
  39874. subMesh.refreshBoundingInfo();
  39875. }
  39876. }
  39877. }
  39878. };
  39879. /** @hidden */
  39880. Geometry.prototype._bind = function (effect, indexToBind) {
  39881. if (!effect) {
  39882. return;
  39883. }
  39884. if (indexToBind === undefined) {
  39885. indexToBind = this._indexBuffer;
  39886. }
  39887. var vbs = this.getVertexBuffers();
  39888. if (!vbs) {
  39889. return;
  39890. }
  39891. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39892. this._engine.bindBuffers(vbs, indexToBind, effect);
  39893. return;
  39894. }
  39895. // Using VAO
  39896. if (!this._vertexArrayObjects[effect.key]) {
  39897. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39898. }
  39899. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39900. };
  39901. /**
  39902. * Gets total number of vertices
  39903. * @returns the total number of vertices
  39904. */
  39905. Geometry.prototype.getTotalVertices = function () {
  39906. if (!this.isReady()) {
  39907. return 0;
  39908. }
  39909. return this._totalVertices;
  39910. };
  39911. /**
  39912. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39913. * @param kind defines the data kind (Position, normal, etc...)
  39914. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39915. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39916. * @returns a float array containing vertex data
  39917. */
  39918. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39919. var vertexBuffer = this.getVertexBuffer(kind);
  39920. if (!vertexBuffer) {
  39921. return null;
  39922. }
  39923. var data = vertexBuffer.getData();
  39924. if (!data) {
  39925. return null;
  39926. }
  39927. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39928. var count = this._totalVertices * vertexBuffer.getSize();
  39929. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39930. var copy_1 = new Array(count);
  39931. vertexBuffer.forEach(count, function (value, index) {
  39932. copy_1[index] = value;
  39933. });
  39934. return copy_1;
  39935. }
  39936. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39937. if (data instanceof Array) {
  39938. var offset = vertexBuffer.byteOffset / 4;
  39939. return BABYLON.Tools.Slice(data, offset, offset + count);
  39940. }
  39941. else if (data instanceof ArrayBuffer) {
  39942. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39943. }
  39944. else {
  39945. var offset = data.byteOffset + vertexBuffer.byteOffset;
  39946. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39947. var result = new Float32Array(count);
  39948. var source = new Float32Array(data.buffer, offset, count);
  39949. result.set(source);
  39950. return result;
  39951. }
  39952. return new Float32Array(data.buffer, offset, count);
  39953. }
  39954. }
  39955. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39956. return BABYLON.Tools.Slice(data);
  39957. }
  39958. return data;
  39959. };
  39960. /**
  39961. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39962. * @param kind defines the data kind (Position, normal, etc...)
  39963. * @returns true if the vertex buffer with the specified kind is updatable
  39964. */
  39965. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39966. var vb = this._vertexBuffers[kind];
  39967. if (!vb) {
  39968. return false;
  39969. }
  39970. return vb.isUpdatable();
  39971. };
  39972. /**
  39973. * Gets a specific vertex buffer
  39974. * @param kind defines the data kind (Position, normal, etc...)
  39975. * @returns a {BABYLON.VertexBuffer}
  39976. */
  39977. Geometry.prototype.getVertexBuffer = function (kind) {
  39978. if (!this.isReady()) {
  39979. return null;
  39980. }
  39981. return this._vertexBuffers[kind];
  39982. };
  39983. /**
  39984. * Returns all vertex buffers
  39985. * @return an object holding all vertex buffers indexed by kind
  39986. */
  39987. Geometry.prototype.getVertexBuffers = function () {
  39988. if (!this.isReady()) {
  39989. return null;
  39990. }
  39991. return this._vertexBuffers;
  39992. };
  39993. /**
  39994. * Gets a boolean indicating if specific vertex buffer is present
  39995. * @param kind defines the data kind (Position, normal, etc...)
  39996. * @returns true if data is present
  39997. */
  39998. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39999. if (!this._vertexBuffers) {
  40000. if (this._delayInfo) {
  40001. return this._delayInfo.indexOf(kind) !== -1;
  40002. }
  40003. return false;
  40004. }
  40005. return this._vertexBuffers[kind] !== undefined;
  40006. };
  40007. /**
  40008. * Gets a list of all attached data kinds (Position, normal, etc...)
  40009. * @returns a list of string containing all kinds
  40010. */
  40011. Geometry.prototype.getVerticesDataKinds = function () {
  40012. var result = [];
  40013. var kind;
  40014. if (!this._vertexBuffers && this._delayInfo) {
  40015. for (kind in this._delayInfo) {
  40016. result.push(kind);
  40017. }
  40018. }
  40019. else {
  40020. for (kind in this._vertexBuffers) {
  40021. result.push(kind);
  40022. }
  40023. }
  40024. return result;
  40025. };
  40026. /**
  40027. * Update index buffer
  40028. * @param indices defines the indices to store in the index buffer
  40029. * @param offset defines the offset in the target buffer where to store the data
  40030. */
  40031. Geometry.prototype.updateIndices = function (indices, offset) {
  40032. if (!this._indexBuffer) {
  40033. return;
  40034. }
  40035. if (!this._indexBufferIsUpdatable) {
  40036. this.setIndices(indices, null, true);
  40037. }
  40038. else {
  40039. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  40040. }
  40041. };
  40042. /**
  40043. * Creates a new index buffer
  40044. * @param indices defines the indices to store in the index buffer
  40045. * @param totalVertices defines the total number of vertices (could be null)
  40046. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  40047. */
  40048. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  40049. if (totalVertices === void 0) { totalVertices = null; }
  40050. if (updatable === void 0) { updatable = false; }
  40051. if (this._indexBuffer) {
  40052. this._engine._releaseBuffer(this._indexBuffer);
  40053. }
  40054. this._disposeVertexArrayObjects();
  40055. this._indices = indices;
  40056. this._indexBufferIsUpdatable = updatable;
  40057. if (this._meshes.length !== 0 && this._indices) {
  40058. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  40059. }
  40060. if (totalVertices != undefined) { // including null and undefined
  40061. this._totalVertices = totalVertices;
  40062. }
  40063. var meshes = this._meshes;
  40064. var numOfMeshes = meshes.length;
  40065. for (var index = 0; index < numOfMeshes; index++) {
  40066. meshes[index]._createGlobalSubMesh(true);
  40067. }
  40068. this.notifyUpdate();
  40069. };
  40070. /**
  40071. * Return the total number of indices
  40072. * @returns the total number of indices
  40073. */
  40074. Geometry.prototype.getTotalIndices = function () {
  40075. if (!this.isReady()) {
  40076. return 0;
  40077. }
  40078. return this._indices.length;
  40079. };
  40080. /**
  40081. * Gets the index buffer array
  40082. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40083. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40084. * @returns the index buffer array
  40085. */
  40086. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  40087. if (!this.isReady()) {
  40088. return null;
  40089. }
  40090. var orig = this._indices;
  40091. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  40092. return orig;
  40093. }
  40094. else {
  40095. var len = orig.length;
  40096. var copy = [];
  40097. for (var i = 0; i < len; i++) {
  40098. copy.push(orig[i]);
  40099. }
  40100. return copy;
  40101. }
  40102. };
  40103. /**
  40104. * Gets the index buffer
  40105. * @return the index buffer
  40106. */
  40107. Geometry.prototype.getIndexBuffer = function () {
  40108. if (!this.isReady()) {
  40109. return null;
  40110. }
  40111. return this._indexBuffer;
  40112. };
  40113. /** @hidden */
  40114. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  40115. if (effect === void 0) { effect = null; }
  40116. if (!effect || !this._vertexArrayObjects) {
  40117. return;
  40118. }
  40119. if (this._vertexArrayObjects[effect.key]) {
  40120. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  40121. delete this._vertexArrayObjects[effect.key];
  40122. }
  40123. };
  40124. /**
  40125. * Release the associated resources for a specific mesh
  40126. * @param mesh defines the source mesh
  40127. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  40128. */
  40129. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  40130. var meshes = this._meshes;
  40131. var index = meshes.indexOf(mesh);
  40132. if (index === -1) {
  40133. return;
  40134. }
  40135. meshes.splice(index, 1);
  40136. mesh._geometry = null;
  40137. if (meshes.length === 0 && shouldDispose) {
  40138. this.dispose();
  40139. }
  40140. };
  40141. /**
  40142. * Apply current geometry to a given mesh
  40143. * @param mesh defines the mesh to apply geometry to
  40144. */
  40145. Geometry.prototype.applyToMesh = function (mesh) {
  40146. if (mesh._geometry === this) {
  40147. return;
  40148. }
  40149. var previousGeometry = mesh._geometry;
  40150. if (previousGeometry) {
  40151. previousGeometry.releaseForMesh(mesh);
  40152. }
  40153. var meshes = this._meshes;
  40154. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  40155. mesh._geometry = this;
  40156. this._scene.pushGeometry(this);
  40157. meshes.push(mesh);
  40158. if (this.isReady()) {
  40159. this._applyToMesh(mesh);
  40160. }
  40161. else {
  40162. mesh._boundingInfo = this._boundingInfo;
  40163. }
  40164. };
  40165. Geometry.prototype._updateExtend = function (data) {
  40166. if (data === void 0) { data = null; }
  40167. if (!data) {
  40168. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40169. }
  40170. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  40171. };
  40172. Geometry.prototype._applyToMesh = function (mesh) {
  40173. var numOfMeshes = this._meshes.length;
  40174. // vertexBuffers
  40175. for (var kind in this._vertexBuffers) {
  40176. if (numOfMeshes === 1) {
  40177. this._vertexBuffers[kind].create();
  40178. }
  40179. var buffer = this._vertexBuffers[kind].getBuffer();
  40180. if (buffer)
  40181. buffer.references = numOfMeshes;
  40182. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40183. if (!this._extend) {
  40184. this._updateExtend();
  40185. }
  40186. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40187. mesh._createGlobalSubMesh(false);
  40188. //bounding info was just created again, world matrix should be applied again.
  40189. mesh._updateBoundingInfo();
  40190. }
  40191. }
  40192. // indexBuffer
  40193. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  40194. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40195. }
  40196. if (this._indexBuffer) {
  40197. this._indexBuffer.references = numOfMeshes;
  40198. }
  40199. };
  40200. Geometry.prototype.notifyUpdate = function (kind) {
  40201. if (this.onGeometryUpdated) {
  40202. this.onGeometryUpdated(this, kind);
  40203. }
  40204. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  40205. var mesh = _a[_i];
  40206. mesh._markSubMeshesAsAttributesDirty();
  40207. }
  40208. };
  40209. /**
  40210. * Load the geometry if it was flagged as delay loaded
  40211. * @param scene defines the hosting scene
  40212. * @param onLoaded defines a callback called when the geometry is loaded
  40213. */
  40214. Geometry.prototype.load = function (scene, onLoaded) {
  40215. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  40216. return;
  40217. }
  40218. if (this.isReady()) {
  40219. if (onLoaded) {
  40220. onLoaded();
  40221. }
  40222. return;
  40223. }
  40224. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  40225. this._queueLoad(scene, onLoaded);
  40226. };
  40227. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  40228. var _this = this;
  40229. if (!this.delayLoadingFile) {
  40230. return;
  40231. }
  40232. scene._addPendingData(this);
  40233. scene._loadFile(this.delayLoadingFile, function (data) {
  40234. if (!_this._delayLoadingFunction) {
  40235. return;
  40236. }
  40237. _this._delayLoadingFunction(JSON.parse(data), _this);
  40238. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40239. _this._delayInfo = [];
  40240. scene._removePendingData(_this);
  40241. var meshes = _this._meshes;
  40242. var numOfMeshes = meshes.length;
  40243. for (var index = 0; index < numOfMeshes; index++) {
  40244. _this._applyToMesh(meshes[index]);
  40245. }
  40246. if (onLoaded) {
  40247. onLoaded();
  40248. }
  40249. }, undefined, true);
  40250. };
  40251. /**
  40252. * Invert the geometry to move from a right handed system to a left handed one.
  40253. */
  40254. Geometry.prototype.toLeftHanded = function () {
  40255. // Flip faces
  40256. var tIndices = this.getIndices(false);
  40257. if (tIndices != null && tIndices.length > 0) {
  40258. for (var i = 0; i < tIndices.length; i += 3) {
  40259. var tTemp = tIndices[i + 0];
  40260. tIndices[i + 0] = tIndices[i + 2];
  40261. tIndices[i + 2] = tTemp;
  40262. }
  40263. this.setIndices(tIndices);
  40264. }
  40265. // Negate position.z
  40266. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  40267. if (tPositions != null && tPositions.length > 0) {
  40268. for (var i = 0; i < tPositions.length; i += 3) {
  40269. tPositions[i + 2] = -tPositions[i + 2];
  40270. }
  40271. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  40272. }
  40273. // Negate normal.z
  40274. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  40275. if (tNormals != null && tNormals.length > 0) {
  40276. for (var i = 0; i < tNormals.length; i += 3) {
  40277. tNormals[i + 2] = -tNormals[i + 2];
  40278. }
  40279. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  40280. }
  40281. };
  40282. // Cache
  40283. /** @hidden */
  40284. Geometry.prototype._resetPointsArrayCache = function () {
  40285. this._positions = null;
  40286. };
  40287. /** @hidden */
  40288. Geometry.prototype._generatePointsArray = function () {
  40289. if (this._positions)
  40290. return true;
  40291. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40292. if (!data || data.length === 0) {
  40293. return false;
  40294. }
  40295. this._positions = [];
  40296. for (var index = 0; index < data.length; index += 3) {
  40297. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  40298. }
  40299. return true;
  40300. };
  40301. /**
  40302. * Gets a value indicating if the geometry is disposed
  40303. * @returns true if the geometry was disposed
  40304. */
  40305. Geometry.prototype.isDisposed = function () {
  40306. return this._isDisposed;
  40307. };
  40308. Geometry.prototype._disposeVertexArrayObjects = function () {
  40309. if (this._vertexArrayObjects) {
  40310. for (var kind in this._vertexArrayObjects) {
  40311. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  40312. }
  40313. this._vertexArrayObjects = {};
  40314. }
  40315. };
  40316. /**
  40317. * Free all associated resources
  40318. */
  40319. Geometry.prototype.dispose = function () {
  40320. var meshes = this._meshes;
  40321. var numOfMeshes = meshes.length;
  40322. var index;
  40323. for (index = 0; index < numOfMeshes; index++) {
  40324. this.releaseForMesh(meshes[index]);
  40325. }
  40326. this._meshes = [];
  40327. this._disposeVertexArrayObjects();
  40328. for (var kind in this._vertexBuffers) {
  40329. this._vertexBuffers[kind].dispose();
  40330. }
  40331. this._vertexBuffers = {};
  40332. this._totalVertices = 0;
  40333. if (this._indexBuffer) {
  40334. this._engine._releaseBuffer(this._indexBuffer);
  40335. }
  40336. this._indexBuffer = null;
  40337. this._indices = [];
  40338. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40339. this.delayLoadingFile = null;
  40340. this._delayLoadingFunction = null;
  40341. this._delayInfo = [];
  40342. this._boundingInfo = null;
  40343. this._scene.removeGeometry(this);
  40344. this._isDisposed = true;
  40345. };
  40346. /**
  40347. * Clone the current geometry into a new geometry
  40348. * @param id defines the unique ID of the new geometry
  40349. * @returns a new geometry object
  40350. */
  40351. Geometry.prototype.copy = function (id) {
  40352. var vertexData = new BABYLON.VertexData();
  40353. vertexData.indices = [];
  40354. var indices = this.getIndices();
  40355. if (indices) {
  40356. for (var index = 0; index < indices.length; index++) {
  40357. vertexData.indices.push(indices[index]);
  40358. }
  40359. }
  40360. var updatable = false;
  40361. var stopChecking = false;
  40362. var kind;
  40363. for (kind in this._vertexBuffers) {
  40364. // using slice() to make a copy of the array and not just reference it
  40365. var data = this.getVerticesData(kind);
  40366. if (data instanceof Float32Array) {
  40367. vertexData.set(new Float32Array(data), kind);
  40368. }
  40369. else {
  40370. vertexData.set(data.slice(0), kind);
  40371. }
  40372. if (!stopChecking) {
  40373. var vb = this.getVertexBuffer(kind);
  40374. if (vb) {
  40375. updatable = vb.isUpdatable();
  40376. stopChecking = !updatable;
  40377. }
  40378. }
  40379. }
  40380. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  40381. geometry.delayLoadState = this.delayLoadState;
  40382. geometry.delayLoadingFile = this.delayLoadingFile;
  40383. geometry._delayLoadingFunction = this._delayLoadingFunction;
  40384. for (kind in this._delayInfo) {
  40385. geometry._delayInfo = geometry._delayInfo || [];
  40386. geometry._delayInfo.push(kind);
  40387. }
  40388. // Bounding info
  40389. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40390. return geometry;
  40391. };
  40392. /**
  40393. * Serialize the current geometry info (and not the vertices data) into a JSON object
  40394. * @return a JSON representation of the current geometry data (without the vertices data)
  40395. */
  40396. Geometry.prototype.serialize = function () {
  40397. var serializationObject = {};
  40398. serializationObject.id = this.id;
  40399. serializationObject.updatable = this._updatable;
  40400. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  40401. serializationObject.tags = BABYLON.Tags.GetTags(this);
  40402. }
  40403. return serializationObject;
  40404. };
  40405. Geometry.prototype.toNumberArray = function (origin) {
  40406. if (Array.isArray(origin)) {
  40407. return origin;
  40408. }
  40409. else {
  40410. return Array.prototype.slice.call(origin);
  40411. }
  40412. };
  40413. /**
  40414. * Serialize all vertices data into a JSON oject
  40415. * @returns a JSON representation of the current geometry data
  40416. */
  40417. Geometry.prototype.serializeVerticeData = function () {
  40418. var serializationObject = this.serialize();
  40419. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  40420. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  40421. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  40422. serializationObject.positions._updatable = true;
  40423. }
  40424. }
  40425. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40426. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  40427. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  40428. serializationObject.normals._updatable = true;
  40429. }
  40430. }
  40431. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40432. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  40433. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  40434. serializationObject.tangets._updatable = true;
  40435. }
  40436. }
  40437. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40438. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  40439. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  40440. serializationObject.uvs._updatable = true;
  40441. }
  40442. }
  40443. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  40444. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  40445. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  40446. serializationObject.uv2s._updatable = true;
  40447. }
  40448. }
  40449. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  40450. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  40451. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  40452. serializationObject.uv3s._updatable = true;
  40453. }
  40454. }
  40455. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  40456. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  40457. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  40458. serializationObject.uv4s._updatable = true;
  40459. }
  40460. }
  40461. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  40462. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  40463. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  40464. serializationObject.uv5s._updatable = true;
  40465. }
  40466. }
  40467. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  40468. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  40469. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  40470. serializationObject.uv6s._updatable = true;
  40471. }
  40472. }
  40473. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  40474. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  40475. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  40476. serializationObject.colors._updatable = true;
  40477. }
  40478. }
  40479. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40480. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  40481. serializationObject.matricesIndices._isExpanded = true;
  40482. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40483. serializationObject.matricesIndices._updatable = true;
  40484. }
  40485. }
  40486. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40487. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  40488. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40489. serializationObject.matricesWeights._updatable = true;
  40490. }
  40491. }
  40492. serializationObject.indices = this.toNumberArray(this.getIndices());
  40493. return serializationObject;
  40494. };
  40495. // Statics
  40496. /**
  40497. * Extracts a clone of a mesh geometry
  40498. * @param mesh defines the source mesh
  40499. * @param id defines the unique ID of the new geometry object
  40500. * @returns the new geometry object
  40501. */
  40502. Geometry.ExtractFromMesh = function (mesh, id) {
  40503. var geometry = mesh._geometry;
  40504. if (!geometry) {
  40505. return null;
  40506. }
  40507. return geometry.copy(id);
  40508. };
  40509. /**
  40510. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  40511. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  40512. * Be aware Math.random() could cause collisions, but:
  40513. * "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"
  40514. * @returns a string containing a new GUID
  40515. */
  40516. Geometry.RandomId = function () {
  40517. return BABYLON.Tools.RandomId();
  40518. };
  40519. /** @hidden */
  40520. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  40521. var scene = mesh.getScene();
  40522. // Geometry
  40523. var geometryId = parsedGeometry.geometryId;
  40524. if (geometryId) {
  40525. var geometry = scene.getGeometryByID(geometryId);
  40526. if (geometry) {
  40527. geometry.applyToMesh(mesh);
  40528. }
  40529. }
  40530. else if (parsedGeometry instanceof ArrayBuffer) {
  40531. var binaryInfo = mesh._binaryInfo;
  40532. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  40533. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  40534. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  40535. }
  40536. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  40537. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  40538. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  40539. }
  40540. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  40541. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  40542. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  40543. }
  40544. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  40545. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  40546. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  40547. }
  40548. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  40549. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  40550. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  40551. }
  40552. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  40553. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  40554. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  40555. }
  40556. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  40557. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  40558. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  40559. }
  40560. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  40561. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  40562. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  40563. }
  40564. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  40565. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  40566. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  40567. }
  40568. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  40569. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  40570. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  40571. }
  40572. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  40573. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  40574. var floatIndices = [];
  40575. for (var i = 0; i < matricesIndicesData.length; i++) {
  40576. var index = matricesIndicesData[i];
  40577. floatIndices.push(index & 0x000000FF);
  40578. floatIndices.push((index & 0x0000FF00) >> 8);
  40579. floatIndices.push((index & 0x00FF0000) >> 16);
  40580. floatIndices.push(index >> 24);
  40581. }
  40582. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  40583. }
  40584. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40585. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40586. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40587. }
  40588. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40589. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40590. mesh.setIndices(indicesData, null);
  40591. }
  40592. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40593. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40594. mesh.subMeshes = [];
  40595. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40596. var materialIndex = subMeshesData[(i * 5) + 0];
  40597. var verticesStart = subMeshesData[(i * 5) + 1];
  40598. var verticesCount = subMeshesData[(i * 5) + 2];
  40599. var indexStart = subMeshesData[(i * 5) + 3];
  40600. var indexCount = subMeshesData[(i * 5) + 4];
  40601. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40602. }
  40603. }
  40604. }
  40605. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40606. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40607. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40608. if (parsedGeometry.tangents) {
  40609. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40610. }
  40611. if (parsedGeometry.uvs) {
  40612. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40613. }
  40614. if (parsedGeometry.uvs2) {
  40615. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40616. }
  40617. if (parsedGeometry.uvs3) {
  40618. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40619. }
  40620. if (parsedGeometry.uvs4) {
  40621. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40622. }
  40623. if (parsedGeometry.uvs5) {
  40624. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40625. }
  40626. if (parsedGeometry.uvs6) {
  40627. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40628. }
  40629. if (parsedGeometry.colors) {
  40630. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40631. }
  40632. if (parsedGeometry.matricesIndices) {
  40633. if (!parsedGeometry.matricesIndices._isExpanded) {
  40634. var floatIndices = [];
  40635. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40636. var matricesIndex = parsedGeometry.matricesIndices[i];
  40637. floatIndices.push(matricesIndex & 0x000000FF);
  40638. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40639. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40640. floatIndices.push(matricesIndex >> 24);
  40641. }
  40642. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40643. }
  40644. else {
  40645. delete parsedGeometry.matricesIndices._isExpanded;
  40646. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40647. }
  40648. }
  40649. if (parsedGeometry.matricesIndicesExtra) {
  40650. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40651. var floatIndices = [];
  40652. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40653. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40654. floatIndices.push(matricesIndex & 0x000000FF);
  40655. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40656. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40657. floatIndices.push(matricesIndex >> 24);
  40658. }
  40659. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40660. }
  40661. else {
  40662. delete parsedGeometry.matricesIndices._isExpanded;
  40663. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40664. }
  40665. }
  40666. if (parsedGeometry.matricesWeights) {
  40667. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40668. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40669. }
  40670. if (parsedGeometry.matricesWeightsExtra) {
  40671. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40672. }
  40673. mesh.setIndices(parsedGeometry.indices, null);
  40674. }
  40675. // SubMeshes
  40676. if (parsedGeometry.subMeshes) {
  40677. mesh.subMeshes = [];
  40678. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40679. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40680. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40681. }
  40682. }
  40683. // Flat shading
  40684. if (mesh._shouldGenerateFlatShading) {
  40685. mesh.convertToFlatShadedMesh();
  40686. delete mesh._shouldGenerateFlatShading;
  40687. }
  40688. // Update
  40689. mesh.computeWorldMatrix(true);
  40690. scene.onMeshImportedObservable.notifyObservers(mesh);
  40691. };
  40692. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40693. var epsilon = 1e-3;
  40694. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40695. return;
  40696. }
  40697. var noInfluenceBoneIndex = 0.0;
  40698. if (parsedGeometry.skeletonId > -1) {
  40699. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40700. if (!skeleton) {
  40701. return;
  40702. }
  40703. noInfluenceBoneIndex = skeleton.bones.length;
  40704. }
  40705. else {
  40706. return;
  40707. }
  40708. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40709. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40710. var matricesWeights = parsedGeometry.matricesWeights;
  40711. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40712. var influencers = parsedGeometry.numBoneInfluencer;
  40713. var size = matricesWeights.length;
  40714. for (var i = 0; i < size; i += 4) {
  40715. var weight = 0.0;
  40716. var firstZeroWeight = -1;
  40717. for (var j = 0; j < 4; j++) {
  40718. var w = matricesWeights[i + j];
  40719. weight += w;
  40720. if (w < epsilon && firstZeroWeight < 0) {
  40721. firstZeroWeight = j;
  40722. }
  40723. }
  40724. if (matricesWeightsExtra) {
  40725. for (var j = 0; j < 4; j++) {
  40726. var w = matricesWeightsExtra[i + j];
  40727. weight += w;
  40728. if (w < epsilon && firstZeroWeight < 0) {
  40729. firstZeroWeight = j + 4;
  40730. }
  40731. }
  40732. }
  40733. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40734. firstZeroWeight = influencers - 1;
  40735. }
  40736. if (weight > epsilon) {
  40737. var mweight = 1.0 / weight;
  40738. for (var j = 0; j < 4; j++) {
  40739. matricesWeights[i + j] *= mweight;
  40740. }
  40741. if (matricesWeightsExtra) {
  40742. for (var j = 0; j < 4; j++) {
  40743. matricesWeightsExtra[i + j] *= mweight;
  40744. }
  40745. }
  40746. }
  40747. else {
  40748. if (firstZeroWeight >= 4) {
  40749. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40750. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40751. }
  40752. else {
  40753. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40754. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40755. }
  40756. }
  40757. }
  40758. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40759. if (parsedGeometry.matricesWeightsExtra) {
  40760. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40761. }
  40762. };
  40763. /**
  40764. * Create a new geometry from persisted data (Using .babylon file format)
  40765. * @param parsedVertexData defines the persisted data
  40766. * @param scene defines the hosting scene
  40767. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40768. * @returns the new geometry object
  40769. */
  40770. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40771. if (scene.getGeometryByID(parsedVertexData.id)) {
  40772. return null; // null since geometry could be something else than a box...
  40773. }
  40774. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40775. if (BABYLON.Tags) {
  40776. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40777. }
  40778. if (parsedVertexData.delayLoadingFile) {
  40779. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40780. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40781. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40782. geometry._delayInfo = [];
  40783. if (parsedVertexData.hasUVs) {
  40784. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40785. }
  40786. if (parsedVertexData.hasUVs2) {
  40787. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40788. }
  40789. if (parsedVertexData.hasUVs3) {
  40790. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40791. }
  40792. if (parsedVertexData.hasUVs4) {
  40793. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40794. }
  40795. if (parsedVertexData.hasUVs5) {
  40796. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40797. }
  40798. if (parsedVertexData.hasUVs6) {
  40799. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40800. }
  40801. if (parsedVertexData.hasColors) {
  40802. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40803. }
  40804. if (parsedVertexData.hasMatricesIndices) {
  40805. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40806. }
  40807. if (parsedVertexData.hasMatricesWeights) {
  40808. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40809. }
  40810. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40811. }
  40812. else {
  40813. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40814. }
  40815. scene.pushGeometry(geometry, true);
  40816. return geometry;
  40817. };
  40818. return Geometry;
  40819. }());
  40820. BABYLON.Geometry = Geometry;
  40821. // Primitives
  40822. /// Abstract class
  40823. /**
  40824. * Abstract class used to provide common services for all typed geometries
  40825. * @hidden
  40826. */
  40827. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40828. __extends(_PrimitiveGeometry, _super);
  40829. /**
  40830. * Creates a new typed geometry
  40831. * @param id defines the unique ID of the geometry
  40832. * @param scene defines the hosting scene
  40833. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40834. * @param mesh defines the hosting mesh (can be null)
  40835. */
  40836. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40837. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40838. if (mesh === void 0) { mesh = null; }
  40839. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40840. _this._canBeRegenerated = _canBeRegenerated;
  40841. _this._beingRegenerated = true;
  40842. _this.regenerate();
  40843. _this._beingRegenerated = false;
  40844. return _this;
  40845. }
  40846. /**
  40847. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40848. * @returns true if the geometry can be regenerated
  40849. */
  40850. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40851. return this._canBeRegenerated;
  40852. };
  40853. /**
  40854. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40855. */
  40856. _PrimitiveGeometry.prototype.regenerate = function () {
  40857. if (!this._canBeRegenerated) {
  40858. return;
  40859. }
  40860. this._beingRegenerated = true;
  40861. this.setAllVerticesData(this._regenerateVertexData(), false);
  40862. this._beingRegenerated = false;
  40863. };
  40864. /**
  40865. * Clone the geometry
  40866. * @param id defines the unique ID of the new geometry
  40867. * @returns the new geometry
  40868. */
  40869. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40870. return _super.prototype.copy.call(this, id);
  40871. };
  40872. // overrides
  40873. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40874. if (!this._beingRegenerated) {
  40875. return;
  40876. }
  40877. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40878. };
  40879. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40880. if (!this._beingRegenerated) {
  40881. return;
  40882. }
  40883. _super.prototype.setVerticesData.call(this, kind, data, false);
  40884. };
  40885. // to override
  40886. /** @hidden */
  40887. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40888. throw new Error("Abstract method");
  40889. };
  40890. _PrimitiveGeometry.prototype.copy = function (id) {
  40891. throw new Error("Must be overriden in sub-classes.");
  40892. };
  40893. _PrimitiveGeometry.prototype.serialize = function () {
  40894. var serializationObject = _super.prototype.serialize.call(this);
  40895. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40896. return serializationObject;
  40897. };
  40898. return _PrimitiveGeometry;
  40899. }(Geometry));
  40900. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40901. /**
  40902. * Creates a ribbon geometry
  40903. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40904. */
  40905. var RibbonGeometry = /** @class */ (function (_super) {
  40906. __extends(RibbonGeometry, _super);
  40907. /**
  40908. * Creates a ribbon geometry
  40909. * @param id defines the unique ID of the geometry
  40910. * @param scene defines the hosting scene
  40911. * @param pathArray defines the array of paths to use
  40912. * @param closeArray defines if the last path and the first path must be joined
  40913. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40914. * @param offset defines the offset between points
  40915. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40916. * @param mesh defines the hosting mesh (can be null)
  40917. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40918. */
  40919. function RibbonGeometry(id, scene,
  40920. /**
  40921. * Defines the array of paths to use
  40922. */
  40923. pathArray,
  40924. /**
  40925. * Defines if the last and first points of each path in your pathArray must be joined
  40926. */
  40927. closeArray,
  40928. /**
  40929. * Defines if the last and first points of each path in your pathArray must be joined
  40930. */
  40931. closePath,
  40932. /**
  40933. * Defines the offset between points
  40934. */
  40935. offset, canBeRegenerated, mesh,
  40936. /**
  40937. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40938. */
  40939. side) {
  40940. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40941. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40942. _this.pathArray = pathArray;
  40943. _this.closeArray = closeArray;
  40944. _this.closePath = closePath;
  40945. _this.offset = offset;
  40946. _this.side = side;
  40947. return _this;
  40948. }
  40949. /** @hidden */
  40950. RibbonGeometry.prototype._regenerateVertexData = function () {
  40951. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40952. };
  40953. RibbonGeometry.prototype.copy = function (id) {
  40954. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40955. };
  40956. return RibbonGeometry;
  40957. }(_PrimitiveGeometry));
  40958. BABYLON.RibbonGeometry = RibbonGeometry;
  40959. /**
  40960. * Creates a box geometry
  40961. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40962. */
  40963. var BoxGeometry = /** @class */ (function (_super) {
  40964. __extends(BoxGeometry, _super);
  40965. /**
  40966. * Creates a box geometry
  40967. * @param id defines the unique ID of the geometry
  40968. * @param scene defines the hosting scene
  40969. * @param size defines the zise of the box (width, height and depth are the same)
  40970. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40971. * @param mesh defines the hosting mesh (can be null)
  40972. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40973. */
  40974. function BoxGeometry(id, scene,
  40975. /**
  40976. * Defines the zise of the box (width, height and depth are the same)
  40977. */
  40978. size, canBeRegenerated, mesh,
  40979. /**
  40980. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40981. */
  40982. side) {
  40983. if (mesh === void 0) { mesh = null; }
  40984. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40985. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40986. _this.size = size;
  40987. _this.side = side;
  40988. return _this;
  40989. }
  40990. /** @hidden */
  40991. BoxGeometry.prototype._regenerateVertexData = function () {
  40992. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40993. };
  40994. BoxGeometry.prototype.copy = function (id) {
  40995. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40996. };
  40997. BoxGeometry.prototype.serialize = function () {
  40998. var serializationObject = _super.prototype.serialize.call(this);
  40999. serializationObject.size = this.size;
  41000. return serializationObject;
  41001. };
  41002. BoxGeometry.Parse = function (parsedBox, scene) {
  41003. if (scene.getGeometryByID(parsedBox.id)) {
  41004. return null; // null since geometry could be something else than a box...
  41005. }
  41006. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  41007. if (BABYLON.Tags) {
  41008. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  41009. }
  41010. scene.pushGeometry(box, true);
  41011. return box;
  41012. };
  41013. return BoxGeometry;
  41014. }(_PrimitiveGeometry));
  41015. BABYLON.BoxGeometry = BoxGeometry;
  41016. /**
  41017. * Creates a sphere geometry
  41018. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  41019. */
  41020. var SphereGeometry = /** @class */ (function (_super) {
  41021. __extends(SphereGeometry, _super);
  41022. /**
  41023. * Create a new sphere geometry
  41024. * @param id defines the unique ID of the geometry
  41025. * @param scene defines the hosting scene
  41026. * @param segments defines the number of segments to use to create the sphere
  41027. * @param diameter defines the diameter of the sphere
  41028. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41029. * @param mesh defines the hosting mesh (can be null)
  41030. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41031. */
  41032. function SphereGeometry(id, scene,
  41033. /**
  41034. * Defines the number of segments to use to create the sphere
  41035. */
  41036. segments,
  41037. /**
  41038. * Defines the diameter of the sphere
  41039. */
  41040. diameter, canBeRegenerated, mesh,
  41041. /**
  41042. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41043. */
  41044. side) {
  41045. if (mesh === void 0) { mesh = null; }
  41046. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41047. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41048. _this.segments = segments;
  41049. _this.diameter = diameter;
  41050. _this.side = side;
  41051. return _this;
  41052. }
  41053. /** @hidden */
  41054. SphereGeometry.prototype._regenerateVertexData = function () {
  41055. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  41056. };
  41057. SphereGeometry.prototype.copy = function (id) {
  41058. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  41059. };
  41060. SphereGeometry.prototype.serialize = function () {
  41061. var serializationObject = _super.prototype.serialize.call(this);
  41062. serializationObject.segments = this.segments;
  41063. serializationObject.diameter = this.diameter;
  41064. return serializationObject;
  41065. };
  41066. SphereGeometry.Parse = function (parsedSphere, scene) {
  41067. if (scene.getGeometryByID(parsedSphere.id)) {
  41068. return null; // null since geometry could be something else than a sphere...
  41069. }
  41070. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  41071. if (BABYLON.Tags) {
  41072. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  41073. }
  41074. scene.pushGeometry(sphere, true);
  41075. return sphere;
  41076. };
  41077. return SphereGeometry;
  41078. }(_PrimitiveGeometry));
  41079. BABYLON.SphereGeometry = SphereGeometry;
  41080. /**
  41081. * Creates a disc geometry
  41082. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  41083. */
  41084. var DiscGeometry = /** @class */ (function (_super) {
  41085. __extends(DiscGeometry, _super);
  41086. /**
  41087. * Creates a new disc geometry
  41088. * @param id defines the unique ID of the geometry
  41089. * @param scene defines the hosting scene
  41090. * @param radius defines the radius of the disc
  41091. * @param tessellation defines the tesselation factor to apply to the disc
  41092. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41093. * @param mesh defines the hosting mesh (can be null)
  41094. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41095. */
  41096. function DiscGeometry(id, scene,
  41097. /**
  41098. * Defines the radius of the disc
  41099. */
  41100. radius,
  41101. /**
  41102. * Defines the tesselation factor to apply to the disc
  41103. */
  41104. tessellation, canBeRegenerated, mesh,
  41105. /**
  41106. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41107. */
  41108. side) {
  41109. if (mesh === void 0) { mesh = null; }
  41110. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41111. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41112. _this.radius = radius;
  41113. _this.tessellation = tessellation;
  41114. _this.side = side;
  41115. return _this;
  41116. }
  41117. /** @hidden */
  41118. DiscGeometry.prototype._regenerateVertexData = function () {
  41119. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  41120. };
  41121. DiscGeometry.prototype.copy = function (id) {
  41122. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  41123. };
  41124. return DiscGeometry;
  41125. }(_PrimitiveGeometry));
  41126. BABYLON.DiscGeometry = DiscGeometry;
  41127. /**
  41128. * Creates a new cylinder geometry
  41129. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  41130. */
  41131. var CylinderGeometry = /** @class */ (function (_super) {
  41132. __extends(CylinderGeometry, _super);
  41133. /**
  41134. * Creates a new cylinder geometry
  41135. * @param id defines the unique ID of the geometry
  41136. * @param scene defines the hosting scene
  41137. * @param height defines the height of the cylinder
  41138. * @param diameterTop defines the diameter of the cylinder's top cap
  41139. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  41140. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  41141. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  41142. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41143. * @param mesh defines the hosting mesh (can be null)
  41144. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41145. */
  41146. function CylinderGeometry(id, scene,
  41147. /**
  41148. * Defines the height of the cylinder
  41149. */
  41150. height,
  41151. /**
  41152. * Defines the diameter of the cylinder's top cap
  41153. */
  41154. diameterTop,
  41155. /**
  41156. * Defines the diameter of the cylinder's bottom cap
  41157. */
  41158. diameterBottom,
  41159. /**
  41160. * Defines the tessellation factor to apply to the cylinder
  41161. */
  41162. tessellation,
  41163. /**
  41164. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  41165. */
  41166. subdivisions, canBeRegenerated, mesh,
  41167. /**
  41168. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41169. */
  41170. side) {
  41171. if (subdivisions === void 0) { subdivisions = 1; }
  41172. if (mesh === void 0) { mesh = null; }
  41173. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41174. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41175. _this.height = height;
  41176. _this.diameterTop = diameterTop;
  41177. _this.diameterBottom = diameterBottom;
  41178. _this.tessellation = tessellation;
  41179. _this.subdivisions = subdivisions;
  41180. _this.side = side;
  41181. return _this;
  41182. }
  41183. /** @hidden */
  41184. CylinderGeometry.prototype._regenerateVertexData = function () {
  41185. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  41186. };
  41187. CylinderGeometry.prototype.copy = function (id) {
  41188. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  41189. };
  41190. CylinderGeometry.prototype.serialize = function () {
  41191. var serializationObject = _super.prototype.serialize.call(this);
  41192. serializationObject.height = this.height;
  41193. serializationObject.diameterTop = this.diameterTop;
  41194. serializationObject.diameterBottom = this.diameterBottom;
  41195. serializationObject.tessellation = this.tessellation;
  41196. return serializationObject;
  41197. };
  41198. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  41199. if (scene.getGeometryByID(parsedCylinder.id)) {
  41200. return null; // null since geometry could be something else than a cylinder...
  41201. }
  41202. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  41203. if (BABYLON.Tags) {
  41204. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  41205. }
  41206. scene.pushGeometry(cylinder, true);
  41207. return cylinder;
  41208. };
  41209. return CylinderGeometry;
  41210. }(_PrimitiveGeometry));
  41211. BABYLON.CylinderGeometry = CylinderGeometry;
  41212. /**
  41213. * Creates a new torus geometry
  41214. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  41215. */
  41216. var TorusGeometry = /** @class */ (function (_super) {
  41217. __extends(TorusGeometry, _super);
  41218. /**
  41219. * Creates a new torus geometry
  41220. * @param id defines the unique ID of the geometry
  41221. * @param scene defines the hosting scene
  41222. * @param diameter defines the diameter of the torus
  41223. * @param thickness defines the thickness of the torus (ie. internal diameter)
  41224. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  41225. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41226. * @param mesh defines the hosting mesh (can be null)
  41227. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41228. */
  41229. function TorusGeometry(id, scene,
  41230. /**
  41231. * Defines the diameter of the torus
  41232. */
  41233. diameter,
  41234. /**
  41235. * Defines the thickness of the torus (ie. internal diameter)
  41236. */
  41237. thickness,
  41238. /**
  41239. * Defines the tesselation factor to apply to the torus
  41240. */
  41241. tessellation, canBeRegenerated, mesh,
  41242. /**
  41243. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41244. */
  41245. side) {
  41246. if (mesh === void 0) { mesh = null; }
  41247. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41248. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41249. _this.diameter = diameter;
  41250. _this.thickness = thickness;
  41251. _this.tessellation = tessellation;
  41252. _this.side = side;
  41253. return _this;
  41254. }
  41255. /** @hidden */
  41256. TorusGeometry.prototype._regenerateVertexData = function () {
  41257. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  41258. };
  41259. TorusGeometry.prototype.copy = function (id) {
  41260. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  41261. };
  41262. TorusGeometry.prototype.serialize = function () {
  41263. var serializationObject = _super.prototype.serialize.call(this);
  41264. serializationObject.diameter = this.diameter;
  41265. serializationObject.thickness = this.thickness;
  41266. serializationObject.tessellation = this.tessellation;
  41267. return serializationObject;
  41268. };
  41269. TorusGeometry.Parse = function (parsedTorus, scene) {
  41270. if (scene.getGeometryByID(parsedTorus.id)) {
  41271. return null; // null since geometry could be something else than a torus...
  41272. }
  41273. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  41274. if (BABYLON.Tags) {
  41275. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  41276. }
  41277. scene.pushGeometry(torus, true);
  41278. return torus;
  41279. };
  41280. return TorusGeometry;
  41281. }(_PrimitiveGeometry));
  41282. BABYLON.TorusGeometry = TorusGeometry;
  41283. /**
  41284. * Creates a new ground geometry
  41285. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  41286. */
  41287. var GroundGeometry = /** @class */ (function (_super) {
  41288. __extends(GroundGeometry, _super);
  41289. /**
  41290. * Creates a new ground geometry
  41291. * @param id defines the unique ID of the geometry
  41292. * @param scene defines the hosting scene
  41293. * @param width defines the width of the ground
  41294. * @param height defines the height of the ground
  41295. * @param subdivisions defines the subdivisions to apply to the ground
  41296. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41297. * @param mesh defines the hosting mesh (can be null)
  41298. */
  41299. function GroundGeometry(id, scene,
  41300. /**
  41301. * Defines the width of the ground
  41302. */
  41303. width,
  41304. /**
  41305. * Defines the height of the ground
  41306. */
  41307. height,
  41308. /**
  41309. * Defines the subdivisions to apply to the ground
  41310. */
  41311. subdivisions, canBeRegenerated, mesh) {
  41312. if (mesh === void 0) { mesh = null; }
  41313. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41314. _this.width = width;
  41315. _this.height = height;
  41316. _this.subdivisions = subdivisions;
  41317. return _this;
  41318. }
  41319. /** @hidden */
  41320. GroundGeometry.prototype._regenerateVertexData = function () {
  41321. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  41322. };
  41323. GroundGeometry.prototype.copy = function (id) {
  41324. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  41325. };
  41326. GroundGeometry.prototype.serialize = function () {
  41327. var serializationObject = _super.prototype.serialize.call(this);
  41328. serializationObject.width = this.width;
  41329. serializationObject.height = this.height;
  41330. serializationObject.subdivisions = this.subdivisions;
  41331. return serializationObject;
  41332. };
  41333. GroundGeometry.Parse = function (parsedGround, scene) {
  41334. if (scene.getGeometryByID(parsedGround.id)) {
  41335. return null; // null since geometry could be something else than a ground...
  41336. }
  41337. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  41338. if (BABYLON.Tags) {
  41339. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  41340. }
  41341. scene.pushGeometry(ground, true);
  41342. return ground;
  41343. };
  41344. return GroundGeometry;
  41345. }(_PrimitiveGeometry));
  41346. BABYLON.GroundGeometry = GroundGeometry;
  41347. /**
  41348. * Creates a tiled ground geometry
  41349. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  41350. */
  41351. var TiledGroundGeometry = /** @class */ (function (_super) {
  41352. __extends(TiledGroundGeometry, _super);
  41353. /**
  41354. * Creates a tiled ground geometry
  41355. * @param id defines the unique ID of the geometry
  41356. * @param scene defines the hosting scene
  41357. * @param xmin defines the minimum value on X axis
  41358. * @param zmin defines the minimum value on Z axis
  41359. * @param xmax defines the maximum value on X axis
  41360. * @param zmax defines the maximum value on Z axis
  41361. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  41362. * @param precision defines the precision to use when computing the tiles
  41363. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41364. * @param mesh defines the hosting mesh (can be null)
  41365. */
  41366. function TiledGroundGeometry(id, scene,
  41367. /**
  41368. * Defines the minimum value on X axis
  41369. */
  41370. xmin,
  41371. /**
  41372. * Defines the minimum value on Z axis
  41373. */
  41374. zmin,
  41375. /**
  41376. * Defines the maximum value on X axis
  41377. */
  41378. xmax,
  41379. /**
  41380. * Defines the maximum value on Z axis
  41381. */
  41382. zmax,
  41383. /**
  41384. * Defines the subdivisions to apply to the ground
  41385. */
  41386. subdivisions,
  41387. /**
  41388. * Defines the precision to use when computing the tiles
  41389. */
  41390. precision, canBeRegenerated, mesh) {
  41391. if (mesh === void 0) { mesh = null; }
  41392. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41393. _this.xmin = xmin;
  41394. _this.zmin = zmin;
  41395. _this.xmax = xmax;
  41396. _this.zmax = zmax;
  41397. _this.subdivisions = subdivisions;
  41398. _this.precision = precision;
  41399. return _this;
  41400. }
  41401. /** @hidden */
  41402. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  41403. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  41404. };
  41405. TiledGroundGeometry.prototype.copy = function (id) {
  41406. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  41407. };
  41408. return TiledGroundGeometry;
  41409. }(_PrimitiveGeometry));
  41410. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  41411. /**
  41412. * Creates a plane geometry
  41413. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  41414. */
  41415. var PlaneGeometry = /** @class */ (function (_super) {
  41416. __extends(PlaneGeometry, _super);
  41417. /**
  41418. * Creates a plane geometry
  41419. * @param id defines the unique ID of the geometry
  41420. * @param scene defines the hosting scene
  41421. * @param size defines the size of the plane (width === height)
  41422. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41423. * @param mesh defines the hosting mesh (can be null)
  41424. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41425. */
  41426. function PlaneGeometry(id, scene,
  41427. /**
  41428. * Defines the size of the plane (width === height)
  41429. */
  41430. size, canBeRegenerated, mesh,
  41431. /**
  41432. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41433. */
  41434. side) {
  41435. if (mesh === void 0) { mesh = null; }
  41436. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41437. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41438. _this.size = size;
  41439. _this.side = side;
  41440. return _this;
  41441. }
  41442. /** @hidden */
  41443. PlaneGeometry.prototype._regenerateVertexData = function () {
  41444. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  41445. };
  41446. PlaneGeometry.prototype.copy = function (id) {
  41447. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  41448. };
  41449. PlaneGeometry.prototype.serialize = function () {
  41450. var serializationObject = _super.prototype.serialize.call(this);
  41451. serializationObject.size = this.size;
  41452. return serializationObject;
  41453. };
  41454. PlaneGeometry.Parse = function (parsedPlane, scene) {
  41455. if (scene.getGeometryByID(parsedPlane.id)) {
  41456. return null; // null since geometry could be something else than a ground...
  41457. }
  41458. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  41459. if (BABYLON.Tags) {
  41460. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  41461. }
  41462. scene.pushGeometry(plane, true);
  41463. return plane;
  41464. };
  41465. return PlaneGeometry;
  41466. }(_PrimitiveGeometry));
  41467. BABYLON.PlaneGeometry = PlaneGeometry;
  41468. /**
  41469. * Creates a torus knot geometry
  41470. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  41471. */
  41472. var TorusKnotGeometry = /** @class */ (function (_super) {
  41473. __extends(TorusKnotGeometry, _super);
  41474. /**
  41475. * Creates a torus knot geometry
  41476. * @param id defines the unique ID of the geometry
  41477. * @param scene defines the hosting scene
  41478. * @param radius defines the radius of the torus knot
  41479. * @param tube defines the thickness of the torus knot tube
  41480. * @param radialSegments defines the number of radial segments
  41481. * @param tubularSegments defines the number of tubular segments
  41482. * @param p defines the first number of windings
  41483. * @param q defines the second number of windings
  41484. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41485. * @param mesh defines the hosting mesh (can be null)
  41486. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41487. */
  41488. function TorusKnotGeometry(id, scene,
  41489. /**
  41490. * Defines the radius of the torus knot
  41491. */
  41492. radius,
  41493. /**
  41494. * Defines the thickness of the torus knot tube
  41495. */
  41496. tube,
  41497. /**
  41498. * Defines the number of radial segments
  41499. */
  41500. radialSegments,
  41501. /**
  41502. * Defines the number of tubular segments
  41503. */
  41504. tubularSegments,
  41505. /**
  41506. * Defines the first number of windings
  41507. */
  41508. p,
  41509. /**
  41510. * Defines the second number of windings
  41511. */
  41512. q, canBeRegenerated, mesh,
  41513. /**
  41514. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41515. */
  41516. side) {
  41517. if (mesh === void 0) { mesh = null; }
  41518. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41519. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41520. _this.radius = radius;
  41521. _this.tube = tube;
  41522. _this.radialSegments = radialSegments;
  41523. _this.tubularSegments = tubularSegments;
  41524. _this.p = p;
  41525. _this.q = q;
  41526. _this.side = side;
  41527. return _this;
  41528. }
  41529. /** @hidden */
  41530. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  41531. 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 });
  41532. };
  41533. TorusKnotGeometry.prototype.copy = function (id) {
  41534. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  41535. };
  41536. TorusKnotGeometry.prototype.serialize = function () {
  41537. var serializationObject = _super.prototype.serialize.call(this);
  41538. serializationObject.radius = this.radius;
  41539. serializationObject.tube = this.tube;
  41540. serializationObject.radialSegments = this.radialSegments;
  41541. serializationObject.tubularSegments = this.tubularSegments;
  41542. serializationObject.p = this.p;
  41543. serializationObject.q = this.q;
  41544. return serializationObject;
  41545. };
  41546. ;
  41547. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  41548. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  41549. return null; // null since geometry could be something else than a ground...
  41550. }
  41551. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  41552. if (BABYLON.Tags) {
  41553. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  41554. }
  41555. scene.pushGeometry(torusKnot, true);
  41556. return torusKnot;
  41557. };
  41558. return TorusKnotGeometry;
  41559. }(_PrimitiveGeometry));
  41560. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  41561. //}
  41562. })(BABYLON || (BABYLON = {}));
  41563. //# sourceMappingURL=babylon.geometry.js.map
  41564. var BABYLON;
  41565. (function (BABYLON) {
  41566. /**
  41567. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  41568. */
  41569. var PerformanceMonitor = /** @class */ (function () {
  41570. /**
  41571. * constructor
  41572. * @param frameSampleSize The number of samples required to saturate the sliding window
  41573. */
  41574. function PerformanceMonitor(frameSampleSize) {
  41575. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41576. this._enabled = true;
  41577. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41578. }
  41579. /**
  41580. * Samples current frame
  41581. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41582. */
  41583. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41584. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41585. if (!this._enabled)
  41586. return;
  41587. if (this._lastFrameTimeMs != null) {
  41588. var dt = timeMs - this._lastFrameTimeMs;
  41589. this._rollingFrameTime.add(dt);
  41590. }
  41591. this._lastFrameTimeMs = timeMs;
  41592. };
  41593. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41594. /**
  41595. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41596. */
  41597. get: function () {
  41598. return this._rollingFrameTime.average;
  41599. },
  41600. enumerable: true,
  41601. configurable: true
  41602. });
  41603. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41604. /**
  41605. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41606. */
  41607. get: function () {
  41608. return this._rollingFrameTime.variance;
  41609. },
  41610. enumerable: true,
  41611. configurable: true
  41612. });
  41613. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41614. /**
  41615. * Returns the frame time of the most recent frame
  41616. */
  41617. get: function () {
  41618. return this._rollingFrameTime.history(0);
  41619. },
  41620. enumerable: true,
  41621. configurable: true
  41622. });
  41623. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41624. /**
  41625. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41626. */
  41627. get: function () {
  41628. return 1000.0 / this._rollingFrameTime.average;
  41629. },
  41630. enumerable: true,
  41631. configurable: true
  41632. });
  41633. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41634. /**
  41635. * Returns the average framerate in frames per second using the most recent frame time
  41636. */
  41637. get: function () {
  41638. var history = this._rollingFrameTime.history(0);
  41639. if (history === 0) {
  41640. return 0;
  41641. }
  41642. return 1000.0 / history;
  41643. },
  41644. enumerable: true,
  41645. configurable: true
  41646. });
  41647. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41648. /**
  41649. * Returns true if enough samples have been taken to completely fill the sliding window
  41650. */
  41651. get: function () {
  41652. return this._rollingFrameTime.isSaturated();
  41653. },
  41654. enumerable: true,
  41655. configurable: true
  41656. });
  41657. /**
  41658. * Enables contributions to the sliding window sample set
  41659. */
  41660. PerformanceMonitor.prototype.enable = function () {
  41661. this._enabled = true;
  41662. };
  41663. /**
  41664. * Disables contributions to the sliding window sample set
  41665. * Samples will not be interpolated over the disabled period
  41666. */
  41667. PerformanceMonitor.prototype.disable = function () {
  41668. this._enabled = false;
  41669. //clear last sample to avoid interpolating over the disabled period when next enabled
  41670. this._lastFrameTimeMs = null;
  41671. };
  41672. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41673. /**
  41674. * Returns true if sampling is enabled
  41675. */
  41676. get: function () {
  41677. return this._enabled;
  41678. },
  41679. enumerable: true,
  41680. configurable: true
  41681. });
  41682. /**
  41683. * Resets performance monitor
  41684. */
  41685. PerformanceMonitor.prototype.reset = function () {
  41686. //clear last sample to avoid interpolating over the disabled period when next enabled
  41687. this._lastFrameTimeMs = null;
  41688. //wipe record
  41689. this._rollingFrameTime.reset();
  41690. };
  41691. return PerformanceMonitor;
  41692. }());
  41693. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41694. /**
  41695. * RollingAverage
  41696. *
  41697. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41698. */
  41699. var RollingAverage = /** @class */ (function () {
  41700. /**
  41701. * constructor
  41702. * @param length The number of samples required to saturate the sliding window
  41703. */
  41704. function RollingAverage(length) {
  41705. this._samples = new Array(length);
  41706. this.reset();
  41707. }
  41708. /**
  41709. * Adds a sample to the sample set
  41710. * @param v The sample value
  41711. */
  41712. RollingAverage.prototype.add = function (v) {
  41713. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41714. var delta;
  41715. //we need to check if we've already wrapped round
  41716. if (this.isSaturated()) {
  41717. //remove bottom of stack from mean
  41718. var bottomValue = this._samples[this._pos];
  41719. delta = bottomValue - this.average;
  41720. this.average -= delta / (this._sampleCount - 1);
  41721. this._m2 -= delta * (bottomValue - this.average);
  41722. }
  41723. else {
  41724. this._sampleCount++;
  41725. }
  41726. //add new value to mean
  41727. delta = v - this.average;
  41728. this.average += delta / (this._sampleCount);
  41729. this._m2 += delta * (v - this.average);
  41730. //set the new variance
  41731. this.variance = this._m2 / (this._sampleCount - 1);
  41732. this._samples[this._pos] = v;
  41733. this._pos++;
  41734. this._pos %= this._samples.length; //positive wrap around
  41735. };
  41736. /**
  41737. * Returns previously added values or null if outside of history or outside the sliding window domain
  41738. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41739. * @return Value previously recorded with add() or null if outside of range
  41740. */
  41741. RollingAverage.prototype.history = function (i) {
  41742. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41743. return 0;
  41744. }
  41745. var i0 = this._wrapPosition(this._pos - 1.0);
  41746. return this._samples[this._wrapPosition(i0 - i)];
  41747. };
  41748. /**
  41749. * Returns true if enough samples have been taken to completely fill the sliding window
  41750. * @return true if sample-set saturated
  41751. */
  41752. RollingAverage.prototype.isSaturated = function () {
  41753. return this._sampleCount >= this._samples.length;
  41754. };
  41755. /**
  41756. * Resets the rolling average (equivalent to 0 samples taken so far)
  41757. */
  41758. RollingAverage.prototype.reset = function () {
  41759. this.average = 0;
  41760. this.variance = 0;
  41761. this._sampleCount = 0;
  41762. this._pos = 0;
  41763. this._m2 = 0;
  41764. };
  41765. /**
  41766. * Wraps a value around the sample range boundaries
  41767. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41768. * @return Wrapped position in sample range
  41769. */
  41770. RollingAverage.prototype._wrapPosition = function (i) {
  41771. var max = this._samples.length;
  41772. return ((i % max) + max) % max;
  41773. };
  41774. return RollingAverage;
  41775. }());
  41776. BABYLON.RollingAverage = RollingAverage;
  41777. })(BABYLON || (BABYLON = {}));
  41778. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41779. var BABYLON;
  41780. (function (BABYLON) {
  41781. /**
  41782. * "Static Class" containing the most commonly used helper while dealing with material for
  41783. * rendering purpose.
  41784. *
  41785. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41786. *
  41787. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41788. */
  41789. var MaterialHelper = /** @class */ (function () {
  41790. function MaterialHelper() {
  41791. }
  41792. /**
  41793. * Bind the current view position to an effect.
  41794. * @param effect The effect to be bound
  41795. * @param scene The scene the eyes position is used from
  41796. */
  41797. MaterialHelper.BindEyePosition = function (effect, scene) {
  41798. if (scene._forcedViewPosition) {
  41799. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41800. return;
  41801. }
  41802. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41803. };
  41804. /**
  41805. * Helps preparing the defines values about the UVs in used in the effect.
  41806. * UVs are shared as much as we can accross channels in the shaders.
  41807. * @param texture The texture we are preparing the UVs for
  41808. * @param defines The defines to update
  41809. * @param key The channel key "diffuse", "specular"... used in the shader
  41810. */
  41811. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41812. defines._needUVs = true;
  41813. defines[key] = true;
  41814. if (texture.getTextureMatrix().isIdentity(true)) {
  41815. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41816. if (texture.coordinatesIndex === 0) {
  41817. defines["MAINUV1"] = true;
  41818. }
  41819. else {
  41820. defines["MAINUV2"] = true;
  41821. }
  41822. }
  41823. else {
  41824. defines[key + "DIRECTUV"] = 0;
  41825. }
  41826. };
  41827. /**
  41828. * Binds a texture matrix value to its corrsponding uniform
  41829. * @param texture The texture to bind the matrix for
  41830. * @param uniformBuffer The uniform buffer receivin the data
  41831. * @param key The channel key "diffuse", "specular"... used in the shader
  41832. */
  41833. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41834. var matrix = texture.getTextureMatrix();
  41835. if (!matrix.isIdentity(true)) {
  41836. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41837. }
  41838. };
  41839. /**
  41840. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41841. * @param mesh defines the current mesh
  41842. * @param scene defines the current scene
  41843. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41844. * @param pointsCloud defines if point cloud rendering has to be turned on
  41845. * @param fogEnabled defines if fog has to be turned on
  41846. * @param alphaTest defines if alpha testing has to be turned on
  41847. * @param defines defines the current list of defines
  41848. */
  41849. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41850. if (defines._areMiscDirty) {
  41851. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41852. defines["POINTSIZE"] = pointsCloud;
  41853. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41854. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41855. defines["ALPHATEST"] = alphaTest;
  41856. }
  41857. };
  41858. /**
  41859. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41860. * @param scene defines the current scene
  41861. * @param engine defines the current engine
  41862. * @param defines specifies the list of active defines
  41863. * @param useInstances defines if instances have to be turned on
  41864. * @param useClipPlane defines if clip plane have to be turned on
  41865. */
  41866. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41867. if (useClipPlane === void 0) { useClipPlane = null; }
  41868. var changed = false;
  41869. var useClipPlane1 = false;
  41870. var useClipPlane2 = false;
  41871. var useClipPlane3 = false;
  41872. var useClipPlane4 = false;
  41873. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  41874. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  41875. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  41876. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  41877. if (defines["CLIPPLANE"] !== useClipPlane1) {
  41878. defines["CLIPPLANE"] = useClipPlane1;
  41879. changed = true;
  41880. }
  41881. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  41882. defines["CLIPPLANE2"] = useClipPlane2;
  41883. changed = true;
  41884. }
  41885. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  41886. defines["CLIPPLANE3"] = useClipPlane3;
  41887. changed = true;
  41888. }
  41889. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  41890. defines["CLIPPLANE4"] = useClipPlane4;
  41891. changed = true;
  41892. }
  41893. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41894. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41895. changed = true;
  41896. }
  41897. if (defines["INSTANCES"] !== useInstances) {
  41898. defines["INSTANCES"] = useInstances;
  41899. changed = true;
  41900. }
  41901. if (changed) {
  41902. defines.markAsUnprocessed();
  41903. }
  41904. };
  41905. /**
  41906. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41907. * @param mesh The mesh containing the geometry data we will draw
  41908. * @param defines The defines to update
  41909. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41910. * @param useBones Precise whether bones should be used or not (override mesh info)
  41911. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41912. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41913. * @returns false if defines are considered not dirty and have not been checked
  41914. */
  41915. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41916. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41917. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41918. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41919. return false;
  41920. }
  41921. defines._normals = defines._needNormals;
  41922. defines._uvs = defines._needUVs;
  41923. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41924. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41925. defines["TANGENT"] = true;
  41926. }
  41927. if (defines._needUVs) {
  41928. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41929. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41930. }
  41931. else {
  41932. defines["UV1"] = false;
  41933. defines["UV2"] = false;
  41934. }
  41935. if (useVertexColor) {
  41936. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41937. defines["VERTEXCOLOR"] = hasVertexColors;
  41938. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41939. }
  41940. if (useBones) {
  41941. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41942. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41943. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41944. }
  41945. else {
  41946. defines["NUM_BONE_INFLUENCERS"] = 0;
  41947. defines["BonesPerMesh"] = 0;
  41948. }
  41949. }
  41950. if (useMorphTargets) {
  41951. var manager = mesh.morphTargetManager;
  41952. if (manager) {
  41953. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41954. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41955. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41956. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41957. }
  41958. else {
  41959. defines["MORPHTARGETS_TANGENT"] = false;
  41960. defines["MORPHTARGETS_NORMAL"] = false;
  41961. defines["MORPHTARGETS"] = false;
  41962. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41963. }
  41964. }
  41965. return true;
  41966. };
  41967. /**
  41968. * Prepares the defines related to the light information passed in parameter
  41969. * @param scene The scene we are intending to draw
  41970. * @param mesh The mesh the effect is compiling for
  41971. * @param defines The defines to update
  41972. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41973. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41974. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41975. * @returns true if normals will be required for the rest of the effect
  41976. */
  41977. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41978. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41979. if (disableLighting === void 0) { disableLighting = false; }
  41980. if (!defines._areLightsDirty) {
  41981. return defines._needNormals;
  41982. }
  41983. var lightIndex = 0;
  41984. var needNormals = false;
  41985. var needRebuild = false;
  41986. var lightmapMode = false;
  41987. var shadowEnabled = false;
  41988. var specularEnabled = false;
  41989. if (scene.lightsEnabled && !disableLighting) {
  41990. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41991. var light = _a[_i];
  41992. needNormals = true;
  41993. if (defines["LIGHT" + lightIndex] === undefined) {
  41994. needRebuild = true;
  41995. }
  41996. defines["LIGHT" + lightIndex] = true;
  41997. defines["SPOTLIGHT" + lightIndex] = false;
  41998. defines["HEMILIGHT" + lightIndex] = false;
  41999. defines["POINTLIGHT" + lightIndex] = false;
  42000. defines["DIRLIGHT" + lightIndex] = false;
  42001. light.prepareLightSpecificDefines(defines, lightIndex);
  42002. // FallOff.
  42003. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  42004. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  42005. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  42006. switch (light.falloffType) {
  42007. case BABYLON.Light.FALLOFF_GLTF:
  42008. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  42009. break;
  42010. case BABYLON.Light.FALLOFF_PHYSICAL:
  42011. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  42012. break;
  42013. case BABYLON.Light.FALLOFF_STANDARD:
  42014. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  42015. break;
  42016. }
  42017. // Specular
  42018. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42019. specularEnabled = true;
  42020. }
  42021. // Shadows
  42022. defines["SHADOW" + lightIndex] = false;
  42023. defines["SHADOWPCF" + lightIndex] = false;
  42024. defines["SHADOWPCSS" + lightIndex] = false;
  42025. defines["SHADOWPOISSON" + lightIndex] = false;
  42026. defines["SHADOWESM" + lightIndex] = false;
  42027. defines["SHADOWCUBE" + lightIndex] = false;
  42028. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42029. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42030. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42031. var shadowGenerator = light.getShadowGenerator();
  42032. if (shadowGenerator) {
  42033. var shadowMap = shadowGenerator.getShadowMap();
  42034. if (shadowMap) {
  42035. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  42036. shadowEnabled = true;
  42037. shadowGenerator.prepareDefines(defines, lightIndex);
  42038. }
  42039. }
  42040. }
  42041. }
  42042. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42043. lightmapMode = true;
  42044. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42045. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42046. }
  42047. else {
  42048. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42049. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42050. }
  42051. lightIndex++;
  42052. if (lightIndex === maxSimultaneousLights)
  42053. break;
  42054. }
  42055. }
  42056. defines["SPECULARTERM"] = specularEnabled;
  42057. defines["SHADOWS"] = shadowEnabled;
  42058. // Resetting all other lights if any
  42059. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42060. if (defines["LIGHT" + index] !== undefined) {
  42061. defines["LIGHT" + index] = false;
  42062. defines["HEMILIGHT" + lightIndex] = false;
  42063. defines["POINTLIGHT" + lightIndex] = false;
  42064. defines["DIRLIGHT" + lightIndex] = false;
  42065. defines["SPOTLIGHT" + lightIndex] = false;
  42066. defines["SHADOW" + lightIndex] = false;
  42067. }
  42068. }
  42069. var caps = scene.getEngine().getCaps();
  42070. if (defines["SHADOWFLOAT"] === undefined) {
  42071. needRebuild = true;
  42072. }
  42073. defines["SHADOWFLOAT"] = shadowEnabled &&
  42074. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42075. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42076. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42077. if (needRebuild) {
  42078. defines.rebuild();
  42079. }
  42080. return needNormals;
  42081. };
  42082. /**
  42083. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42084. * that won t be acctive due to defines being turned off.
  42085. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42086. * @param samplersList The samplers list
  42087. * @param defines The defines helping in the list generation
  42088. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42089. */
  42090. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42091. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42092. var uniformsList;
  42093. var uniformBuffersList = null;
  42094. if (uniformsListOrOptions.uniformsNames) {
  42095. var options = uniformsListOrOptions;
  42096. uniformsList = options.uniformsNames;
  42097. uniformBuffersList = options.uniformBuffersNames;
  42098. samplersList = options.samplers;
  42099. defines = options.defines;
  42100. maxSimultaneousLights = options.maxSimultaneousLights;
  42101. }
  42102. else {
  42103. uniformsList = uniformsListOrOptions;
  42104. if (!samplersList) {
  42105. samplersList = [];
  42106. }
  42107. }
  42108. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42109. if (!defines["LIGHT" + lightIndex]) {
  42110. break;
  42111. }
  42112. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42113. if (uniformBuffersList) {
  42114. uniformBuffersList.push("Light" + lightIndex);
  42115. }
  42116. samplersList.push("shadowSampler" + lightIndex);
  42117. samplersList.push("depthSampler" + lightIndex);
  42118. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42119. samplersList.push("projectionLightSampler" + lightIndex);
  42120. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42121. }
  42122. }
  42123. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42124. uniformsList.push("morphTargetInfluences");
  42125. }
  42126. };
  42127. /**
  42128. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42129. * @param defines The defines to update while falling back
  42130. * @param fallbacks The authorized effect fallbacks
  42131. * @param maxSimultaneousLights The maximum number of lights allowed
  42132. * @param rank the current rank of the Effect
  42133. * @returns The newly affected rank
  42134. */
  42135. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42136. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42137. if (rank === void 0) { rank = 0; }
  42138. var lightFallbackRank = 0;
  42139. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42140. if (!defines["LIGHT" + lightIndex]) {
  42141. break;
  42142. }
  42143. if (lightIndex > 0) {
  42144. lightFallbackRank = rank + lightIndex;
  42145. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42146. }
  42147. if (!defines["SHADOWS"]) {
  42148. if (defines["SHADOW" + lightIndex]) {
  42149. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42150. }
  42151. if (defines["SHADOWPCF" + lightIndex]) {
  42152. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42153. }
  42154. if (defines["SHADOWPCSS" + lightIndex]) {
  42155. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42156. }
  42157. if (defines["SHADOWPOISSON" + lightIndex]) {
  42158. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42159. }
  42160. if (defines["SHADOWESM" + lightIndex]) {
  42161. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42162. }
  42163. }
  42164. }
  42165. return lightFallbackRank++;
  42166. };
  42167. /**
  42168. * Prepares the list of attributes required for morph targets according to the effect defines.
  42169. * @param attribs The current list of supported attribs
  42170. * @param mesh The mesh to prepare the morph targets attributes for
  42171. * @param defines The current Defines of the effect
  42172. */
  42173. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42174. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42175. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42176. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42177. var manager = mesh.morphTargetManager;
  42178. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42179. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42180. for (var index = 0; index < influencers; index++) {
  42181. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42182. if (normal) {
  42183. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42184. }
  42185. if (tangent) {
  42186. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42187. }
  42188. if (attribs.length > maxAttributesCount) {
  42189. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42190. }
  42191. }
  42192. }
  42193. };
  42194. /**
  42195. * Prepares the list of attributes required for bones according to the effect defines.
  42196. * @param attribs The current list of supported attribs
  42197. * @param mesh The mesh to prepare the bones attributes for
  42198. * @param defines The current Defines of the effect
  42199. * @param fallbacks The current efffect fallback strategy
  42200. */
  42201. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42202. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42203. fallbacks.addCPUSkinningFallback(0, mesh);
  42204. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42205. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42206. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42207. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42208. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42209. }
  42210. }
  42211. };
  42212. /**
  42213. * Prepares the list of attributes required for instances according to the effect defines.
  42214. * @param attribs The current list of supported attribs
  42215. * @param defines The current Defines of the effect
  42216. */
  42217. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42218. if (defines["INSTANCES"]) {
  42219. attribs.push("world0");
  42220. attribs.push("world1");
  42221. attribs.push("world2");
  42222. attribs.push("world3");
  42223. }
  42224. };
  42225. /**
  42226. * Binds the light shadow information to the effect for the given mesh.
  42227. * @param light The light containing the generator
  42228. * @param scene The scene the lights belongs to
  42229. * @param mesh The mesh we are binding the information to render
  42230. * @param lightIndex The light index in the effect used to render the mesh
  42231. * @param effect The effect we are binding the data to
  42232. */
  42233. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42234. if (light.shadowEnabled && mesh.receiveShadows) {
  42235. var shadowGenerator = light.getShadowGenerator();
  42236. if (shadowGenerator) {
  42237. shadowGenerator.bindShadowLight(lightIndex, effect);
  42238. }
  42239. }
  42240. };
  42241. /**
  42242. * Binds the light information to the effect.
  42243. * @param light The light containing the generator
  42244. * @param effect The effect we are binding the data to
  42245. * @param lightIndex The light index in the effect used to render
  42246. */
  42247. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42248. light.transferToEffect(effect, lightIndex + "");
  42249. };
  42250. /**
  42251. * Binds the lights information from the scene to the effect for the given mesh.
  42252. * @param scene The scene the lights belongs to
  42253. * @param mesh The mesh we are binding the information to render
  42254. * @param effect The effect we are binding the data to
  42255. * @param defines The generated defines for the effect
  42256. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42257. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42258. */
  42259. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42260. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42261. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42262. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42263. for (var i = 0; i < len; i++) {
  42264. var light = mesh._lightSources[i];
  42265. var iAsString = i.toString();
  42266. var scaledIntensity = light.getScaledIntensity();
  42267. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42268. MaterialHelper.BindLightProperties(light, effect, i);
  42269. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42270. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42271. if (defines["SPECULARTERM"]) {
  42272. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42273. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42274. }
  42275. // Shadows
  42276. if (scene.shadowsEnabled) {
  42277. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42278. }
  42279. light._uniformBuffer.update();
  42280. }
  42281. };
  42282. /**
  42283. * Binds the fog information from the scene to the effect for the given mesh.
  42284. * @param scene The scene the lights belongs to
  42285. * @param mesh The mesh we are binding the information to render
  42286. * @param effect The effect we are binding the data to
  42287. * @param linearSpace Defines if the fog effect is applied in linear space
  42288. */
  42289. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  42290. if (linearSpace === void 0) { linearSpace = false; }
  42291. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42292. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42293. // Convert fog color to linear space if used in a linear space computed shader.
  42294. if (linearSpace) {
  42295. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  42296. effect.setColor3("vFogColor", this._tempFogColor);
  42297. }
  42298. else {
  42299. effect.setColor3("vFogColor", scene.fogColor);
  42300. }
  42301. }
  42302. };
  42303. /**
  42304. * Binds the bones information from the mesh to the effect.
  42305. * @param mesh The mesh we are binding the information to render
  42306. * @param effect The effect we are binding the data to
  42307. */
  42308. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42309. if (!effect || !mesh) {
  42310. return;
  42311. }
  42312. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42313. mesh.computeBonesUsingShaders = false;
  42314. }
  42315. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42316. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42317. if (matrices) {
  42318. effect.setMatrices("mBones", matrices);
  42319. }
  42320. }
  42321. };
  42322. /**
  42323. * Binds the morph targets information from the mesh to the effect.
  42324. * @param abstractMesh The mesh we are binding the information to render
  42325. * @param effect The effect we are binding the data to
  42326. */
  42327. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42328. var manager = abstractMesh.morphTargetManager;
  42329. if (!abstractMesh || !manager) {
  42330. return;
  42331. }
  42332. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42333. };
  42334. /**
  42335. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42336. * @param defines The generated defines used in the effect
  42337. * @param effect The effect we are binding the data to
  42338. * @param scene The scene we are willing to render with logarithmic scale for
  42339. */
  42340. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42341. if (defines["LOGARITHMICDEPTH"]) {
  42342. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42343. }
  42344. };
  42345. /**
  42346. * Binds the clip plane information from the scene to the effect.
  42347. * @param scene The scene the clip plane information are extracted from
  42348. * @param effect The effect we are binding the data to
  42349. */
  42350. MaterialHelper.BindClipPlane = function (effect, scene) {
  42351. if (scene.clipPlane) {
  42352. var clipPlane = scene.clipPlane;
  42353. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42354. }
  42355. if (scene.clipPlane2) {
  42356. var clipPlane = scene.clipPlane2;
  42357. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42358. }
  42359. if (scene.clipPlane3) {
  42360. var clipPlane = scene.clipPlane3;
  42361. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42362. }
  42363. if (scene.clipPlane4) {
  42364. var clipPlane = scene.clipPlane4;
  42365. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42366. }
  42367. };
  42368. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  42369. return MaterialHelper;
  42370. }());
  42371. BABYLON.MaterialHelper = MaterialHelper;
  42372. })(BABYLON || (BABYLON = {}));
  42373. //# sourceMappingURL=babylon.materialHelper.js.map
  42374. var BABYLON;
  42375. (function (BABYLON) {
  42376. /**
  42377. * Base class of materials working in push mode in babylon JS
  42378. * @hidden
  42379. */
  42380. var PushMaterial = /** @class */ (function (_super) {
  42381. __extends(PushMaterial, _super);
  42382. function PushMaterial(name, scene) {
  42383. var _this = _super.call(this, name, scene) || this;
  42384. _this._normalMatrix = new BABYLON.Matrix();
  42385. _this.storeEffectOnSubMeshes = true;
  42386. return _this;
  42387. }
  42388. PushMaterial.prototype.getEffect = function () {
  42389. return this._activeEffect;
  42390. };
  42391. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42392. if (!mesh) {
  42393. return false;
  42394. }
  42395. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42396. return true;
  42397. }
  42398. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42399. };
  42400. /**
  42401. * Binds the given world matrix to the active effect
  42402. *
  42403. * @param world the matrix to bind
  42404. */
  42405. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42406. this._activeEffect.setMatrix("world", world);
  42407. };
  42408. /**
  42409. * Binds the given normal matrix to the active effect
  42410. *
  42411. * @param normalMatrix the matrix to bind
  42412. */
  42413. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42414. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42415. };
  42416. PushMaterial.prototype.bind = function (world, mesh) {
  42417. if (!mesh) {
  42418. return;
  42419. }
  42420. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42421. };
  42422. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42423. if (effect === void 0) { effect = null; }
  42424. _super.prototype._afterBind.call(this, mesh);
  42425. this.getScene()._cachedEffect = effect;
  42426. };
  42427. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42428. if (visibility === void 0) { visibility = 1; }
  42429. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42430. };
  42431. return PushMaterial;
  42432. }(BABYLON.Material));
  42433. BABYLON.PushMaterial = PushMaterial;
  42434. })(BABYLON || (BABYLON = {}));
  42435. //# sourceMappingURL=babylon.pushMaterial.js.map
  42436. var BABYLON;
  42437. (function (BABYLON) {
  42438. /** @hidden */
  42439. var StandardMaterialDefines = /** @class */ (function (_super) {
  42440. __extends(StandardMaterialDefines, _super);
  42441. function StandardMaterialDefines() {
  42442. var _this = _super.call(this) || this;
  42443. _this.MAINUV1 = false;
  42444. _this.MAINUV2 = false;
  42445. _this.DIFFUSE = false;
  42446. _this.DIFFUSEDIRECTUV = 0;
  42447. _this.AMBIENT = false;
  42448. _this.AMBIENTDIRECTUV = 0;
  42449. _this.OPACITY = false;
  42450. _this.OPACITYDIRECTUV = 0;
  42451. _this.OPACITYRGB = false;
  42452. _this.REFLECTION = false;
  42453. _this.EMISSIVE = false;
  42454. _this.EMISSIVEDIRECTUV = 0;
  42455. _this.SPECULAR = false;
  42456. _this.SPECULARDIRECTUV = 0;
  42457. _this.BUMP = false;
  42458. _this.BUMPDIRECTUV = 0;
  42459. _this.PARALLAX = false;
  42460. _this.PARALLAXOCCLUSION = false;
  42461. _this.SPECULAROVERALPHA = false;
  42462. _this.CLIPPLANE = false;
  42463. _this.CLIPPLANE2 = false;
  42464. _this.CLIPPLANE3 = false;
  42465. _this.CLIPPLANE4 = false;
  42466. _this.ALPHATEST = false;
  42467. _this.DEPTHPREPASS = false;
  42468. _this.ALPHAFROMDIFFUSE = false;
  42469. _this.POINTSIZE = false;
  42470. _this.FOG = false;
  42471. _this.SPECULARTERM = false;
  42472. _this.DIFFUSEFRESNEL = false;
  42473. _this.OPACITYFRESNEL = false;
  42474. _this.REFLECTIONFRESNEL = false;
  42475. _this.REFRACTIONFRESNEL = false;
  42476. _this.EMISSIVEFRESNEL = false;
  42477. _this.FRESNEL = false;
  42478. _this.NORMAL = false;
  42479. _this.UV1 = false;
  42480. _this.UV2 = false;
  42481. _this.VERTEXCOLOR = false;
  42482. _this.VERTEXALPHA = false;
  42483. _this.NUM_BONE_INFLUENCERS = 0;
  42484. _this.BonesPerMesh = 0;
  42485. _this.INSTANCES = false;
  42486. _this.GLOSSINESS = false;
  42487. _this.ROUGHNESS = false;
  42488. _this.EMISSIVEASILLUMINATION = false;
  42489. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42490. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42491. _this.LIGHTMAP = false;
  42492. _this.LIGHTMAPDIRECTUV = 0;
  42493. _this.OBJECTSPACE_NORMALMAP = false;
  42494. _this.USELIGHTMAPASSHADOWMAP = false;
  42495. _this.REFLECTIONMAP_3D = false;
  42496. _this.REFLECTIONMAP_SPHERICAL = false;
  42497. _this.REFLECTIONMAP_PLANAR = false;
  42498. _this.REFLECTIONMAP_CUBIC = false;
  42499. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42500. _this.REFLECTIONMAP_PROJECTION = false;
  42501. _this.REFLECTIONMAP_SKYBOX = false;
  42502. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  42503. _this.REFLECTIONMAP_EXPLICIT = false;
  42504. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42505. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42506. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42507. _this.INVERTCUBICMAP = false;
  42508. _this.LOGARITHMICDEPTH = false;
  42509. _this.REFRACTION = false;
  42510. _this.REFRACTIONMAP_3D = false;
  42511. _this.REFLECTIONOVERALPHA = false;
  42512. _this.TWOSIDEDLIGHTING = false;
  42513. _this.SHADOWFLOAT = false;
  42514. _this.MORPHTARGETS = false;
  42515. _this.MORPHTARGETS_NORMAL = false;
  42516. _this.MORPHTARGETS_TANGENT = false;
  42517. _this.NUM_MORPH_INFLUENCERS = 0;
  42518. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42519. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42520. _this.IMAGEPROCESSING = false;
  42521. _this.VIGNETTE = false;
  42522. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42523. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42524. _this.TONEMAPPING = false;
  42525. _this.TONEMAPPING_ACES = false;
  42526. _this.CONTRAST = false;
  42527. _this.COLORCURVES = false;
  42528. _this.COLORGRADING = false;
  42529. _this.COLORGRADING3D = false;
  42530. _this.SAMPLER3DGREENDEPTH = false;
  42531. _this.SAMPLER3DBGRMAP = false;
  42532. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42533. /**
  42534. * If the reflection texture on this material is in linear color space
  42535. * @hidden
  42536. */
  42537. _this.IS_REFLECTION_LINEAR = false;
  42538. /**
  42539. * If the refraction texture on this material is in linear color space
  42540. * @hidden
  42541. */
  42542. _this.IS_REFRACTION_LINEAR = false;
  42543. _this.EXPOSURE = false;
  42544. _this.rebuild();
  42545. return _this;
  42546. }
  42547. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42548. var modes = [
  42549. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42550. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42551. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42552. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42553. ];
  42554. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42555. var mode = modes_1[_i];
  42556. this[mode] = (mode === modeToEnable);
  42557. }
  42558. };
  42559. return StandardMaterialDefines;
  42560. }(BABYLON.MaterialDefines));
  42561. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42562. /**
  42563. * This is the default material used in Babylon. It is the best trade off between quality
  42564. * and performances.
  42565. * @see http://doc.babylonjs.com/babylon101/materials
  42566. */
  42567. var StandardMaterial = /** @class */ (function (_super) {
  42568. __extends(StandardMaterial, _super);
  42569. /**
  42570. * Instantiates a new standard material.
  42571. * This is the default material used in Babylon. It is the best trade off between quality
  42572. * and performances.
  42573. * @see http://doc.babylonjs.com/babylon101/materials
  42574. * @param name Define the name of the material in the scene
  42575. * @param scene Define the scene the material belong to
  42576. */
  42577. function StandardMaterial(name, scene) {
  42578. var _this = _super.call(this, name, scene) || this;
  42579. /**
  42580. * The color of the material lit by the environmental background lighting.
  42581. * @see http://doc.babylonjs.com/babylon101/materials#ambient-color-example
  42582. */
  42583. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42584. /**
  42585. * The basic color of the material as viewed under a light.
  42586. */
  42587. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42588. /**
  42589. * Define how the color and intensity of the highlight given by the light in the material.
  42590. */
  42591. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42592. /**
  42593. * Define the color of the material as if self lit.
  42594. * This will be mixed in the final result even in the absence of light.
  42595. */
  42596. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42597. /**
  42598. * Defines how sharp are the highlights in the material.
  42599. * The bigger the value the sharper giving a more glossy feeling to the result.
  42600. * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.
  42601. */
  42602. _this.specularPower = 64;
  42603. _this._useAlphaFromDiffuseTexture = false;
  42604. _this._useEmissiveAsIllumination = false;
  42605. _this._linkEmissiveWithDiffuse = false;
  42606. _this._useSpecularOverAlpha = false;
  42607. _this._useReflectionOverAlpha = false;
  42608. _this._disableLighting = false;
  42609. _this._useObjectSpaceNormalMap = false;
  42610. _this._useParallax = false;
  42611. _this._useParallaxOcclusion = false;
  42612. /**
  42613. * Apply a scaling factor that determine which "depth" the height map should reprensent. A value between 0.05 and 0.1 is reasonnable in Parallax, you can reach 0.2 using Parallax Occlusion.
  42614. */
  42615. _this.parallaxScaleBias = 0.05;
  42616. _this._roughness = 0;
  42617. /**
  42618. * In case of refraction, define the value of the indice of refraction.
  42619. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  42620. */
  42621. _this.indexOfRefraction = 0.98;
  42622. /**
  42623. * Invert the refraction texture alongside the y axis.
  42624. * It can be usefull with procedural textures or probe for instance.
  42625. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  42626. */
  42627. _this.invertRefractionY = true;
  42628. /**
  42629. * Defines the alpha limits in alpha test mode.
  42630. */
  42631. _this.alphaCutOff = 0.4;
  42632. _this._useLightmapAsShadowmap = false;
  42633. _this._useReflectionFresnelFromSpecular = false;
  42634. _this._useGlossinessFromSpecularMapAlpha = false;
  42635. _this._maxSimultaneousLights = 4;
  42636. _this._invertNormalMapX = false;
  42637. _this._invertNormalMapY = false;
  42638. _this._twoSidedLighting = false;
  42639. _this._renderTargets = new BABYLON.SmartArray(16);
  42640. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42641. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42642. // Setup the default processing configuration to the scene.
  42643. _this._attachImageProcessingConfiguration(null);
  42644. _this.getRenderTargetTextures = function () {
  42645. _this._renderTargets.reset();
  42646. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42647. _this._renderTargets.push(_this._reflectionTexture);
  42648. }
  42649. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42650. _this._renderTargets.push(_this._refractionTexture);
  42651. }
  42652. return _this._renderTargets;
  42653. };
  42654. return _this;
  42655. }
  42656. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42657. /**
  42658. * Gets the image processing configuration used either in this material.
  42659. */
  42660. get: function () {
  42661. return this._imageProcessingConfiguration;
  42662. },
  42663. /**
  42664. * Sets the Default image processing configuration used either in the this material.
  42665. *
  42666. * If sets to null, the scene one is in use.
  42667. */
  42668. set: function (value) {
  42669. this._attachImageProcessingConfiguration(value);
  42670. // Ensure the effect will be rebuilt.
  42671. this._markAllSubMeshesAsTexturesDirty();
  42672. },
  42673. enumerable: true,
  42674. configurable: true
  42675. });
  42676. /**
  42677. * Attaches a new image processing configuration to the Standard Material.
  42678. * @param configuration
  42679. */
  42680. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42681. var _this = this;
  42682. if (configuration === this._imageProcessingConfiguration) {
  42683. return;
  42684. }
  42685. // Detaches observer.
  42686. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42687. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42688. }
  42689. // Pick the scene configuration if needed.
  42690. if (!configuration) {
  42691. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42692. }
  42693. else {
  42694. this._imageProcessingConfiguration = configuration;
  42695. }
  42696. // Attaches observer.
  42697. if (this._imageProcessingConfiguration) {
  42698. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42699. _this._markAllSubMeshesAsImageProcessingDirty();
  42700. });
  42701. }
  42702. };
  42703. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42704. /**
  42705. * Gets wether the color curves effect is enabled.
  42706. */
  42707. get: function () {
  42708. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42709. },
  42710. /**
  42711. * Sets wether the color curves effect is enabled.
  42712. */
  42713. set: function (value) {
  42714. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42715. },
  42716. enumerable: true,
  42717. configurable: true
  42718. });
  42719. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42720. /**
  42721. * Gets wether the color grading effect is enabled.
  42722. */
  42723. get: function () {
  42724. return this.imageProcessingConfiguration.colorGradingEnabled;
  42725. },
  42726. /**
  42727. * Gets wether the color grading effect is enabled.
  42728. */
  42729. set: function (value) {
  42730. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42731. },
  42732. enumerable: true,
  42733. configurable: true
  42734. });
  42735. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42736. /**
  42737. * Gets wether tonemapping is enabled or not.
  42738. */
  42739. get: function () {
  42740. return this._imageProcessingConfiguration.toneMappingEnabled;
  42741. },
  42742. /**
  42743. * Sets wether tonemapping is enabled or not
  42744. */
  42745. set: function (value) {
  42746. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42747. },
  42748. enumerable: true,
  42749. configurable: true
  42750. });
  42751. ;
  42752. ;
  42753. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42754. /**
  42755. * The camera exposure used on this material.
  42756. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42757. * This corresponds to a photographic exposure.
  42758. */
  42759. get: function () {
  42760. return this._imageProcessingConfiguration.exposure;
  42761. },
  42762. /**
  42763. * The camera exposure used on this material.
  42764. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42765. * This corresponds to a photographic exposure.
  42766. */
  42767. set: function (value) {
  42768. this._imageProcessingConfiguration.exposure = value;
  42769. },
  42770. enumerable: true,
  42771. configurable: true
  42772. });
  42773. ;
  42774. ;
  42775. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42776. /**
  42777. * Gets The camera contrast used on this material.
  42778. */
  42779. get: function () {
  42780. return this._imageProcessingConfiguration.contrast;
  42781. },
  42782. /**
  42783. * Sets The camera contrast used on this material.
  42784. */
  42785. set: function (value) {
  42786. this._imageProcessingConfiguration.contrast = value;
  42787. },
  42788. enumerable: true,
  42789. configurable: true
  42790. });
  42791. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42792. /**
  42793. * Gets the Color Grading 2D Lookup Texture.
  42794. */
  42795. get: function () {
  42796. return this._imageProcessingConfiguration.colorGradingTexture;
  42797. },
  42798. /**
  42799. * Sets the Color Grading 2D Lookup Texture.
  42800. */
  42801. set: function (value) {
  42802. this._imageProcessingConfiguration.colorGradingTexture = value;
  42803. },
  42804. enumerable: true,
  42805. configurable: true
  42806. });
  42807. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42808. /**
  42809. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42810. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42811. * 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;
  42812. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42813. */
  42814. get: function () {
  42815. return this._imageProcessingConfiguration.colorCurves;
  42816. },
  42817. /**
  42818. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42819. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42820. * 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;
  42821. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42822. */
  42823. set: function (value) {
  42824. this._imageProcessingConfiguration.colorCurves = value;
  42825. },
  42826. enumerable: true,
  42827. configurable: true
  42828. });
  42829. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  42830. /**
  42831. * Gets a boolean indicating that current material needs to register RTT
  42832. */
  42833. get: function () {
  42834. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42835. return true;
  42836. }
  42837. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42838. return true;
  42839. }
  42840. return false;
  42841. },
  42842. enumerable: true,
  42843. configurable: true
  42844. });
  42845. /**
  42846. * Gets the current class name of the material e.g. "StandardMaterial"
  42847. * Mainly use in serialization.
  42848. * @returns the class name
  42849. */
  42850. StandardMaterial.prototype.getClassName = function () {
  42851. return "StandardMaterial";
  42852. };
  42853. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42854. /**
  42855. * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
  42856. * You can try switching to logarithmic depth.
  42857. * @see http://doc.babylonjs.com/how_to/using_logarithmic_depth_buffer
  42858. */
  42859. get: function () {
  42860. return this._useLogarithmicDepth;
  42861. },
  42862. set: function (value) {
  42863. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42864. this._markAllSubMeshesAsMiscDirty();
  42865. },
  42866. enumerable: true,
  42867. configurable: true
  42868. });
  42869. /**
  42870. * Specifies if the material will require alpha blending
  42871. * @returns a boolean specifying if alpha blending is needed
  42872. */
  42873. StandardMaterial.prototype.needAlphaBlending = function () {
  42874. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42875. };
  42876. /**
  42877. * Specifies if this material should be rendered in alpha test mode
  42878. * @returns a boolean specifying if an alpha test is needed.
  42879. */
  42880. StandardMaterial.prototype.needAlphaTesting = function () {
  42881. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42882. };
  42883. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42884. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42885. };
  42886. /**
  42887. * Get the texture used for alpha test purpose.
  42888. * @returns the diffuse texture in case of the standard material.
  42889. */
  42890. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42891. return this._diffuseTexture;
  42892. };
  42893. /**
  42894. * Get if the submesh is ready to be used and all its information available.
  42895. * Child classes can use it to update shaders
  42896. * @param mesh defines the mesh to check
  42897. * @param subMesh defines which submesh to check
  42898. * @param useInstances specifies that instances should be used
  42899. * @returns a boolean indicating that the submesh is ready or not
  42900. */
  42901. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42902. if (useInstances === void 0) { useInstances = false; }
  42903. if (subMesh.effect && this.isFrozen) {
  42904. if (this._wasPreviouslyReady) {
  42905. return true;
  42906. }
  42907. }
  42908. if (!subMesh._materialDefines) {
  42909. subMesh._materialDefines = new StandardMaterialDefines();
  42910. }
  42911. var scene = this.getScene();
  42912. var defines = subMesh._materialDefines;
  42913. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42914. if (defines._renderId === scene.getRenderId()) {
  42915. return true;
  42916. }
  42917. }
  42918. var engine = scene.getEngine();
  42919. // Lights
  42920. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42921. // Textures
  42922. if (defines._areTexturesDirty) {
  42923. defines._needUVs = false;
  42924. defines.MAINUV1 = false;
  42925. defines.MAINUV2 = false;
  42926. if (scene.texturesEnabled) {
  42927. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42928. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42929. return false;
  42930. }
  42931. else {
  42932. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42933. }
  42934. }
  42935. else {
  42936. defines.DIFFUSE = false;
  42937. }
  42938. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42939. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42940. return false;
  42941. }
  42942. else {
  42943. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42944. }
  42945. }
  42946. else {
  42947. defines.AMBIENT = false;
  42948. }
  42949. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42950. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42951. return false;
  42952. }
  42953. else {
  42954. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42955. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42956. }
  42957. }
  42958. else {
  42959. defines.OPACITY = false;
  42960. }
  42961. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42962. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42963. return false;
  42964. }
  42965. else {
  42966. defines._needNormals = true;
  42967. defines.REFLECTION = true;
  42968. defines.ROUGHNESS = (this._roughness > 0);
  42969. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42970. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42971. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42972. switch (this._reflectionTexture.coordinatesMode) {
  42973. case BABYLON.Texture.EXPLICIT_MODE:
  42974. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42975. break;
  42976. case BABYLON.Texture.PLANAR_MODE:
  42977. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42978. break;
  42979. case BABYLON.Texture.PROJECTION_MODE:
  42980. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42981. break;
  42982. case BABYLON.Texture.SKYBOX_MODE:
  42983. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42984. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  42985. break;
  42986. case BABYLON.Texture.SPHERICAL_MODE:
  42987. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42988. break;
  42989. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42990. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42991. break;
  42992. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42993. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42994. break;
  42995. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42996. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42997. break;
  42998. case BABYLON.Texture.CUBIC_MODE:
  42999. case BABYLON.Texture.INVCUBIC_MODE:
  43000. default:
  43001. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43002. break;
  43003. }
  43004. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43005. }
  43006. }
  43007. else {
  43008. defines.REFLECTION = false;
  43009. }
  43010. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43011. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43012. return false;
  43013. }
  43014. else {
  43015. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43016. }
  43017. }
  43018. else {
  43019. defines.EMISSIVE = false;
  43020. }
  43021. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43022. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43023. return false;
  43024. }
  43025. else {
  43026. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43027. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43028. }
  43029. }
  43030. else {
  43031. defines.LIGHTMAP = false;
  43032. }
  43033. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43034. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43035. return false;
  43036. }
  43037. else {
  43038. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43039. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43040. }
  43041. }
  43042. else {
  43043. defines.SPECULAR = false;
  43044. }
  43045. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43046. // Bump texure can not be not blocking.
  43047. if (!this._bumpTexture.isReady()) {
  43048. return false;
  43049. }
  43050. else {
  43051. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43052. defines.PARALLAX = this._useParallax;
  43053. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43054. }
  43055. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43056. }
  43057. else {
  43058. defines.BUMP = false;
  43059. }
  43060. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43061. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43062. return false;
  43063. }
  43064. else {
  43065. defines._needUVs = true;
  43066. defines.REFRACTION = true;
  43067. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43068. }
  43069. }
  43070. else {
  43071. defines.REFRACTION = false;
  43072. }
  43073. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43074. }
  43075. else {
  43076. defines.DIFFUSE = false;
  43077. defines.AMBIENT = false;
  43078. defines.OPACITY = false;
  43079. defines.REFLECTION = false;
  43080. defines.EMISSIVE = false;
  43081. defines.LIGHTMAP = false;
  43082. defines.BUMP = false;
  43083. defines.REFRACTION = false;
  43084. }
  43085. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43086. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43087. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43088. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43089. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43090. }
  43091. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43092. if (!this._imageProcessingConfiguration.isReady()) {
  43093. return false;
  43094. }
  43095. this._imageProcessingConfiguration.prepareDefines(defines);
  43096. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43097. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43098. }
  43099. if (defines._areFresnelDirty) {
  43100. if (StandardMaterial.FresnelEnabled) {
  43101. // Fresnel
  43102. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43103. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43104. this._reflectionFresnelParameters) {
  43105. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43106. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43107. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43108. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43109. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43110. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43111. defines._needNormals = true;
  43112. defines.FRESNEL = true;
  43113. }
  43114. }
  43115. else {
  43116. defines.FRESNEL = false;
  43117. }
  43118. }
  43119. // Misc.
  43120. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43121. // Attribs
  43122. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43123. // Values that need to be evaluated on every frame
  43124. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43125. // Get correct effect
  43126. if (defines.isDirty) {
  43127. defines.markAsProcessed();
  43128. scene.resetCachedMaterial();
  43129. // Fallbacks
  43130. var fallbacks = new BABYLON.EffectFallbacks();
  43131. if (defines.REFLECTION) {
  43132. fallbacks.addFallback(0, "REFLECTION");
  43133. }
  43134. if (defines.SPECULAR) {
  43135. fallbacks.addFallback(0, "SPECULAR");
  43136. }
  43137. if (defines.BUMP) {
  43138. fallbacks.addFallback(0, "BUMP");
  43139. }
  43140. if (defines.PARALLAX) {
  43141. fallbacks.addFallback(1, "PARALLAX");
  43142. }
  43143. if (defines.PARALLAXOCCLUSION) {
  43144. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43145. }
  43146. if (defines.SPECULAROVERALPHA) {
  43147. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43148. }
  43149. if (defines.FOG) {
  43150. fallbacks.addFallback(1, "FOG");
  43151. }
  43152. if (defines.POINTSIZE) {
  43153. fallbacks.addFallback(0, "POINTSIZE");
  43154. }
  43155. if (defines.LOGARITHMICDEPTH) {
  43156. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43157. }
  43158. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43159. if (defines.SPECULARTERM) {
  43160. fallbacks.addFallback(0, "SPECULARTERM");
  43161. }
  43162. if (defines.DIFFUSEFRESNEL) {
  43163. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43164. }
  43165. if (defines.OPACITYFRESNEL) {
  43166. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43167. }
  43168. if (defines.REFLECTIONFRESNEL) {
  43169. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43170. }
  43171. if (defines.EMISSIVEFRESNEL) {
  43172. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43173. }
  43174. if (defines.FRESNEL) {
  43175. fallbacks.addFallback(4, "FRESNEL");
  43176. }
  43177. //Attributes
  43178. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43179. if (defines.NORMAL) {
  43180. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43181. }
  43182. if (defines.UV1) {
  43183. attribs.push(BABYLON.VertexBuffer.UVKind);
  43184. }
  43185. if (defines.UV2) {
  43186. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43187. }
  43188. if (defines.VERTEXCOLOR) {
  43189. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43190. }
  43191. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43192. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43193. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43194. var shaderName = "default";
  43195. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43196. "vFogInfos", "vFogColor", "pointSize",
  43197. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43198. "mBones",
  43199. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43200. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43201. "vReflectionPosition", "vReflectionSize",
  43202. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43203. ];
  43204. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43205. var uniformBuffers = ["Material", "Scene"];
  43206. if (BABYLON.ImageProcessingConfiguration) {
  43207. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43208. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43209. }
  43210. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43211. uniformsNames: uniforms,
  43212. uniformBuffersNames: uniformBuffers,
  43213. samplers: samplers,
  43214. defines: defines,
  43215. maxSimultaneousLights: this._maxSimultaneousLights
  43216. });
  43217. if (this.customShaderNameResolve) {
  43218. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43219. }
  43220. var join = defines.toString();
  43221. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43222. attributes: attribs,
  43223. uniformsNames: uniforms,
  43224. uniformBuffersNames: uniformBuffers,
  43225. samplers: samplers,
  43226. defines: join,
  43227. fallbacks: fallbacks,
  43228. onCompiled: this.onCompiled,
  43229. onError: this.onError,
  43230. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43231. }, engine), defines);
  43232. this.buildUniformLayout();
  43233. }
  43234. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43235. return false;
  43236. }
  43237. defines._renderId = scene.getRenderId();
  43238. this._wasPreviouslyReady = true;
  43239. return true;
  43240. };
  43241. /**
  43242. * Builds the material UBO layouts.
  43243. * Used internally during the effect preparation.
  43244. */
  43245. StandardMaterial.prototype.buildUniformLayout = function () {
  43246. // Order is important !
  43247. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43248. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43249. this._uniformBuffer.addUniform("opacityParts", 4);
  43250. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43251. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43252. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43253. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43254. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43255. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43256. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43257. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43258. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43259. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43260. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43261. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43262. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43263. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43264. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43265. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43266. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43267. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43268. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43269. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43270. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43271. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43272. this._uniformBuffer.addUniform("specularMatrix", 16);
  43273. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43274. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43275. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43276. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43277. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43278. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43279. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43280. this._uniformBuffer.addUniform("pointSize", 1);
  43281. this._uniformBuffer.create();
  43282. };
  43283. /**
  43284. * Unbinds the material from the mesh
  43285. */
  43286. StandardMaterial.prototype.unbind = function () {
  43287. if (this._activeEffect) {
  43288. var needFlag = false;
  43289. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43290. this._activeEffect.setTexture("reflection2DSampler", null);
  43291. needFlag = true;
  43292. }
  43293. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43294. this._activeEffect.setTexture("refraction2DSampler", null);
  43295. needFlag = true;
  43296. }
  43297. if (needFlag) {
  43298. this._markAllSubMeshesAsTexturesDirty();
  43299. }
  43300. }
  43301. _super.prototype.unbind.call(this);
  43302. };
  43303. /**
  43304. * Binds the submesh to this material by preparing the effect and shader to draw
  43305. * @param world defines the world transformation matrix
  43306. * @param mesh defines the mesh containing the submesh
  43307. * @param subMesh defines the submesh to bind the material to
  43308. */
  43309. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43310. var scene = this.getScene();
  43311. var defines = subMesh._materialDefines;
  43312. if (!defines) {
  43313. return;
  43314. }
  43315. var effect = subMesh.effect;
  43316. if (!effect) {
  43317. return;
  43318. }
  43319. this._activeEffect = effect;
  43320. // Matrices
  43321. this.bindOnlyWorldMatrix(world);
  43322. // Normal Matrix
  43323. if (defines.OBJECTSPACE_NORMALMAP) {
  43324. world.toNormalMatrix(this._normalMatrix);
  43325. this.bindOnlyNormalMatrix(this._normalMatrix);
  43326. }
  43327. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43328. // Bones
  43329. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43330. if (mustRebind) {
  43331. this._uniformBuffer.bindToEffect(effect, "Material");
  43332. this.bindViewProjection(effect);
  43333. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43334. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43335. // Fresnel
  43336. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43337. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43338. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43339. }
  43340. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43341. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43342. }
  43343. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43344. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43345. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43346. }
  43347. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43348. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43349. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43350. }
  43351. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43352. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43353. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43354. }
  43355. }
  43356. // Textures
  43357. if (scene.texturesEnabled) {
  43358. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43359. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43360. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43361. if (this._diffuseTexture.hasAlpha) {
  43362. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43363. }
  43364. }
  43365. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43366. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43367. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43368. }
  43369. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43370. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43371. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43372. }
  43373. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43374. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43375. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43376. if (this._reflectionTexture.boundingBoxSize) {
  43377. var cubeTexture = this._reflectionTexture;
  43378. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43379. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43380. }
  43381. }
  43382. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43383. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43384. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43385. }
  43386. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43387. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43388. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43389. }
  43390. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43391. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43392. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43393. }
  43394. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43395. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43396. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43397. if (scene._mirroredCameraPosition) {
  43398. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43399. }
  43400. else {
  43401. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43402. }
  43403. }
  43404. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43405. var depth = 1.0;
  43406. if (!this._refractionTexture.isCube) {
  43407. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43408. if (this._refractionTexture.depth) {
  43409. depth = this._refractionTexture.depth;
  43410. }
  43411. }
  43412. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43413. }
  43414. }
  43415. // Point size
  43416. if (this.pointsCloud) {
  43417. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43418. }
  43419. if (defines.SPECULARTERM) {
  43420. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43421. }
  43422. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43423. // Diffuse
  43424. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43425. }
  43426. // Textures
  43427. if (scene.texturesEnabled) {
  43428. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43429. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43430. }
  43431. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43432. effect.setTexture("ambientSampler", this._ambientTexture);
  43433. }
  43434. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43435. effect.setTexture("opacitySampler", this._opacityTexture);
  43436. }
  43437. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43438. if (this._reflectionTexture.isCube) {
  43439. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43440. }
  43441. else {
  43442. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43443. }
  43444. }
  43445. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43446. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43447. }
  43448. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43449. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43450. }
  43451. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43452. effect.setTexture("specularSampler", this._specularTexture);
  43453. }
  43454. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43455. effect.setTexture("bumpSampler", this._bumpTexture);
  43456. }
  43457. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43458. var depth = 1.0;
  43459. if (this._refractionTexture.isCube) {
  43460. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43461. }
  43462. else {
  43463. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43464. }
  43465. }
  43466. }
  43467. // Clip plane
  43468. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43469. // Colors
  43470. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43471. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43472. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43473. }
  43474. if (mustRebind || !this.isFrozen) {
  43475. // Lights
  43476. if (scene.lightsEnabled && !this._disableLighting) {
  43477. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43478. }
  43479. // View
  43480. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43481. this.bindView(effect);
  43482. }
  43483. // Fog
  43484. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43485. // Morph targets
  43486. if (defines.NUM_MORPH_INFLUENCERS) {
  43487. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43488. }
  43489. // Log. depth
  43490. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43491. // image processing
  43492. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  43493. this._imageProcessingConfiguration.bind(this._activeEffect);
  43494. }
  43495. }
  43496. this._uniformBuffer.update();
  43497. this._afterBind(mesh, this._activeEffect);
  43498. };
  43499. /**
  43500. * Get the list of animatables in the material.
  43501. * @returns the list of animatables object used in the material
  43502. */
  43503. StandardMaterial.prototype.getAnimatables = function () {
  43504. var results = [];
  43505. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43506. results.push(this._diffuseTexture);
  43507. }
  43508. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43509. results.push(this._ambientTexture);
  43510. }
  43511. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43512. results.push(this._opacityTexture);
  43513. }
  43514. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43515. results.push(this._reflectionTexture);
  43516. }
  43517. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43518. results.push(this._emissiveTexture);
  43519. }
  43520. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43521. results.push(this._specularTexture);
  43522. }
  43523. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43524. results.push(this._bumpTexture);
  43525. }
  43526. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43527. results.push(this._lightmapTexture);
  43528. }
  43529. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43530. results.push(this._refractionTexture);
  43531. }
  43532. return results;
  43533. };
  43534. /**
  43535. * Gets the active textures from the material
  43536. * @returns an array of textures
  43537. */
  43538. StandardMaterial.prototype.getActiveTextures = function () {
  43539. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43540. if (this._diffuseTexture) {
  43541. activeTextures.push(this._diffuseTexture);
  43542. }
  43543. if (this._ambientTexture) {
  43544. activeTextures.push(this._ambientTexture);
  43545. }
  43546. if (this._opacityTexture) {
  43547. activeTextures.push(this._opacityTexture);
  43548. }
  43549. if (this._reflectionTexture) {
  43550. activeTextures.push(this._reflectionTexture);
  43551. }
  43552. if (this._emissiveTexture) {
  43553. activeTextures.push(this._emissiveTexture);
  43554. }
  43555. if (this._specularTexture) {
  43556. activeTextures.push(this._specularTexture);
  43557. }
  43558. if (this._bumpTexture) {
  43559. activeTextures.push(this._bumpTexture);
  43560. }
  43561. if (this._lightmapTexture) {
  43562. activeTextures.push(this._lightmapTexture);
  43563. }
  43564. if (this._refractionTexture) {
  43565. activeTextures.push(this._refractionTexture);
  43566. }
  43567. return activeTextures;
  43568. };
  43569. /**
  43570. * Specifies if the material uses a texture
  43571. * @param texture defines the texture to check against the material
  43572. * @returns a boolean specifying if the material uses the texture
  43573. */
  43574. StandardMaterial.prototype.hasTexture = function (texture) {
  43575. if (_super.prototype.hasTexture.call(this, texture)) {
  43576. return true;
  43577. }
  43578. if (this._diffuseTexture === texture) {
  43579. return true;
  43580. }
  43581. if (this._ambientTexture === texture) {
  43582. return true;
  43583. }
  43584. if (this._opacityTexture === texture) {
  43585. return true;
  43586. }
  43587. if (this._reflectionTexture === texture) {
  43588. return true;
  43589. }
  43590. if (this._emissiveTexture === texture) {
  43591. return true;
  43592. }
  43593. if (this._specularTexture === texture) {
  43594. return true;
  43595. }
  43596. if (this._bumpTexture === texture) {
  43597. return true;
  43598. }
  43599. if (this._lightmapTexture === texture) {
  43600. return true;
  43601. }
  43602. if (this._refractionTexture === texture) {
  43603. return true;
  43604. }
  43605. return false;
  43606. };
  43607. /**
  43608. * Disposes the material
  43609. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  43610. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  43611. */
  43612. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43613. if (forceDisposeTextures) {
  43614. if (this._diffuseTexture) {
  43615. this._diffuseTexture.dispose();
  43616. }
  43617. if (this._ambientTexture) {
  43618. this._ambientTexture.dispose();
  43619. }
  43620. if (this._opacityTexture) {
  43621. this._opacityTexture.dispose();
  43622. }
  43623. if (this._reflectionTexture) {
  43624. this._reflectionTexture.dispose();
  43625. }
  43626. if (this._emissiveTexture) {
  43627. this._emissiveTexture.dispose();
  43628. }
  43629. if (this._specularTexture) {
  43630. this._specularTexture.dispose();
  43631. }
  43632. if (this._bumpTexture) {
  43633. this._bumpTexture.dispose();
  43634. }
  43635. if (this._lightmapTexture) {
  43636. this._lightmapTexture.dispose();
  43637. }
  43638. if (this._refractionTexture) {
  43639. this._refractionTexture.dispose();
  43640. }
  43641. }
  43642. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43643. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43644. }
  43645. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43646. };
  43647. /**
  43648. * Makes a duplicate of the material, and gives it a new name
  43649. * @param name defines the new name for the duplicated material
  43650. * @returns the cloned material
  43651. */
  43652. StandardMaterial.prototype.clone = function (name) {
  43653. var _this = this;
  43654. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43655. result.name = name;
  43656. result.id = name;
  43657. return result;
  43658. };
  43659. /**
  43660. * Serializes this material in a JSON representation
  43661. * @returns the serialized material object
  43662. */
  43663. StandardMaterial.prototype.serialize = function () {
  43664. return BABYLON.SerializationHelper.Serialize(this);
  43665. };
  43666. /**
  43667. * Creates a standard material from parsed material data
  43668. * @param source defines the JSON represnetation of the material
  43669. * @param scene defines the hosting scene
  43670. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  43671. * @returns a new material
  43672. */
  43673. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43674. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43675. };
  43676. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43677. /**
  43678. * Are diffuse textures enabled in the application.
  43679. */
  43680. get: function () {
  43681. return StandardMaterial._DiffuseTextureEnabled;
  43682. },
  43683. set: function (value) {
  43684. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43685. return;
  43686. }
  43687. StandardMaterial._DiffuseTextureEnabled = value;
  43688. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43689. },
  43690. enumerable: true,
  43691. configurable: true
  43692. });
  43693. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43694. /**
  43695. * Are ambient textures enabled in the application.
  43696. */
  43697. get: function () {
  43698. return StandardMaterial._AmbientTextureEnabled;
  43699. },
  43700. set: function (value) {
  43701. if (StandardMaterial._AmbientTextureEnabled === value) {
  43702. return;
  43703. }
  43704. StandardMaterial._AmbientTextureEnabled = value;
  43705. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43706. },
  43707. enumerable: true,
  43708. configurable: true
  43709. });
  43710. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43711. /**
  43712. * Are opacity textures enabled in the application.
  43713. */
  43714. get: function () {
  43715. return StandardMaterial._OpacityTextureEnabled;
  43716. },
  43717. set: function (value) {
  43718. if (StandardMaterial._OpacityTextureEnabled === value) {
  43719. return;
  43720. }
  43721. StandardMaterial._OpacityTextureEnabled = value;
  43722. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43723. },
  43724. enumerable: true,
  43725. configurable: true
  43726. });
  43727. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43728. /**
  43729. * Are reflection textures enabled in the application.
  43730. */
  43731. get: function () {
  43732. return StandardMaterial._ReflectionTextureEnabled;
  43733. },
  43734. set: function (value) {
  43735. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43736. return;
  43737. }
  43738. StandardMaterial._ReflectionTextureEnabled = value;
  43739. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43740. },
  43741. enumerable: true,
  43742. configurable: true
  43743. });
  43744. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43745. /**
  43746. * Are emissive textures enabled in the application.
  43747. */
  43748. get: function () {
  43749. return StandardMaterial._EmissiveTextureEnabled;
  43750. },
  43751. set: function (value) {
  43752. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43753. return;
  43754. }
  43755. StandardMaterial._EmissiveTextureEnabled = value;
  43756. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43757. },
  43758. enumerable: true,
  43759. configurable: true
  43760. });
  43761. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43762. /**
  43763. * Are specular textures enabled in the application.
  43764. */
  43765. get: function () {
  43766. return StandardMaterial._SpecularTextureEnabled;
  43767. },
  43768. set: function (value) {
  43769. if (StandardMaterial._SpecularTextureEnabled === value) {
  43770. return;
  43771. }
  43772. StandardMaterial._SpecularTextureEnabled = value;
  43773. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43774. },
  43775. enumerable: true,
  43776. configurable: true
  43777. });
  43778. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43779. /**
  43780. * Are bump textures enabled in the application.
  43781. */
  43782. get: function () {
  43783. return StandardMaterial._BumpTextureEnabled;
  43784. },
  43785. set: function (value) {
  43786. if (StandardMaterial._BumpTextureEnabled === value) {
  43787. return;
  43788. }
  43789. StandardMaterial._BumpTextureEnabled = value;
  43790. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43791. },
  43792. enumerable: true,
  43793. configurable: true
  43794. });
  43795. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43796. /**
  43797. * Are lightmap textures enabled in the application.
  43798. */
  43799. get: function () {
  43800. return StandardMaterial._LightmapTextureEnabled;
  43801. },
  43802. set: function (value) {
  43803. if (StandardMaterial._LightmapTextureEnabled === value) {
  43804. return;
  43805. }
  43806. StandardMaterial._LightmapTextureEnabled = value;
  43807. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43808. },
  43809. enumerable: true,
  43810. configurable: true
  43811. });
  43812. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43813. /**
  43814. * Are refraction textures enabled in the application.
  43815. */
  43816. get: function () {
  43817. return StandardMaterial._RefractionTextureEnabled;
  43818. },
  43819. set: function (value) {
  43820. if (StandardMaterial._RefractionTextureEnabled === value) {
  43821. return;
  43822. }
  43823. StandardMaterial._RefractionTextureEnabled = value;
  43824. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43825. },
  43826. enumerable: true,
  43827. configurable: true
  43828. });
  43829. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43830. /**
  43831. * Are color grading textures enabled in the application.
  43832. */
  43833. get: function () {
  43834. return StandardMaterial._ColorGradingTextureEnabled;
  43835. },
  43836. set: function (value) {
  43837. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43838. return;
  43839. }
  43840. StandardMaterial._ColorGradingTextureEnabled = value;
  43841. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43842. },
  43843. enumerable: true,
  43844. configurable: true
  43845. });
  43846. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43847. /**
  43848. * Are fresnels enabled in the application.
  43849. */
  43850. get: function () {
  43851. return StandardMaterial._FresnelEnabled;
  43852. },
  43853. set: function (value) {
  43854. if (StandardMaterial._FresnelEnabled === value) {
  43855. return;
  43856. }
  43857. StandardMaterial._FresnelEnabled = value;
  43858. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43859. },
  43860. enumerable: true,
  43861. configurable: true
  43862. });
  43863. // Flags used to enable or disable a type of texture for all Standard Materials
  43864. StandardMaterial._DiffuseTextureEnabled = true;
  43865. StandardMaterial._AmbientTextureEnabled = true;
  43866. StandardMaterial._OpacityTextureEnabled = true;
  43867. StandardMaterial._ReflectionTextureEnabled = true;
  43868. StandardMaterial._EmissiveTextureEnabled = true;
  43869. StandardMaterial._SpecularTextureEnabled = true;
  43870. StandardMaterial._BumpTextureEnabled = true;
  43871. StandardMaterial._LightmapTextureEnabled = true;
  43872. StandardMaterial._RefractionTextureEnabled = true;
  43873. StandardMaterial._ColorGradingTextureEnabled = true;
  43874. StandardMaterial._FresnelEnabled = true;
  43875. __decorate([
  43876. BABYLON.serializeAsTexture("diffuseTexture")
  43877. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43878. __decorate([
  43879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43880. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43881. __decorate([
  43882. BABYLON.serializeAsTexture("ambientTexture")
  43883. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43884. __decorate([
  43885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43886. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43887. __decorate([
  43888. BABYLON.serializeAsTexture("opacityTexture")
  43889. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43890. __decorate([
  43891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43892. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43893. __decorate([
  43894. BABYLON.serializeAsTexture("reflectionTexture")
  43895. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43896. __decorate([
  43897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43898. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43899. __decorate([
  43900. BABYLON.serializeAsTexture("emissiveTexture")
  43901. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43902. __decorate([
  43903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43904. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43905. __decorate([
  43906. BABYLON.serializeAsTexture("specularTexture")
  43907. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43908. __decorate([
  43909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43910. ], StandardMaterial.prototype, "specularTexture", void 0);
  43911. __decorate([
  43912. BABYLON.serializeAsTexture("bumpTexture")
  43913. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43914. __decorate([
  43915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43916. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43917. __decorate([
  43918. BABYLON.serializeAsTexture("lightmapTexture")
  43919. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43920. __decorate([
  43921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43922. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43923. __decorate([
  43924. BABYLON.serializeAsTexture("refractionTexture")
  43925. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43926. __decorate([
  43927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43928. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43929. __decorate([
  43930. BABYLON.serializeAsColor3("ambient")
  43931. ], StandardMaterial.prototype, "ambientColor", void 0);
  43932. __decorate([
  43933. BABYLON.serializeAsColor3("diffuse")
  43934. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43935. __decorate([
  43936. BABYLON.serializeAsColor3("specular")
  43937. ], StandardMaterial.prototype, "specularColor", void 0);
  43938. __decorate([
  43939. BABYLON.serializeAsColor3("emissive")
  43940. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43941. __decorate([
  43942. BABYLON.serialize()
  43943. ], StandardMaterial.prototype, "specularPower", void 0);
  43944. __decorate([
  43945. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43946. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43947. __decorate([
  43948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43949. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43950. __decorate([
  43951. BABYLON.serialize("useEmissiveAsIllumination")
  43952. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43953. __decorate([
  43954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43955. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43956. __decorate([
  43957. BABYLON.serialize("linkEmissiveWithDiffuse")
  43958. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43959. __decorate([
  43960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43961. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43962. __decorate([
  43963. BABYLON.serialize("useSpecularOverAlpha")
  43964. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43965. __decorate([
  43966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43967. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43968. __decorate([
  43969. BABYLON.serialize("useReflectionOverAlpha")
  43970. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43971. __decorate([
  43972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43973. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43974. __decorate([
  43975. BABYLON.serialize("disableLighting")
  43976. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43977. __decorate([
  43978. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43979. ], StandardMaterial.prototype, "disableLighting", void 0);
  43980. __decorate([
  43981. BABYLON.serialize("useObjectSpaceNormalMap")
  43982. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43983. __decorate([
  43984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43985. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43986. __decorate([
  43987. BABYLON.serialize("useParallax")
  43988. ], StandardMaterial.prototype, "_useParallax", void 0);
  43989. __decorate([
  43990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43991. ], StandardMaterial.prototype, "useParallax", void 0);
  43992. __decorate([
  43993. BABYLON.serialize("useParallaxOcclusion")
  43994. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43995. __decorate([
  43996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43997. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43998. __decorate([
  43999. BABYLON.serialize()
  44000. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44001. __decorate([
  44002. BABYLON.serialize("roughness")
  44003. ], StandardMaterial.prototype, "_roughness", void 0);
  44004. __decorate([
  44005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44006. ], StandardMaterial.prototype, "roughness", void 0);
  44007. __decorate([
  44008. BABYLON.serialize()
  44009. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44010. __decorate([
  44011. BABYLON.serialize()
  44012. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44013. __decorate([
  44014. BABYLON.serialize()
  44015. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44016. __decorate([
  44017. BABYLON.serialize("useLightmapAsShadowmap")
  44018. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44019. __decorate([
  44020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44021. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44022. __decorate([
  44023. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44024. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44025. __decorate([
  44026. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44027. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44028. __decorate([
  44029. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44030. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44031. __decorate([
  44032. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44033. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44034. __decorate([
  44035. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44036. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44037. __decorate([
  44038. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44039. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44040. __decorate([
  44041. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44042. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44043. __decorate([
  44044. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44045. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44046. __decorate([
  44047. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44048. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44049. __decorate([
  44050. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44051. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44052. __decorate([
  44053. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44054. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44055. __decorate([
  44056. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44057. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44058. __decorate([
  44059. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44060. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44061. __decorate([
  44062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44063. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44064. __decorate([
  44065. BABYLON.serialize("maxSimultaneousLights")
  44066. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44067. __decorate([
  44068. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44069. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44070. __decorate([
  44071. BABYLON.serialize("invertNormalMapX")
  44072. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44073. __decorate([
  44074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44075. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44076. __decorate([
  44077. BABYLON.serialize("invertNormalMapY")
  44078. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44079. __decorate([
  44080. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44081. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44082. __decorate([
  44083. BABYLON.serialize("twoSidedLighting")
  44084. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44085. __decorate([
  44086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44087. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44088. __decorate([
  44089. BABYLON.serialize()
  44090. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44091. return StandardMaterial;
  44092. }(BABYLON.PushMaterial));
  44093. BABYLON.StandardMaterial = StandardMaterial;
  44094. })(BABYLON || (BABYLON = {}));
  44095. //# sourceMappingURL=babylon.standardMaterial.js.map
  44096. var BABYLON;
  44097. (function (BABYLON) {
  44098. /**
  44099. * Class representing spherical polynomial coefficients to the 3rd degree
  44100. */
  44101. var SphericalPolynomial = /** @class */ (function () {
  44102. function SphericalPolynomial() {
  44103. /**
  44104. * The x coefficients of the spherical polynomial
  44105. */
  44106. this.x = BABYLON.Vector3.Zero();
  44107. /**
  44108. * The y coefficients of the spherical polynomial
  44109. */
  44110. this.y = BABYLON.Vector3.Zero();
  44111. /**
  44112. * The z coefficients of the spherical polynomial
  44113. */
  44114. this.z = BABYLON.Vector3.Zero();
  44115. /**
  44116. * The xx coefficients of the spherical polynomial
  44117. */
  44118. this.xx = BABYLON.Vector3.Zero();
  44119. /**
  44120. * The yy coefficients of the spherical polynomial
  44121. */
  44122. this.yy = BABYLON.Vector3.Zero();
  44123. /**
  44124. * The zz coefficients of the spherical polynomial
  44125. */
  44126. this.zz = BABYLON.Vector3.Zero();
  44127. /**
  44128. * The xy coefficients of the spherical polynomial
  44129. */
  44130. this.xy = BABYLON.Vector3.Zero();
  44131. /**
  44132. * The yz coefficients of the spherical polynomial
  44133. */
  44134. this.yz = BABYLON.Vector3.Zero();
  44135. /**
  44136. * The zx coefficients of the spherical polynomial
  44137. */
  44138. this.zx = BABYLON.Vector3.Zero();
  44139. }
  44140. /**
  44141. * Adds an ambient color to the spherical polynomial
  44142. * @param color the color to add
  44143. */
  44144. SphericalPolynomial.prototype.addAmbient = function (color) {
  44145. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44146. this.xx = this.xx.add(colorVector);
  44147. this.yy = this.yy.add(colorVector);
  44148. this.zz = this.zz.add(colorVector);
  44149. };
  44150. /**
  44151. * Scales the spherical polynomial by the given amount
  44152. * @param scale the amount to scale
  44153. */
  44154. SphericalPolynomial.prototype.scale = function (scale) {
  44155. this.x = this.x.scale(scale);
  44156. this.y = this.y.scale(scale);
  44157. this.z = this.z.scale(scale);
  44158. this.xx = this.xx.scale(scale);
  44159. this.yy = this.yy.scale(scale);
  44160. this.zz = this.zz.scale(scale);
  44161. this.yz = this.yz.scale(scale);
  44162. this.zx = this.zx.scale(scale);
  44163. this.xy = this.xy.scale(scale);
  44164. };
  44165. /**
  44166. * Gets the spherical polynomial from harmonics
  44167. * @param harmonics the spherical harmonics
  44168. * @returns the spherical polynomial
  44169. */
  44170. SphericalPolynomial.FromHarmonics = function (harmonics) {
  44171. var result = new SphericalPolynomial();
  44172. result.x = harmonics.l11.scale(1.02333);
  44173. result.y = harmonics.l1_1.scale(1.02333);
  44174. result.z = harmonics.l10.scale(1.02333);
  44175. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  44176. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  44177. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  44178. result.yz = harmonics.l2_1.scale(0.858086);
  44179. result.zx = harmonics.l21.scale(0.858086);
  44180. result.xy = harmonics.l2_2.scale(0.858086);
  44181. result.scale(1.0 / Math.PI);
  44182. return result;
  44183. };
  44184. /**
  44185. * Constructs a spherical polynomial from an array.
  44186. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  44187. * @returns the spherical polynomial
  44188. */
  44189. SphericalPolynomial.FromArray = function (data) {
  44190. var sp = new SphericalPolynomial();
  44191. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  44192. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  44193. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  44194. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  44195. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  44196. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  44197. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  44198. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  44199. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  44200. return sp;
  44201. };
  44202. return SphericalPolynomial;
  44203. }());
  44204. BABYLON.SphericalPolynomial = SphericalPolynomial;
  44205. /**
  44206. * Class representing spherical harmonics coefficients to the 3rd degree
  44207. */
  44208. var SphericalHarmonics = /** @class */ (function () {
  44209. function SphericalHarmonics() {
  44210. /**
  44211. * The l0,0 coefficients of the spherical harmonics
  44212. */
  44213. this.l00 = BABYLON.Vector3.Zero();
  44214. /**
  44215. * The l1,-1 coefficients of the spherical harmonics
  44216. */
  44217. this.l1_1 = BABYLON.Vector3.Zero();
  44218. /**
  44219. * The l1,0 coefficients of the spherical harmonics
  44220. */
  44221. this.l10 = BABYLON.Vector3.Zero();
  44222. /**
  44223. * The l1,1 coefficients of the spherical harmonics
  44224. */
  44225. this.l11 = BABYLON.Vector3.Zero();
  44226. /**
  44227. * The l2,-2 coefficients of the spherical harmonics
  44228. */
  44229. this.l2_2 = BABYLON.Vector3.Zero();
  44230. /**
  44231. * The l2,-1 coefficients of the spherical harmonics
  44232. */
  44233. this.l2_1 = BABYLON.Vector3.Zero();
  44234. /**
  44235. * The l2,0 coefficients of the spherical harmonics
  44236. */
  44237. this.l20 = BABYLON.Vector3.Zero();
  44238. /**
  44239. * The l2,1 coefficients of the spherical harmonics
  44240. */
  44241. this.l21 = BABYLON.Vector3.Zero();
  44242. /**
  44243. * The l2,2 coefficients of the spherical harmonics
  44244. */
  44245. this.lL22 = BABYLON.Vector3.Zero();
  44246. }
  44247. /**
  44248. * Adds a light to the spherical harmonics
  44249. * @param direction the direction of the light
  44250. * @param color the color of the light
  44251. * @param deltaSolidAngle the delta solid angle of the light
  44252. */
  44253. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  44254. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44255. var c = colorVector.scale(deltaSolidAngle);
  44256. this.l00 = this.l00.add(c.scale(0.282095));
  44257. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  44258. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  44259. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  44260. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  44261. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  44262. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  44263. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  44264. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  44265. };
  44266. /**
  44267. * Scales the spherical harmonics by the given amount
  44268. * @param scale the amount to scale
  44269. */
  44270. SphericalHarmonics.prototype.scale = function (scale) {
  44271. this.l00 = this.l00.scale(scale);
  44272. this.l1_1 = this.l1_1.scale(scale);
  44273. this.l10 = this.l10.scale(scale);
  44274. this.l11 = this.l11.scale(scale);
  44275. this.l2_2 = this.l2_2.scale(scale);
  44276. this.l2_1 = this.l2_1.scale(scale);
  44277. this.l20 = this.l20.scale(scale);
  44278. this.l21 = this.l21.scale(scale);
  44279. this.lL22 = this.lL22.scale(scale);
  44280. };
  44281. /**
  44282. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  44283. *
  44284. * ```
  44285. * E_lm = A_l * L_lm
  44286. * ```
  44287. *
  44288. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  44289. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  44290. * the scaling factors are given in equation 9.
  44291. */
  44292. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  44293. // Constant (Band 0)
  44294. this.l00 = this.l00.scale(3.141593);
  44295. // Linear (Band 1)
  44296. this.l1_1 = this.l1_1.scale(2.094395);
  44297. this.l10 = this.l10.scale(2.094395);
  44298. this.l11 = this.l11.scale(2.094395);
  44299. // Quadratic (Band 2)
  44300. this.l2_2 = this.l2_2.scale(0.785398);
  44301. this.l2_1 = this.l2_1.scale(0.785398);
  44302. this.l20 = this.l20.scale(0.785398);
  44303. this.l21 = this.l21.scale(0.785398);
  44304. this.lL22 = this.lL22.scale(0.785398);
  44305. };
  44306. /**
  44307. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  44308. *
  44309. * ```
  44310. * L = (1/pi) * E * rho
  44311. * ```
  44312. *
  44313. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  44314. */
  44315. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  44316. this.scale(1.0 / Math.PI);
  44317. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  44318. // (The pixel shader must apply albedo after texture fetches, etc).
  44319. };
  44320. /**
  44321. * Gets the spherical harmonics from polynomial
  44322. * @param polynomial the spherical polynomial
  44323. * @returns the spherical harmonics
  44324. */
  44325. SphericalHarmonics.FromPolynomial = function (polynomial) {
  44326. var result = new SphericalHarmonics();
  44327. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  44328. result.l1_1 = polynomial.y.scale(0.977204);
  44329. result.l10 = polynomial.z.scale(0.977204);
  44330. result.l11 = polynomial.x.scale(0.977204);
  44331. result.l2_2 = polynomial.xy.scale(1.16538);
  44332. result.l2_1 = polynomial.yz.scale(1.16538);
  44333. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  44334. result.l21 = polynomial.zx.scale(1.16538);
  44335. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  44336. result.scale(Math.PI);
  44337. return result;
  44338. };
  44339. /**
  44340. * Constructs a spherical harmonics from an array.
  44341. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  44342. * @returns the spherical harmonics
  44343. */
  44344. SphericalHarmonics.FromArray = function (data) {
  44345. var sh = new SphericalHarmonics();
  44346. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  44347. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  44348. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  44349. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  44350. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  44351. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  44352. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  44353. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  44354. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  44355. return sh;
  44356. };
  44357. return SphericalHarmonics;
  44358. }());
  44359. BABYLON.SphericalHarmonics = SphericalHarmonics;
  44360. })(BABYLON || (BABYLON = {}));
  44361. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  44362. var BABYLON;
  44363. (function (BABYLON) {
  44364. var FileFaceOrientation = /** @class */ (function () {
  44365. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  44366. this.name = name;
  44367. this.worldAxisForNormal = worldAxisForNormal;
  44368. this.worldAxisForFileX = worldAxisForFileX;
  44369. this.worldAxisForFileY = worldAxisForFileY;
  44370. }
  44371. return FileFaceOrientation;
  44372. }());
  44373. ;
  44374. /**
  44375. * Helper class dealing with the extraction of spherical polynomial dataArray
  44376. * from a cube map.
  44377. */
  44378. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  44379. function CubeMapToSphericalPolynomialTools() {
  44380. }
  44381. /**
  44382. * Converts a texture to the according Spherical Polynomial data.
  44383. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44384. *
  44385. * @param texture The texture to extract the information from.
  44386. * @return The Spherical Polynomial data.
  44387. */
  44388. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  44389. if (!texture.isCube) {
  44390. // Only supports cube Textures currently.
  44391. return null;
  44392. }
  44393. var size = texture.getSize().width;
  44394. var right = texture.readPixels(0);
  44395. var left = texture.readPixels(1);
  44396. var up;
  44397. var down;
  44398. if (texture.isRenderTarget) {
  44399. up = texture.readPixels(3);
  44400. down = texture.readPixels(2);
  44401. }
  44402. else {
  44403. up = texture.readPixels(2);
  44404. down = texture.readPixels(3);
  44405. }
  44406. var front = texture.readPixels(4);
  44407. var back = texture.readPixels(5);
  44408. var gammaSpace = texture.gammaSpace;
  44409. // Always read as RGBA.
  44410. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  44411. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  44412. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44413. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  44414. }
  44415. var cubeInfo = {
  44416. size: size,
  44417. right: right,
  44418. left: left,
  44419. up: up,
  44420. down: down,
  44421. front: front,
  44422. back: back,
  44423. format: format,
  44424. type: type,
  44425. gammaSpace: gammaSpace,
  44426. };
  44427. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  44428. };
  44429. /**
  44430. * Converts a cubemap to the according Spherical Polynomial data.
  44431. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44432. *
  44433. * @param cubeInfo The Cube map to extract the information from.
  44434. * @return The Spherical Polynomial data.
  44435. */
  44436. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  44437. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  44438. var totalSolidAngle = 0.0;
  44439. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  44440. var du = 2.0 / cubeInfo.size;
  44441. var dv = du;
  44442. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  44443. var minUV = du * 0.5 - 1.0;
  44444. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  44445. var fileFace = this.FileFaces[faceIndex];
  44446. var dataArray = cubeInfo[fileFace.name];
  44447. var v = minUV;
  44448. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  44449. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  44450. // Because SP is still linear, so summation is fine in that basis.
  44451. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  44452. for (var y = 0; y < cubeInfo.size; y++) {
  44453. var u = minUV;
  44454. for (var x = 0; x < cubeInfo.size; x++) {
  44455. // World direction (not normalised)
  44456. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  44457. worldDirection.normalize();
  44458. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  44459. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  44460. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  44461. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  44462. // Handle Integer types.
  44463. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44464. r /= 255;
  44465. g /= 255;
  44466. b /= 255;
  44467. }
  44468. // Handle Gamma space textures.
  44469. if (cubeInfo.gammaSpace) {
  44470. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  44471. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  44472. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  44473. }
  44474. var color = new BABYLON.Color3(r, g, b);
  44475. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  44476. totalSolidAngle += deltaSolidAngle;
  44477. u += du;
  44478. }
  44479. v += dv;
  44480. }
  44481. }
  44482. // Solid angle for entire sphere is 4*pi
  44483. var sphereSolidAngle = 4.0 * Math.PI;
  44484. // Adjust the solid angle to allow for how many faces we processed.
  44485. var facesProcessed = 6.0;
  44486. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  44487. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  44488. // This is needed because the numerical integration over the cube uses a
  44489. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  44490. // and also to compensate for accumulative error due to float precision in the summation.
  44491. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  44492. sphericalHarmonics.scale(correctionFactor);
  44493. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  44494. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  44495. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  44496. };
  44497. CubeMapToSphericalPolynomialTools.FileFaces = [
  44498. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  44499. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  44500. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  44501. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  44502. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  44503. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  44504. ];
  44505. return CubeMapToSphericalPolynomialTools;
  44506. }());
  44507. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  44508. })(BABYLON || (BABYLON = {}));
  44509. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  44510. var BABYLON;
  44511. (function (BABYLON) {
  44512. /**
  44513. * Manages the defines for the PBR Material.
  44514. * @hiddenChildren
  44515. */
  44516. var PBRMaterialDefines = /** @class */ (function (_super) {
  44517. __extends(PBRMaterialDefines, _super);
  44518. /**
  44519. * Initializes the PBR Material defines.
  44520. */
  44521. function PBRMaterialDefines() {
  44522. var _this = _super.call(this) || this;
  44523. _this.PBR = true;
  44524. _this.MAINUV1 = false;
  44525. _this.MAINUV2 = false;
  44526. _this.UV1 = false;
  44527. _this.UV2 = false;
  44528. _this.ALBEDO = false;
  44529. _this.ALBEDODIRECTUV = 0;
  44530. _this.VERTEXCOLOR = false;
  44531. _this.AMBIENT = false;
  44532. _this.AMBIENTDIRECTUV = 0;
  44533. _this.AMBIENTINGRAYSCALE = false;
  44534. _this.OPACITY = false;
  44535. _this.VERTEXALPHA = false;
  44536. _this.OPACITYDIRECTUV = 0;
  44537. _this.OPACITYRGB = false;
  44538. _this.ALPHATEST = false;
  44539. _this.DEPTHPREPASS = false;
  44540. _this.ALPHABLEND = false;
  44541. _this.ALPHAFROMALBEDO = false;
  44542. _this.ALPHATESTVALUE = "0.5";
  44543. _this.SPECULAROVERALPHA = false;
  44544. _this.RADIANCEOVERALPHA = false;
  44545. _this.ALPHAFRESNEL = false;
  44546. _this.LINEARALPHAFRESNEL = false;
  44547. _this.PREMULTIPLYALPHA = false;
  44548. _this.EMISSIVE = false;
  44549. _this.EMISSIVEDIRECTUV = 0;
  44550. _this.REFLECTIVITY = false;
  44551. _this.REFLECTIVITYDIRECTUV = 0;
  44552. _this.SPECULARTERM = false;
  44553. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44554. _this.MICROSURFACEAUTOMATIC = false;
  44555. _this.LODBASEDMICROSFURACE = false;
  44556. _this.MICROSURFACEMAP = false;
  44557. _this.MICROSURFACEMAPDIRECTUV = 0;
  44558. _this.METALLICWORKFLOW = false;
  44559. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44560. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44561. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44562. _this.AOSTOREINMETALMAPRED = false;
  44563. _this.ENVIRONMENTBRDF = false;
  44564. _this.NORMAL = false;
  44565. _this.TANGENT = false;
  44566. _this.BUMP = false;
  44567. _this.BUMPDIRECTUV = 0;
  44568. _this.OBJECTSPACE_NORMALMAP = false;
  44569. _this.PARALLAX = false;
  44570. _this.PARALLAXOCCLUSION = false;
  44571. _this.NORMALXYSCALE = true;
  44572. _this.LIGHTMAP = false;
  44573. _this.LIGHTMAPDIRECTUV = 0;
  44574. _this.USELIGHTMAPASSHADOWMAP = false;
  44575. _this.GAMMALIGHTMAP = false;
  44576. _this.REFLECTION = false;
  44577. _this.REFLECTIONMAP_3D = false;
  44578. _this.REFLECTIONMAP_SPHERICAL = false;
  44579. _this.REFLECTIONMAP_PLANAR = false;
  44580. _this.REFLECTIONMAP_CUBIC = false;
  44581. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44582. _this.REFLECTIONMAP_PROJECTION = false;
  44583. _this.REFLECTIONMAP_SKYBOX = false;
  44584. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44585. _this.REFLECTIONMAP_EXPLICIT = false;
  44586. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44587. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44588. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44589. _this.INVERTCUBICMAP = false;
  44590. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44591. _this.USESPHERICALINVERTEX = false;
  44592. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44593. _this.LODINREFLECTIONALPHA = false;
  44594. _this.GAMMAREFLECTION = false;
  44595. _this.RGBDREFLECTION = false;
  44596. _this.RADIANCEOCCLUSION = false;
  44597. _this.HORIZONOCCLUSION = false;
  44598. _this.REFRACTION = false;
  44599. _this.REFRACTIONMAP_3D = false;
  44600. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44601. _this.LODINREFRACTIONALPHA = false;
  44602. _this.GAMMAREFRACTION = false;
  44603. _this.RGBDREFRACTION = false;
  44604. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44605. _this.INSTANCES = false;
  44606. _this.NUM_BONE_INFLUENCERS = 0;
  44607. _this.BonesPerMesh = 0;
  44608. _this.NONUNIFORMSCALING = false;
  44609. _this.MORPHTARGETS = false;
  44610. _this.MORPHTARGETS_NORMAL = false;
  44611. _this.MORPHTARGETS_TANGENT = false;
  44612. _this.NUM_MORPH_INFLUENCERS = 0;
  44613. _this.IMAGEPROCESSING = false;
  44614. _this.VIGNETTE = false;
  44615. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44616. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44617. _this.TONEMAPPING = false;
  44618. _this.TONEMAPPING_ACES = false;
  44619. _this.CONTRAST = false;
  44620. _this.COLORCURVES = false;
  44621. _this.COLORGRADING = false;
  44622. _this.COLORGRADING3D = false;
  44623. _this.SAMPLER3DGREENDEPTH = false;
  44624. _this.SAMPLER3DBGRMAP = false;
  44625. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44626. _this.EXPOSURE = false;
  44627. _this.USEPHYSICALLIGHTFALLOFF = false;
  44628. _this.USEGLTFLIGHTFALLOFF = false;
  44629. _this.TWOSIDEDLIGHTING = false;
  44630. _this.SHADOWFLOAT = false;
  44631. _this.CLIPPLANE = false;
  44632. _this.CLIPPLANE2 = false;
  44633. _this.CLIPPLANE3 = false;
  44634. _this.CLIPPLANE4 = false;
  44635. _this.POINTSIZE = false;
  44636. _this.FOG = false;
  44637. _this.LOGARITHMICDEPTH = false;
  44638. _this.FORCENORMALFORWARD = false;
  44639. _this.SPECULARAA = false;
  44640. _this.UNLIT = false;
  44641. _this.rebuild();
  44642. return _this;
  44643. }
  44644. /**
  44645. * Resets the PBR Material defines.
  44646. */
  44647. PBRMaterialDefines.prototype.reset = function () {
  44648. _super.prototype.reset.call(this);
  44649. this.ALPHATESTVALUE = "0.5";
  44650. this.PBR = true;
  44651. };
  44652. return PBRMaterialDefines;
  44653. }(BABYLON.MaterialDefines));
  44654. /**
  44655. * The Physically based material base class of BJS.
  44656. *
  44657. * This offers the main features of a standard PBR material.
  44658. * For more information, please refer to the documentation :
  44659. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44660. */
  44661. var PBRBaseMaterial = /** @class */ (function (_super) {
  44662. __extends(PBRBaseMaterial, _super);
  44663. /**
  44664. * Instantiates a new PBRMaterial instance.
  44665. *
  44666. * @param name The material name
  44667. * @param scene The scene the material will be use in.
  44668. */
  44669. function PBRBaseMaterial(name, scene) {
  44670. var _this = _super.call(this, name, scene) || this;
  44671. /**
  44672. * Intensity of the direct lights e.g. the four lights available in your scene.
  44673. * This impacts both the direct diffuse and specular highlights.
  44674. */
  44675. _this._directIntensity = 1.0;
  44676. /**
  44677. * Intensity of the emissive part of the material.
  44678. * This helps controlling the emissive effect without modifying the emissive color.
  44679. */
  44680. _this._emissiveIntensity = 1.0;
  44681. /**
  44682. * Intensity of the environment e.g. how much the environment will light the object
  44683. * either through harmonics for rough material or through the refelction for shiny ones.
  44684. */
  44685. _this._environmentIntensity = 1.0;
  44686. /**
  44687. * This is a special control allowing the reduction of the specular highlights coming from the
  44688. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44689. */
  44690. _this._specularIntensity = 1.0;
  44691. /**
  44692. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44693. */
  44694. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44695. /**
  44696. * Debug Control allowing disabling the bump map on this material.
  44697. */
  44698. _this._disableBumpMap = false;
  44699. /**
  44700. * AKA Occlusion Texture Intensity in other nomenclature.
  44701. */
  44702. _this._ambientTextureStrength = 1.0;
  44703. /**
  44704. * Defines how much the AO map is occluding the analytical lights (point spot...).
  44705. * 1 means it completely occludes it
  44706. * 0 mean it has no impact
  44707. */
  44708. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  44709. /**
  44710. * The color of a material in ambient lighting.
  44711. */
  44712. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44713. /**
  44714. * AKA Diffuse Color in other nomenclature.
  44715. */
  44716. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44717. /**
  44718. * AKA Specular Color in other nomenclature.
  44719. */
  44720. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44721. /**
  44722. * The color applied when light is reflected from a material.
  44723. */
  44724. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44725. /**
  44726. * The color applied when light is emitted from a material.
  44727. */
  44728. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44729. /**
  44730. * AKA Glossiness in other nomenclature.
  44731. */
  44732. _this._microSurface = 0.9;
  44733. /**
  44734. * source material index of refraction (IOR)' / 'destination material IOR.
  44735. */
  44736. _this._indexOfRefraction = 0.66;
  44737. /**
  44738. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44739. */
  44740. _this._invertRefractionY = false;
  44741. /**
  44742. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44743. * Materials half opaque for instance using refraction could benefit from this control.
  44744. */
  44745. _this._linkRefractionWithTransparency = false;
  44746. /**
  44747. * Specifies that the material will use the light map as a show map.
  44748. */
  44749. _this._useLightmapAsShadowmap = false;
  44750. /**
  44751. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44752. * makes the reflect vector face the model (under horizon).
  44753. */
  44754. _this._useHorizonOcclusion = true;
  44755. /**
  44756. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44757. * too much the area relying on ambient texture to define their ambient occlusion.
  44758. */
  44759. _this._useRadianceOcclusion = true;
  44760. /**
  44761. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44762. */
  44763. _this._useAlphaFromAlbedoTexture = false;
  44764. /**
  44765. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44766. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44767. */
  44768. _this._useSpecularOverAlpha = true;
  44769. /**
  44770. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44771. */
  44772. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44773. /**
  44774. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44775. */
  44776. _this._useRoughnessFromMetallicTextureAlpha = true;
  44777. /**
  44778. * Specifies if the metallic texture contains the roughness information in its green channel.
  44779. */
  44780. _this._useRoughnessFromMetallicTextureGreen = false;
  44781. /**
  44782. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44783. */
  44784. _this._useMetallnessFromMetallicTextureBlue = false;
  44785. /**
  44786. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44787. */
  44788. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44789. /**
  44790. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44791. */
  44792. _this._useAmbientInGrayScale = false;
  44793. /**
  44794. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44795. * The material will try to infer what glossiness each pixel should be.
  44796. */
  44797. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44798. /**
  44799. * Defines the falloff type used in this material.
  44800. * It by default is Physical.
  44801. */
  44802. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  44803. /**
  44804. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44805. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44806. */
  44807. _this._useRadianceOverAlpha = true;
  44808. /**
  44809. * Allows using an object space normal map (instead of tangent space).
  44810. */
  44811. _this._useObjectSpaceNormalMap = false;
  44812. /**
  44813. * Allows using the bump map in parallax mode.
  44814. */
  44815. _this._useParallax = false;
  44816. /**
  44817. * Allows using the bump map in parallax occlusion mode.
  44818. */
  44819. _this._useParallaxOcclusion = false;
  44820. /**
  44821. * Controls the scale bias of the parallax mode.
  44822. */
  44823. _this._parallaxScaleBias = 0.05;
  44824. /**
  44825. * If sets to true, disables all the lights affecting the material.
  44826. */
  44827. _this._disableLighting = false;
  44828. /**
  44829. * Number of Simultaneous lights allowed on the material.
  44830. */
  44831. _this._maxSimultaneousLights = 4;
  44832. /**
  44833. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44834. */
  44835. _this._invertNormalMapX = false;
  44836. /**
  44837. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44838. */
  44839. _this._invertNormalMapY = false;
  44840. /**
  44841. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44842. */
  44843. _this._twoSidedLighting = false;
  44844. /**
  44845. * Defines the alpha limits in alpha test mode.
  44846. */
  44847. _this._alphaCutOff = 0.4;
  44848. /**
  44849. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44850. */
  44851. _this._forceAlphaTest = false;
  44852. /**
  44853. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44854. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44855. */
  44856. _this._useAlphaFresnel = false;
  44857. /**
  44858. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44859. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44860. */
  44861. _this._useLinearAlphaFresnel = false;
  44862. /**
  44863. * The transparency mode of the material.
  44864. */
  44865. _this._transparencyMode = null;
  44866. /**
  44867. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44868. * from cos thetav and roughness:
  44869. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44870. */
  44871. _this._environmentBRDFTexture = null;
  44872. /**
  44873. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44874. */
  44875. _this._forceIrradianceInFragment = false;
  44876. /**
  44877. * Force normal to face away from face.
  44878. */
  44879. _this._forceNormalForward = false;
  44880. /**
  44881. * Enables specular anti aliasing in the PBR shader.
  44882. * It will both interacts on the Geometry for analytical and IBL lighting.
  44883. * It also prefilter the roughness map based on the bump values.
  44884. */
  44885. _this._enableSpecularAntiAliasing = false;
  44886. /**
  44887. * Stores the available render targets.
  44888. */
  44889. _this._renderTargets = new BABYLON.SmartArray(16);
  44890. /**
  44891. * Sets the global ambient color for the material used in lighting calculations.
  44892. */
  44893. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44894. /**
  44895. * If set to true, no lighting calculations will be applied.
  44896. */
  44897. _this._unlit = false;
  44898. // Setup the default processing configuration to the scene.
  44899. _this._attachImageProcessingConfiguration(null);
  44900. _this.getRenderTargetTextures = function () {
  44901. _this._renderTargets.reset();
  44902. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44903. _this._renderTargets.push(_this._reflectionTexture);
  44904. }
  44905. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44906. _this._renderTargets.push(_this._refractionTexture);
  44907. }
  44908. return _this._renderTargets;
  44909. };
  44910. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44911. return _this;
  44912. }
  44913. /**
  44914. * Attaches a new image processing configuration to the PBR Material.
  44915. * @param configuration
  44916. */
  44917. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44918. var _this = this;
  44919. if (configuration === this._imageProcessingConfiguration) {
  44920. return;
  44921. }
  44922. // Detaches observer.
  44923. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44924. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44925. }
  44926. // Pick the scene configuration if needed.
  44927. if (!configuration) {
  44928. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44929. }
  44930. else {
  44931. this._imageProcessingConfiguration = configuration;
  44932. }
  44933. // Attaches observer.
  44934. if (this._imageProcessingConfiguration) {
  44935. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44936. _this._markAllSubMeshesAsImageProcessingDirty();
  44937. });
  44938. }
  44939. };
  44940. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  44941. /**
  44942. * Gets a boolean indicating that current material needs to register RTT
  44943. */
  44944. get: function () {
  44945. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44946. return true;
  44947. }
  44948. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44949. return true;
  44950. }
  44951. return false;
  44952. },
  44953. enumerable: true,
  44954. configurable: true
  44955. });
  44956. /**
  44957. * Gets the name of the material class.
  44958. */
  44959. PBRBaseMaterial.prototype.getClassName = function () {
  44960. return "PBRBaseMaterial";
  44961. };
  44962. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44963. /**
  44964. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44965. */
  44966. get: function () {
  44967. return this._useLogarithmicDepth;
  44968. },
  44969. /**
  44970. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44971. */
  44972. set: function (value) {
  44973. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44974. },
  44975. enumerable: true,
  44976. configurable: true
  44977. });
  44978. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44979. /**
  44980. * Gets the current transparency mode.
  44981. */
  44982. get: function () {
  44983. return this._transparencyMode;
  44984. },
  44985. /**
  44986. * Sets the transparency mode of the material.
  44987. *
  44988. * | Value | Type | Description |
  44989. * | ----- | ----------------------------------- | ----------- |
  44990. * | 0 | OPAQUE | |
  44991. * | 1 | ALPHATEST | |
  44992. * | 2 | ALPHABLEND | |
  44993. * | 3 | ALPHATESTANDBLEND | |
  44994. *
  44995. */
  44996. set: function (value) {
  44997. if (this._transparencyMode === value) {
  44998. return;
  44999. }
  45000. this._transparencyMode = value;
  45001. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  45002. this._markAllSubMeshesAsTexturesAndMiscDirty();
  45003. },
  45004. enumerable: true,
  45005. configurable: true
  45006. });
  45007. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45008. /**
  45009. * Returns true if alpha blending should be disabled.
  45010. */
  45011. get: function () {
  45012. return (this._linkRefractionWithTransparency ||
  45013. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45014. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45015. },
  45016. enumerable: true,
  45017. configurable: true
  45018. });
  45019. /**
  45020. * Specifies whether or not this material should be rendered in alpha blend mode.
  45021. */
  45022. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45023. if (this._disableAlphaBlending) {
  45024. return false;
  45025. }
  45026. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  45027. };
  45028. /**
  45029. * Specifies if the mesh will require alpha blending.
  45030. * @param mesh - BJS mesh.
  45031. */
  45032. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45033. if (this._disableAlphaBlending) {
  45034. return false;
  45035. }
  45036. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45037. };
  45038. /**
  45039. * Specifies whether or not this material should be rendered in alpha test mode.
  45040. */
  45041. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45042. if (this._forceAlphaTest) {
  45043. return true;
  45044. }
  45045. if (this._linkRefractionWithTransparency) {
  45046. return false;
  45047. }
  45048. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45049. };
  45050. /**
  45051. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45052. */
  45053. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45054. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45055. };
  45056. /**
  45057. * Gets the texture used for the alpha test.
  45058. */
  45059. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45060. return this._albedoTexture;
  45061. };
  45062. /**
  45063. * Specifies that the submesh is ready to be used.
  45064. * @param mesh - BJS mesh.
  45065. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45066. * @param useInstances - Specifies that instances should be used.
  45067. * @returns - boolean indicating that the submesh is ready or not.
  45068. */
  45069. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45070. if (subMesh.effect && this.isFrozen) {
  45071. if (this._wasPreviouslyReady) {
  45072. return true;
  45073. }
  45074. }
  45075. if (!subMesh._materialDefines) {
  45076. subMesh._materialDefines = new PBRMaterialDefines();
  45077. }
  45078. var defines = subMesh._materialDefines;
  45079. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45080. if (defines._renderId === this.getScene().getRenderId()) {
  45081. return true;
  45082. }
  45083. }
  45084. var scene = this.getScene();
  45085. var engine = scene.getEngine();
  45086. if (defines._areTexturesDirty) {
  45087. if (scene.texturesEnabled) {
  45088. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45089. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45090. return false;
  45091. }
  45092. }
  45093. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45094. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45095. return false;
  45096. }
  45097. }
  45098. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45099. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45100. return false;
  45101. }
  45102. }
  45103. var reflectionTexture = this._getReflectionTexture();
  45104. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45105. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45106. return false;
  45107. }
  45108. }
  45109. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45110. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45111. return false;
  45112. }
  45113. }
  45114. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45115. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45116. return false;
  45117. }
  45118. }
  45119. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45120. if (this._metallicTexture) {
  45121. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45122. return false;
  45123. }
  45124. }
  45125. else if (this._reflectivityTexture) {
  45126. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45127. return false;
  45128. }
  45129. }
  45130. if (this._microSurfaceTexture) {
  45131. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45132. return false;
  45133. }
  45134. }
  45135. }
  45136. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45137. // Bump texture cannot be not blocking.
  45138. if (!this._bumpTexture.isReady()) {
  45139. return false;
  45140. }
  45141. }
  45142. var refractionTexture = this._getRefractionTexture();
  45143. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45144. if (!refractionTexture.isReadyOrNotBlocking()) {
  45145. return false;
  45146. }
  45147. }
  45148. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45149. // This is blocking.
  45150. if (!this._environmentBRDFTexture.isReady()) {
  45151. return false;
  45152. }
  45153. }
  45154. }
  45155. }
  45156. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  45157. if (!this._imageProcessingConfiguration.isReady()) {
  45158. return false;
  45159. }
  45160. }
  45161. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45162. mesh.createNormals(true);
  45163. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45164. }
  45165. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45166. if (effect) {
  45167. scene.resetCachedMaterial();
  45168. subMesh.setEffect(effect, defines);
  45169. this.buildUniformLayout();
  45170. }
  45171. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45172. return false;
  45173. }
  45174. defines._renderId = scene.getRenderId();
  45175. this._wasPreviouslyReady = true;
  45176. return true;
  45177. };
  45178. /**
  45179. * Specifies if the material uses metallic roughness workflow.
  45180. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45181. */
  45182. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45183. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45184. return true;
  45185. }
  45186. return false;
  45187. };
  45188. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45189. if (onCompiled === void 0) { onCompiled = null; }
  45190. if (onError === void 0) { onError = null; }
  45191. if (useInstances === void 0) { useInstances = null; }
  45192. if (useClipPlane === void 0) { useClipPlane = null; }
  45193. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45194. if (!defines.isDirty) {
  45195. return null;
  45196. }
  45197. defines.markAsProcessed();
  45198. var scene = this.getScene();
  45199. var engine = scene.getEngine();
  45200. // Fallbacks
  45201. var fallbacks = new BABYLON.EffectFallbacks();
  45202. var fallbackRank = 0;
  45203. if (defines.USESPHERICALINVERTEX) {
  45204. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45205. }
  45206. if (defines.FOG) {
  45207. fallbacks.addFallback(fallbackRank, "FOG");
  45208. }
  45209. if (defines.SPECULARAA) {
  45210. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45211. }
  45212. if (defines.POINTSIZE) {
  45213. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45214. }
  45215. if (defines.LOGARITHMICDEPTH) {
  45216. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45217. }
  45218. if (defines.PARALLAX) {
  45219. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45220. }
  45221. if (defines.PARALLAXOCCLUSION) {
  45222. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45223. }
  45224. if (defines.ENVIRONMENTBRDF) {
  45225. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45226. }
  45227. if (defines.TANGENT) {
  45228. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45229. }
  45230. if (defines.BUMP) {
  45231. fallbacks.addFallback(fallbackRank++, "BUMP");
  45232. }
  45233. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45234. if (defines.SPECULARTERM) {
  45235. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45236. }
  45237. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45238. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45239. }
  45240. if (defines.LIGHTMAP) {
  45241. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45242. }
  45243. if (defines.NORMAL) {
  45244. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45245. }
  45246. if (defines.AMBIENT) {
  45247. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45248. }
  45249. if (defines.EMISSIVE) {
  45250. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45251. }
  45252. if (defines.VERTEXCOLOR) {
  45253. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45254. }
  45255. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45256. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45257. }
  45258. if (defines.MORPHTARGETS) {
  45259. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45260. }
  45261. //Attributes
  45262. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45263. if (defines.NORMAL) {
  45264. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45265. }
  45266. if (defines.TANGENT) {
  45267. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45268. }
  45269. if (defines.UV1) {
  45270. attribs.push(BABYLON.VertexBuffer.UVKind);
  45271. }
  45272. if (defines.UV2) {
  45273. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45274. }
  45275. if (defines.VERTEXCOLOR) {
  45276. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45277. }
  45278. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45279. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45280. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45281. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45282. "vFogInfos", "vFogColor", "pointSize",
  45283. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45284. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45285. "mBones",
  45286. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45287. "vLightingIntensity",
  45288. "logarithmicDepthConstant",
  45289. "vSphericalX", "vSphericalY", "vSphericalZ",
  45290. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45291. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45292. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45293. "vTangentSpaceParams"
  45294. ];
  45295. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45296. "bumpSampler", "lightmapSampler", "opacitySampler",
  45297. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45298. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45299. "microSurfaceSampler", "environmentBrdfSampler"];
  45300. var uniformBuffers = ["Material", "Scene"];
  45301. if (BABYLON.ImageProcessingConfiguration) {
  45302. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45303. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45304. }
  45305. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45306. uniformsNames: uniforms,
  45307. uniformBuffersNames: uniformBuffers,
  45308. samplers: samplers,
  45309. defines: defines,
  45310. maxSimultaneousLights: this._maxSimultaneousLights
  45311. });
  45312. var join = defines.toString();
  45313. return engine.createEffect("pbr", {
  45314. attributes: attribs,
  45315. uniformsNames: uniforms,
  45316. uniformBuffersNames: uniformBuffers,
  45317. samplers: samplers,
  45318. defines: join,
  45319. fallbacks: fallbacks,
  45320. onCompiled: onCompiled,
  45321. onError: onError,
  45322. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45323. }, engine);
  45324. };
  45325. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45326. if (useInstances === void 0) { useInstances = null; }
  45327. if (useClipPlane === void 0) { useClipPlane = null; }
  45328. var scene = this.getScene();
  45329. var engine = scene.getEngine();
  45330. // Lights
  45331. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45332. defines._needNormals = true;
  45333. // Textures
  45334. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45335. if (defines._areTexturesDirty) {
  45336. defines._needUVs = false;
  45337. if (scene.texturesEnabled) {
  45338. if (scene.getEngine().getCaps().textureLOD) {
  45339. defines.LODBASEDMICROSFURACE = true;
  45340. }
  45341. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45342. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45343. }
  45344. else {
  45345. defines.ALBEDO = false;
  45346. }
  45347. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45348. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45349. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45350. }
  45351. else {
  45352. defines.AMBIENT = false;
  45353. }
  45354. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45355. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45356. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45357. }
  45358. else {
  45359. defines.OPACITY = false;
  45360. }
  45361. var reflectionTexture = this._getReflectionTexture();
  45362. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45363. defines.REFLECTION = true;
  45364. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45365. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  45366. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45367. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45368. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45369. defines.INVERTCUBICMAP = true;
  45370. }
  45371. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45372. switch (reflectionTexture.coordinatesMode) {
  45373. case BABYLON.Texture.EXPLICIT_MODE:
  45374. defines.REFLECTIONMAP_EXPLICIT = true;
  45375. break;
  45376. case BABYLON.Texture.PLANAR_MODE:
  45377. defines.REFLECTIONMAP_PLANAR = true;
  45378. break;
  45379. case BABYLON.Texture.PROJECTION_MODE:
  45380. defines.REFLECTIONMAP_PROJECTION = true;
  45381. break;
  45382. case BABYLON.Texture.SKYBOX_MODE:
  45383. defines.REFLECTIONMAP_SKYBOX = true;
  45384. break;
  45385. case BABYLON.Texture.SPHERICAL_MODE:
  45386. defines.REFLECTIONMAP_SPHERICAL = true;
  45387. break;
  45388. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45389. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45390. break;
  45391. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45392. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45393. break;
  45394. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45395. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45396. break;
  45397. case BABYLON.Texture.CUBIC_MODE:
  45398. case BABYLON.Texture.INVCUBIC_MODE:
  45399. default:
  45400. defines.REFLECTIONMAP_CUBIC = true;
  45401. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45402. break;
  45403. }
  45404. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45405. if (reflectionTexture.sphericalPolynomial) {
  45406. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45407. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45408. defines.USESPHERICALINVERTEX = false;
  45409. }
  45410. else {
  45411. defines.USESPHERICALINVERTEX = true;
  45412. }
  45413. }
  45414. }
  45415. else {
  45416. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  45417. }
  45418. }
  45419. else {
  45420. defines.REFLECTION = false;
  45421. defines.REFLECTIONMAP_3D = false;
  45422. defines.REFLECTIONMAP_SPHERICAL = false;
  45423. defines.REFLECTIONMAP_PLANAR = false;
  45424. defines.REFLECTIONMAP_CUBIC = false;
  45425. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45426. defines.REFLECTIONMAP_PROJECTION = false;
  45427. defines.REFLECTIONMAP_SKYBOX = false;
  45428. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  45429. defines.REFLECTIONMAP_EXPLICIT = false;
  45430. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45431. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45432. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45433. defines.INVERTCUBICMAP = false;
  45434. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45435. defines.USESPHERICALINVERTEX = false;
  45436. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45437. defines.LODINREFLECTIONALPHA = false;
  45438. defines.GAMMAREFLECTION = false;
  45439. defines.RGBDREFLECTION = false;
  45440. }
  45441. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45442. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45443. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45444. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45445. }
  45446. else {
  45447. defines.LIGHTMAP = false;
  45448. }
  45449. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45450. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45451. }
  45452. else {
  45453. defines.EMISSIVE = false;
  45454. }
  45455. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45456. if (this._metallicTexture) {
  45457. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45458. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45459. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45460. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45461. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45462. }
  45463. else if (this._reflectivityTexture) {
  45464. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45465. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45466. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45467. }
  45468. else {
  45469. defines.REFLECTIVITY = false;
  45470. }
  45471. if (this._microSurfaceTexture) {
  45472. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45473. }
  45474. else {
  45475. defines.MICROSURFACEMAP = false;
  45476. }
  45477. }
  45478. else {
  45479. defines.REFLECTIVITY = false;
  45480. defines.MICROSURFACEMAP = false;
  45481. }
  45482. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45483. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45484. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45485. defines.PARALLAX = true;
  45486. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45487. }
  45488. else {
  45489. defines.PARALLAX = false;
  45490. }
  45491. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45492. }
  45493. else {
  45494. defines.BUMP = false;
  45495. }
  45496. var refractionTexture = this._getRefractionTexture();
  45497. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45498. defines.REFRACTION = true;
  45499. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45500. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45501. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  45502. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45503. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45504. if (this._linkRefractionWithTransparency) {
  45505. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45506. }
  45507. }
  45508. else {
  45509. defines.REFRACTION = false;
  45510. }
  45511. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45512. defines.ENVIRONMENTBRDF = true;
  45513. }
  45514. else {
  45515. defines.ENVIRONMENTBRDF = false;
  45516. }
  45517. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45518. defines.ALPHAFROMALBEDO = true;
  45519. }
  45520. else {
  45521. defines.ALPHAFROMALBEDO = false;
  45522. }
  45523. }
  45524. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45525. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  45526. defines.USEPHYSICALLIGHTFALLOFF = false;
  45527. defines.USEGLTFLIGHTFALLOFF = false;
  45528. }
  45529. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  45530. defines.USEPHYSICALLIGHTFALLOFF = false;
  45531. defines.USEGLTFLIGHTFALLOFF = true;
  45532. }
  45533. else {
  45534. defines.USEPHYSICALLIGHTFALLOFF = true;
  45535. defines.USEGLTFLIGHTFALLOFF = false;
  45536. }
  45537. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45538. if (!this.backFaceCulling && this._twoSidedLighting) {
  45539. defines.TWOSIDEDLIGHTING = true;
  45540. }
  45541. else {
  45542. defines.TWOSIDEDLIGHTING = false;
  45543. }
  45544. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45545. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45546. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45547. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45548. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45549. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45550. }
  45551. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  45552. this._imageProcessingConfiguration.prepareDefines(defines);
  45553. }
  45554. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45555. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45556. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45557. // Misc.
  45558. if (defines._areMiscDirty) {
  45559. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45560. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45561. }
  45562. // Values that need to be evaluated on every frame
  45563. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45564. // Attribs
  45565. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45566. };
  45567. /**
  45568. * Force shader compilation
  45569. */
  45570. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45571. var _this = this;
  45572. var localOptions = __assign({ clipPlane: false }, options);
  45573. var defines = new PBRMaterialDefines();
  45574. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45575. if (effect.isReady()) {
  45576. if (onCompiled) {
  45577. onCompiled(this);
  45578. }
  45579. }
  45580. else {
  45581. effect.onCompileObservable.add(function () {
  45582. if (onCompiled) {
  45583. onCompiled(_this);
  45584. }
  45585. });
  45586. }
  45587. };
  45588. /**
  45589. * Initializes the uniform buffer layout for the shader.
  45590. */
  45591. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45592. // Order is important !
  45593. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45594. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  45595. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45596. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45597. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45598. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45599. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45600. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45601. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45602. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45603. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45604. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45605. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45606. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45607. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45608. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45609. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45610. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45611. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45612. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45613. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45614. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45615. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45616. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45617. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45618. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45619. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45620. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45621. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45622. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45623. this._uniformBuffer.addUniform("pointSize", 1);
  45624. this._uniformBuffer.create();
  45625. };
  45626. /**
  45627. * Unbinds the textures.
  45628. */
  45629. PBRBaseMaterial.prototype.unbind = function () {
  45630. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45631. this._uniformBuffer.setTexture("reflectionSampler", null);
  45632. }
  45633. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45634. this._uniformBuffer.setTexture("refractionSampler", null);
  45635. }
  45636. _super.prototype.unbind.call(this);
  45637. };
  45638. /**
  45639. * Binds the submesh data.
  45640. * @param world - The world matrix.
  45641. * @param mesh - The BJS mesh.
  45642. * @param subMesh - A submesh of the BJS mesh.
  45643. */
  45644. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45645. var scene = this.getScene();
  45646. var defines = subMesh._materialDefines;
  45647. if (!defines) {
  45648. return;
  45649. }
  45650. var effect = subMesh.effect;
  45651. if (!effect) {
  45652. return;
  45653. }
  45654. this._activeEffect = effect;
  45655. // Matrices
  45656. this.bindOnlyWorldMatrix(world);
  45657. // Normal Matrix
  45658. if (defines.OBJECTSPACE_NORMALMAP) {
  45659. world.toNormalMatrix(this._normalMatrix);
  45660. this.bindOnlyNormalMatrix(this._normalMatrix);
  45661. }
  45662. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45663. // Bones
  45664. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45665. var reflectionTexture = null;
  45666. if (mustRebind) {
  45667. this._uniformBuffer.bindToEffect(effect, "Material");
  45668. this.bindViewProjection(effect);
  45669. reflectionTexture = this._getReflectionTexture();
  45670. var refractionTexture = this._getRefractionTexture();
  45671. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45672. // Texture uniforms
  45673. if (scene.texturesEnabled) {
  45674. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45675. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45676. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45677. }
  45678. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45679. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  45680. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45681. }
  45682. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45683. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45684. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45685. }
  45686. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45687. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45688. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45689. if (reflectionTexture.boundingBoxSize) {
  45690. var cubeTexture = reflectionTexture;
  45691. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45692. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45693. }
  45694. var polynomials = reflectionTexture.sphericalPolynomial;
  45695. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45696. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45697. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45698. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45699. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45700. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45701. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45702. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45703. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45704. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45705. }
  45706. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45707. }
  45708. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45709. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45710. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45711. }
  45712. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45713. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45714. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45715. }
  45716. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45717. if (this._metallicTexture) {
  45718. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45719. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45720. }
  45721. else if (this._reflectivityTexture) {
  45722. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45723. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45724. }
  45725. if (this._microSurfaceTexture) {
  45726. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45727. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45728. }
  45729. }
  45730. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45731. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45732. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45733. if (scene._mirroredCameraPosition) {
  45734. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45735. }
  45736. else {
  45737. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45738. }
  45739. }
  45740. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45741. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45742. var depth = 1.0;
  45743. if (!refractionTexture.isCube) {
  45744. if (refractionTexture.depth) {
  45745. depth = refractionTexture.depth;
  45746. }
  45747. }
  45748. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45749. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45750. }
  45751. }
  45752. // Point size
  45753. if (this.pointsCloud) {
  45754. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45755. }
  45756. // Colors
  45757. if (defines.METALLICWORKFLOW) {
  45758. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45759. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45760. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45761. }
  45762. else {
  45763. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45764. }
  45765. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45766. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45767. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45768. // Misc
  45769. this._lightingInfos.x = this._directIntensity;
  45770. this._lightingInfos.y = this._emissiveIntensity;
  45771. this._lightingInfos.z = this._environmentIntensity;
  45772. this._lightingInfos.w = this._specularIntensity;
  45773. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45774. }
  45775. // Textures
  45776. if (scene.texturesEnabled) {
  45777. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45778. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45779. }
  45780. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45781. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45782. }
  45783. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45784. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45785. }
  45786. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45787. if (defines.LODBASEDMICROSFURACE) {
  45788. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45789. }
  45790. else {
  45791. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45792. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45793. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45794. }
  45795. }
  45796. if (defines.ENVIRONMENTBRDF) {
  45797. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45798. }
  45799. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45800. if (defines.LODBASEDMICROSFURACE) {
  45801. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45802. }
  45803. else {
  45804. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45805. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45806. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45807. }
  45808. }
  45809. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45810. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45811. }
  45812. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45813. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45814. }
  45815. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45816. if (this._metallicTexture) {
  45817. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45818. }
  45819. else if (this._reflectivityTexture) {
  45820. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45821. }
  45822. if (this._microSurfaceTexture) {
  45823. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45824. }
  45825. }
  45826. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45827. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45828. }
  45829. }
  45830. // Clip plane
  45831. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45832. // Colors
  45833. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45834. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45835. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45836. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45837. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45838. }
  45839. if (mustRebind || !this.isFrozen) {
  45840. // Lights
  45841. if (scene.lightsEnabled && !this._disableLighting) {
  45842. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  45843. }
  45844. // View
  45845. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45846. this.bindView(effect);
  45847. }
  45848. // Fog
  45849. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  45850. // Morph targets
  45851. if (defines.NUM_MORPH_INFLUENCERS) {
  45852. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45853. }
  45854. // image processing
  45855. this._imageProcessingConfiguration.bind(this._activeEffect);
  45856. // Log. depth
  45857. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45858. }
  45859. this._uniformBuffer.update();
  45860. this._afterBind(mesh, this._activeEffect);
  45861. };
  45862. /**
  45863. * Returns the animatable textures.
  45864. * @returns - Array of animatable textures.
  45865. */
  45866. PBRBaseMaterial.prototype.getAnimatables = function () {
  45867. var results = [];
  45868. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45869. results.push(this._albedoTexture);
  45870. }
  45871. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45872. results.push(this._ambientTexture);
  45873. }
  45874. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45875. results.push(this._opacityTexture);
  45876. }
  45877. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45878. results.push(this._reflectionTexture);
  45879. }
  45880. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45881. results.push(this._emissiveTexture);
  45882. }
  45883. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45884. results.push(this._metallicTexture);
  45885. }
  45886. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45887. results.push(this._reflectivityTexture);
  45888. }
  45889. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45890. results.push(this._bumpTexture);
  45891. }
  45892. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45893. results.push(this._lightmapTexture);
  45894. }
  45895. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45896. results.push(this._refractionTexture);
  45897. }
  45898. return results;
  45899. };
  45900. /**
  45901. * Returns the texture used for reflections.
  45902. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45903. */
  45904. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45905. if (this._reflectionTexture) {
  45906. return this._reflectionTexture;
  45907. }
  45908. return this.getScene().environmentTexture;
  45909. };
  45910. /**
  45911. * Returns the texture used for refraction or null if none is used.
  45912. * @returns - Refection texture if present. If no refraction texture and refraction
  45913. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45914. */
  45915. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45916. if (this._refractionTexture) {
  45917. return this._refractionTexture;
  45918. }
  45919. if (this._linkRefractionWithTransparency) {
  45920. return this.getScene().environmentTexture;
  45921. }
  45922. return null;
  45923. };
  45924. /**
  45925. * Disposes the resources of the material.
  45926. * @param forceDisposeEffect - Forces the disposal of effects.
  45927. * @param forceDisposeTextures - Forces the disposal of all textures.
  45928. */
  45929. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45930. if (forceDisposeTextures) {
  45931. if (this._albedoTexture) {
  45932. this._albedoTexture.dispose();
  45933. }
  45934. if (this._ambientTexture) {
  45935. this._ambientTexture.dispose();
  45936. }
  45937. if (this._opacityTexture) {
  45938. this._opacityTexture.dispose();
  45939. }
  45940. if (this._reflectionTexture) {
  45941. this._reflectionTexture.dispose();
  45942. }
  45943. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45944. this._environmentBRDFTexture.dispose();
  45945. }
  45946. if (this._emissiveTexture) {
  45947. this._emissiveTexture.dispose();
  45948. }
  45949. if (this._metallicTexture) {
  45950. this._metallicTexture.dispose();
  45951. }
  45952. if (this._reflectivityTexture) {
  45953. this._reflectivityTexture.dispose();
  45954. }
  45955. if (this._bumpTexture) {
  45956. this._bumpTexture.dispose();
  45957. }
  45958. if (this._lightmapTexture) {
  45959. this._lightmapTexture.dispose();
  45960. }
  45961. if (this._refractionTexture) {
  45962. this._refractionTexture.dispose();
  45963. }
  45964. }
  45965. this._renderTargets.dispose();
  45966. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45967. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45968. }
  45969. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45970. };
  45971. /**
  45972. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  45973. */
  45974. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  45975. /**
  45976. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  45977. * to enhance interoperability with other engines.
  45978. */
  45979. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  45980. /**
  45981. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  45982. * to enhance interoperability with other materials.
  45983. */
  45984. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  45985. /**
  45986. * Stores the reflectivity values based on metallic roughness workflow.
  45987. */
  45988. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45989. __decorate([
  45990. BABYLON.serializeAsImageProcessingConfiguration()
  45991. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45992. __decorate([
  45993. BABYLON.serialize()
  45994. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45995. __decorate([
  45996. BABYLON.serialize()
  45997. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45998. return PBRBaseMaterial;
  45999. }(BABYLON.PushMaterial));
  46000. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  46001. })(BABYLON || (BABYLON = {}));
  46002. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  46003. var BABYLON;
  46004. (function (BABYLON) {
  46005. /**
  46006. * The Physically based simple base material of BJS.
  46007. *
  46008. * This enables better naming and convention enforcements on top of the pbrMaterial.
  46009. * It is used as the base class for both the specGloss and metalRough conventions.
  46010. */
  46011. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  46012. __extends(PBRBaseSimpleMaterial, _super);
  46013. /**
  46014. * Instantiates a new PBRMaterial instance.
  46015. *
  46016. * @param name The material name
  46017. * @param scene The scene the material will be use in.
  46018. */
  46019. function PBRBaseSimpleMaterial(name, scene) {
  46020. var _this = _super.call(this, name, scene) || this;
  46021. /**
  46022. * Number of Simultaneous lights allowed on the material.
  46023. */
  46024. _this.maxSimultaneousLights = 4;
  46025. /**
  46026. * If sets to true, disables all the lights affecting the material.
  46027. */
  46028. _this.disableLighting = false;
  46029. /**
  46030. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46031. */
  46032. _this.invertNormalMapX = false;
  46033. /**
  46034. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46035. */
  46036. _this.invertNormalMapY = false;
  46037. /**
  46038. * Emissivie color used to self-illuminate the model.
  46039. */
  46040. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46041. /**
  46042. * Occlusion Channel Strenght.
  46043. */
  46044. _this.occlusionStrength = 1.0;
  46045. /**
  46046. * If true, the light map contains occlusion information instead of lighting info.
  46047. */
  46048. _this.useLightmapAsShadowmap = false;
  46049. _this._useAlphaFromAlbedoTexture = true;
  46050. _this._useAmbientInGrayScale = true;
  46051. return _this;
  46052. }
  46053. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46054. /**
  46055. * Gets the current double sided mode.
  46056. */
  46057. get: function () {
  46058. return this._twoSidedLighting;
  46059. },
  46060. /**
  46061. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46062. */
  46063. set: function (value) {
  46064. if (this._twoSidedLighting === value) {
  46065. return;
  46066. }
  46067. this._twoSidedLighting = value;
  46068. this.backFaceCulling = !value;
  46069. this._markAllSubMeshesAsTexturesDirty();
  46070. },
  46071. enumerable: true,
  46072. configurable: true
  46073. });
  46074. /**
  46075. * Return the active textures of the material.
  46076. */
  46077. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46078. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46079. if (this.environmentTexture) {
  46080. activeTextures.push(this.environmentTexture);
  46081. }
  46082. if (this.normalTexture) {
  46083. activeTextures.push(this.normalTexture);
  46084. }
  46085. if (this.emissiveTexture) {
  46086. activeTextures.push(this.emissiveTexture);
  46087. }
  46088. if (this.occlusionTexture) {
  46089. activeTextures.push(this.occlusionTexture);
  46090. }
  46091. if (this.lightmapTexture) {
  46092. activeTextures.push(this.lightmapTexture);
  46093. }
  46094. return activeTextures;
  46095. };
  46096. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46097. if (_super.prototype.hasTexture.call(this, texture)) {
  46098. return true;
  46099. }
  46100. if (this.lightmapTexture === texture) {
  46101. return true;
  46102. }
  46103. return false;
  46104. };
  46105. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46106. return "PBRBaseSimpleMaterial";
  46107. };
  46108. __decorate([
  46109. BABYLON.serialize(),
  46110. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46111. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46112. __decorate([
  46113. BABYLON.serialize(),
  46114. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46115. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46116. __decorate([
  46117. BABYLON.serializeAsTexture(),
  46118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46119. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46120. __decorate([
  46121. BABYLON.serialize(),
  46122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46123. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46124. __decorate([
  46125. BABYLON.serialize(),
  46126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46127. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46128. __decorate([
  46129. BABYLON.serializeAsTexture(),
  46130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46131. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46132. __decorate([
  46133. BABYLON.serializeAsColor3("emissive"),
  46134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46135. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46136. __decorate([
  46137. BABYLON.serializeAsTexture(),
  46138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46139. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46140. __decorate([
  46141. BABYLON.serialize(),
  46142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46143. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46144. __decorate([
  46145. BABYLON.serializeAsTexture(),
  46146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46147. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46148. __decorate([
  46149. BABYLON.serialize(),
  46150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46151. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46152. __decorate([
  46153. BABYLON.serialize()
  46154. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46155. __decorate([
  46156. BABYLON.serializeAsTexture(),
  46157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46158. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46159. __decorate([
  46160. BABYLON.serialize(),
  46161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46162. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46163. return PBRBaseSimpleMaterial;
  46164. }(BABYLON.PBRBaseMaterial));
  46165. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46166. })(BABYLON || (BABYLON = {}));
  46167. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46168. var BABYLON;
  46169. (function (BABYLON) {
  46170. /**
  46171. * The Physically based material of BJS.
  46172. *
  46173. * This offers the main features of a standard PBR material.
  46174. * For more information, please refer to the documentation :
  46175. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46176. */
  46177. var PBRMaterial = /** @class */ (function (_super) {
  46178. __extends(PBRMaterial, _super);
  46179. /**
  46180. * Instantiates a new PBRMaterial instance.
  46181. *
  46182. * @param name The material name
  46183. * @param scene The scene the material will be use in.
  46184. */
  46185. function PBRMaterial(name, scene) {
  46186. var _this = _super.call(this, name, scene) || this;
  46187. /**
  46188. * Intensity of the direct lights e.g. the four lights available in your scene.
  46189. * This impacts both the direct diffuse and specular highlights.
  46190. */
  46191. _this.directIntensity = 1.0;
  46192. /**
  46193. * Intensity of the emissive part of the material.
  46194. * This helps controlling the emissive effect without modifying the emissive color.
  46195. */
  46196. _this.emissiveIntensity = 1.0;
  46197. /**
  46198. * Intensity of the environment e.g. how much the environment will light the object
  46199. * either through harmonics for rough material or through the refelction for shiny ones.
  46200. */
  46201. _this.environmentIntensity = 1.0;
  46202. /**
  46203. * This is a special control allowing the reduction of the specular highlights coming from the
  46204. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46205. */
  46206. _this.specularIntensity = 1.0;
  46207. /**
  46208. * Debug Control allowing disabling the bump map on this material.
  46209. */
  46210. _this.disableBumpMap = false;
  46211. /**
  46212. * AKA Occlusion Texture Intensity in other nomenclature.
  46213. */
  46214. _this.ambientTextureStrength = 1.0;
  46215. /**
  46216. * Defines how much the AO map is occluding the analytical lights (point spot...).
  46217. * 1 means it completely occludes it
  46218. * 0 mean it has no impact
  46219. */
  46220. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  46221. /**
  46222. * The color of a material in ambient lighting.
  46223. */
  46224. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46225. /**
  46226. * AKA Diffuse Color in other nomenclature.
  46227. */
  46228. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46229. /**
  46230. * AKA Specular Color in other nomenclature.
  46231. */
  46232. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46233. /**
  46234. * The color reflected from the material.
  46235. */
  46236. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46237. /**
  46238. * The color emitted from the material.
  46239. */
  46240. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46241. /**
  46242. * AKA Glossiness in other nomenclature.
  46243. */
  46244. _this.microSurface = 1.0;
  46245. /**
  46246. * source material index of refraction (IOR)' / 'destination material IOR.
  46247. */
  46248. _this.indexOfRefraction = 0.66;
  46249. /**
  46250. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46251. */
  46252. _this.invertRefractionY = false;
  46253. /**
  46254. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46255. * Materials half opaque for instance using refraction could benefit from this control.
  46256. */
  46257. _this.linkRefractionWithTransparency = false;
  46258. /**
  46259. * If true, the light map contains occlusion information instead of lighting info.
  46260. */
  46261. _this.useLightmapAsShadowmap = false;
  46262. /**
  46263. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46264. */
  46265. _this.useAlphaFromAlbedoTexture = false;
  46266. /**
  46267. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46268. */
  46269. _this.forceAlphaTest = false;
  46270. /**
  46271. * Defines the alpha limits in alpha test mode.
  46272. */
  46273. _this.alphaCutOff = 0.4;
  46274. /**
  46275. * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).
  46276. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46277. */
  46278. _this.useSpecularOverAlpha = true;
  46279. /**
  46280. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46281. */
  46282. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46283. /**
  46284. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46285. */
  46286. _this.useRoughnessFromMetallicTextureAlpha = true;
  46287. /**
  46288. * Specifies if the metallic texture contains the roughness information in its green channel.
  46289. */
  46290. _this.useRoughnessFromMetallicTextureGreen = false;
  46291. /**
  46292. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46293. */
  46294. _this.useMetallnessFromMetallicTextureBlue = false;
  46295. /**
  46296. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46297. */
  46298. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46299. /**
  46300. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46301. */
  46302. _this.useAmbientInGrayScale = false;
  46303. /**
  46304. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46305. * The material will try to infer what glossiness each pixel should be.
  46306. */
  46307. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46308. /**
  46309. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46310. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46311. */
  46312. _this.useRadianceOverAlpha = true;
  46313. /**
  46314. * Allows using an object space normal map (instead of tangent space).
  46315. */
  46316. _this.useObjectSpaceNormalMap = false;
  46317. /**
  46318. * Allows using the bump map in parallax mode.
  46319. */
  46320. _this.useParallax = false;
  46321. /**
  46322. * Allows using the bump map in parallax occlusion mode.
  46323. */
  46324. _this.useParallaxOcclusion = false;
  46325. /**
  46326. * Controls the scale bias of the parallax mode.
  46327. */
  46328. _this.parallaxScaleBias = 0.05;
  46329. /**
  46330. * If sets to true, disables all the lights affecting the material.
  46331. */
  46332. _this.disableLighting = false;
  46333. /**
  46334. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46335. */
  46336. _this.forceIrradianceInFragment = false;
  46337. /**
  46338. * Number of Simultaneous lights allowed on the material.
  46339. */
  46340. _this.maxSimultaneousLights = 4;
  46341. /**
  46342. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46343. */
  46344. _this.invertNormalMapX = false;
  46345. /**
  46346. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46347. */
  46348. _this.invertNormalMapY = false;
  46349. /**
  46350. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46351. */
  46352. _this.twoSidedLighting = false;
  46353. /**
  46354. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46355. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46356. */
  46357. _this.useAlphaFresnel = false;
  46358. /**
  46359. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46360. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46361. */
  46362. _this.useLinearAlphaFresnel = false;
  46363. /**
  46364. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46365. * And/Or occlude the blended part.
  46366. */
  46367. _this.environmentBRDFTexture = null;
  46368. /**
  46369. * Force normal to face away from face.
  46370. */
  46371. _this.forceNormalForward = false;
  46372. /**
  46373. * Enables specular anti aliasing in the PBR shader.
  46374. * It will both interacts on the Geometry for analytical and IBL lighting.
  46375. * It also prefilter the roughness map based on the bump values.
  46376. */
  46377. _this.enableSpecularAntiAliasing = false;
  46378. /**
  46379. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46380. * makes the reflect vector face the model (under horizon).
  46381. */
  46382. _this.useHorizonOcclusion = true;
  46383. /**
  46384. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46385. * too much the area relying on ambient texture to define their ambient occlusion.
  46386. */
  46387. _this.useRadianceOcclusion = true;
  46388. /**
  46389. * If set to true, no lighting calculations will be applied.
  46390. */
  46391. _this.unlit = false;
  46392. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46393. return _this;
  46394. }
  46395. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  46396. /**
  46397. * BJS is using an harcoded light falloff based on a manually sets up range.
  46398. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46399. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46400. */
  46401. get: function () {
  46402. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46403. },
  46404. /**
  46405. * BJS is using an harcoded light falloff based on a manually sets up range.
  46406. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46407. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46408. */
  46409. set: function (value) {
  46410. if (value !== this.usePhysicalLightFalloff) {
  46411. // Ensure the effect will be rebuilt.
  46412. this._markAllSubMeshesAsTexturesDirty();
  46413. if (value) {
  46414. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46415. }
  46416. else {
  46417. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46418. }
  46419. }
  46420. },
  46421. enumerable: true,
  46422. configurable: true
  46423. });
  46424. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  46425. /**
  46426. * In order to support the falloff compatibility with gltf, a special mode has been added
  46427. * to reproduce the gltf light falloff.
  46428. */
  46429. get: function () {
  46430. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  46431. },
  46432. /**
  46433. * In order to support the falloff compatibility with gltf, a special mode has been added
  46434. * to reproduce the gltf light falloff.
  46435. */
  46436. set: function (value) {
  46437. if (value !== this.useGLTFLightFalloff) {
  46438. // Ensure the effect will be rebuilt.
  46439. this._markAllSubMeshesAsTexturesDirty();
  46440. if (value) {
  46441. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  46442. }
  46443. else {
  46444. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46445. }
  46446. }
  46447. },
  46448. enumerable: true,
  46449. configurable: true
  46450. });
  46451. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46452. /**
  46453. * Gets the image processing configuration used either in this material.
  46454. */
  46455. get: function () {
  46456. return this._imageProcessingConfiguration;
  46457. },
  46458. /**
  46459. * Sets the Default image processing configuration used either in the this material.
  46460. *
  46461. * If sets to null, the scene one is in use.
  46462. */
  46463. set: function (value) {
  46464. this._attachImageProcessingConfiguration(value);
  46465. // Ensure the effect will be rebuilt.
  46466. this._markAllSubMeshesAsTexturesDirty();
  46467. },
  46468. enumerable: true,
  46469. configurable: true
  46470. });
  46471. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46472. /**
  46473. * Gets wether the color curves effect is enabled.
  46474. */
  46475. get: function () {
  46476. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46477. },
  46478. /**
  46479. * Sets wether the color curves effect is enabled.
  46480. */
  46481. set: function (value) {
  46482. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46483. },
  46484. enumerable: true,
  46485. configurable: true
  46486. });
  46487. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46488. /**
  46489. * Gets wether the color grading effect is enabled.
  46490. */
  46491. get: function () {
  46492. return this.imageProcessingConfiguration.colorGradingEnabled;
  46493. },
  46494. /**
  46495. * Gets wether the color grading effect is enabled.
  46496. */
  46497. set: function (value) {
  46498. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46499. },
  46500. enumerable: true,
  46501. configurable: true
  46502. });
  46503. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46504. /**
  46505. * Gets wether tonemapping is enabled or not.
  46506. */
  46507. get: function () {
  46508. return this._imageProcessingConfiguration.toneMappingEnabled;
  46509. },
  46510. /**
  46511. * Sets wether tonemapping is enabled or not
  46512. */
  46513. set: function (value) {
  46514. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46515. },
  46516. enumerable: true,
  46517. configurable: true
  46518. });
  46519. ;
  46520. ;
  46521. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46522. /**
  46523. * The camera exposure used on this material.
  46524. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46525. * This corresponds to a photographic exposure.
  46526. */
  46527. get: function () {
  46528. return this._imageProcessingConfiguration.exposure;
  46529. },
  46530. /**
  46531. * The camera exposure used on this material.
  46532. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46533. * This corresponds to a photographic exposure.
  46534. */
  46535. set: function (value) {
  46536. this._imageProcessingConfiguration.exposure = value;
  46537. },
  46538. enumerable: true,
  46539. configurable: true
  46540. });
  46541. ;
  46542. ;
  46543. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46544. /**
  46545. * Gets The camera contrast used on this material.
  46546. */
  46547. get: function () {
  46548. return this._imageProcessingConfiguration.contrast;
  46549. },
  46550. /**
  46551. * Sets The camera contrast used on this material.
  46552. */
  46553. set: function (value) {
  46554. this._imageProcessingConfiguration.contrast = value;
  46555. },
  46556. enumerable: true,
  46557. configurable: true
  46558. });
  46559. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46560. /**
  46561. * Gets the Color Grading 2D Lookup Texture.
  46562. */
  46563. get: function () {
  46564. return this._imageProcessingConfiguration.colorGradingTexture;
  46565. },
  46566. /**
  46567. * Sets the Color Grading 2D Lookup Texture.
  46568. */
  46569. set: function (value) {
  46570. this._imageProcessingConfiguration.colorGradingTexture = value;
  46571. },
  46572. enumerable: true,
  46573. configurable: true
  46574. });
  46575. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46576. /**
  46577. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46578. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46579. * 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;
  46580. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46581. */
  46582. get: function () {
  46583. return this._imageProcessingConfiguration.colorCurves;
  46584. },
  46585. /**
  46586. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46587. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46588. * 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;
  46589. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46590. */
  46591. set: function (value) {
  46592. this._imageProcessingConfiguration.colorCurves = value;
  46593. },
  46594. enumerable: true,
  46595. configurable: true
  46596. });
  46597. /**
  46598. * Returns the name of this material class.
  46599. */
  46600. PBRMaterial.prototype.getClassName = function () {
  46601. return "PBRMaterial";
  46602. };
  46603. /**
  46604. * Returns an array of the actively used textures.
  46605. * @returns - Array of BaseTextures
  46606. */
  46607. PBRMaterial.prototype.getActiveTextures = function () {
  46608. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46609. if (this._albedoTexture) {
  46610. activeTextures.push(this._albedoTexture);
  46611. }
  46612. if (this._ambientTexture) {
  46613. activeTextures.push(this._ambientTexture);
  46614. }
  46615. if (this._opacityTexture) {
  46616. activeTextures.push(this._opacityTexture);
  46617. }
  46618. if (this._reflectionTexture) {
  46619. activeTextures.push(this._reflectionTexture);
  46620. }
  46621. if (this._emissiveTexture) {
  46622. activeTextures.push(this._emissiveTexture);
  46623. }
  46624. if (this._reflectivityTexture) {
  46625. activeTextures.push(this._reflectivityTexture);
  46626. }
  46627. if (this._metallicTexture) {
  46628. activeTextures.push(this._metallicTexture);
  46629. }
  46630. if (this._microSurfaceTexture) {
  46631. activeTextures.push(this._microSurfaceTexture);
  46632. }
  46633. if (this._bumpTexture) {
  46634. activeTextures.push(this._bumpTexture);
  46635. }
  46636. if (this._lightmapTexture) {
  46637. activeTextures.push(this._lightmapTexture);
  46638. }
  46639. if (this._refractionTexture) {
  46640. activeTextures.push(this._refractionTexture);
  46641. }
  46642. return activeTextures;
  46643. };
  46644. /**
  46645. * Checks to see if a texture is used in the material.
  46646. * @param texture - Base texture to use.
  46647. * @returns - Boolean specifying if a texture is used in the material.
  46648. */
  46649. PBRMaterial.prototype.hasTexture = function (texture) {
  46650. if (_super.prototype.hasTexture.call(this, texture)) {
  46651. return true;
  46652. }
  46653. if (this._albedoTexture === texture) {
  46654. return true;
  46655. }
  46656. if (this._ambientTexture === texture) {
  46657. return true;
  46658. }
  46659. if (this._opacityTexture === texture) {
  46660. return true;
  46661. }
  46662. if (this._reflectionTexture === texture) {
  46663. return true;
  46664. }
  46665. if (this._reflectivityTexture === texture) {
  46666. return true;
  46667. }
  46668. if (this._metallicTexture === texture) {
  46669. return true;
  46670. }
  46671. if (this._microSurfaceTexture === texture) {
  46672. return true;
  46673. }
  46674. if (this._bumpTexture === texture) {
  46675. return true;
  46676. }
  46677. if (this._lightmapTexture === texture) {
  46678. return true;
  46679. }
  46680. if (this._refractionTexture === texture) {
  46681. return true;
  46682. }
  46683. return false;
  46684. };
  46685. /**
  46686. * Makes a duplicate of the current material.
  46687. * @param name - name to use for the new material.
  46688. */
  46689. PBRMaterial.prototype.clone = function (name) {
  46690. var _this = this;
  46691. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46692. clone.id = name;
  46693. clone.name = name;
  46694. return clone;
  46695. };
  46696. /**
  46697. * Serializes this PBR Material.
  46698. * @returns - An object with the serialized material.
  46699. */
  46700. PBRMaterial.prototype.serialize = function () {
  46701. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46702. serializationObject.customType = "BABYLON.PBRMaterial";
  46703. return serializationObject;
  46704. };
  46705. // Statics
  46706. /**
  46707. * Parses a PBR Material from a serialized object.
  46708. * @param source - Serialized object.
  46709. * @param scene - BJS scene instance.
  46710. * @param rootUrl - url for the scene object
  46711. * @returns - PBRMaterial
  46712. */
  46713. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46714. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46715. };
  46716. /**
  46717. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46718. */
  46719. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  46720. /**
  46721. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46722. */
  46723. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  46724. /**
  46725. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46726. */
  46727. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  46728. /**
  46729. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46730. * They are also discarded below the alpha cutoff threshold to improve performances.
  46731. */
  46732. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46733. /**
  46734. * Defines the default value of how much AO map is occluding the analytical lights
  46735. * (point spot...).
  46736. */
  46737. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  46738. __decorate([
  46739. BABYLON.serialize(),
  46740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46741. ], PBRMaterial.prototype, "directIntensity", void 0);
  46742. __decorate([
  46743. BABYLON.serialize(),
  46744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46745. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46746. __decorate([
  46747. BABYLON.serialize(),
  46748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46749. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46750. __decorate([
  46751. BABYLON.serialize(),
  46752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46753. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46754. __decorate([
  46755. BABYLON.serialize(),
  46756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46757. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46758. __decorate([
  46759. BABYLON.serializeAsTexture(),
  46760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46761. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46762. __decorate([
  46763. BABYLON.serializeAsTexture(),
  46764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46765. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46766. __decorate([
  46767. BABYLON.serialize(),
  46768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46769. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46770. __decorate([
  46771. BABYLON.serialize(),
  46772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46773. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  46774. __decorate([
  46775. BABYLON.serializeAsTexture(),
  46776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46777. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46778. __decorate([
  46779. BABYLON.serializeAsTexture(),
  46780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46781. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46782. __decorate([
  46783. BABYLON.serializeAsTexture(),
  46784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46785. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46786. __decorate([
  46787. BABYLON.serializeAsTexture(),
  46788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46789. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46790. __decorate([
  46791. BABYLON.serializeAsTexture(),
  46792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46793. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46794. __decorate([
  46795. BABYLON.serialize(),
  46796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46797. ], PBRMaterial.prototype, "metallic", void 0);
  46798. __decorate([
  46799. BABYLON.serialize(),
  46800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46801. ], PBRMaterial.prototype, "roughness", void 0);
  46802. __decorate([
  46803. BABYLON.serializeAsTexture(),
  46804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46805. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46806. __decorate([
  46807. BABYLON.serializeAsTexture(),
  46808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46809. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46810. __decorate([
  46811. BABYLON.serializeAsTexture(),
  46812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46813. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46814. __decorate([
  46815. BABYLON.serializeAsTexture(),
  46816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46817. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46818. __decorate([
  46819. BABYLON.serializeAsColor3("ambient"),
  46820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46821. ], PBRMaterial.prototype, "ambientColor", void 0);
  46822. __decorate([
  46823. BABYLON.serializeAsColor3("albedo"),
  46824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46825. ], PBRMaterial.prototype, "albedoColor", void 0);
  46826. __decorate([
  46827. BABYLON.serializeAsColor3("reflectivity"),
  46828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46829. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46830. __decorate([
  46831. BABYLON.serializeAsColor3("reflection"),
  46832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46833. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46834. __decorate([
  46835. BABYLON.serializeAsColor3("emissive"),
  46836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46837. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46838. __decorate([
  46839. BABYLON.serialize(),
  46840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46841. ], PBRMaterial.prototype, "microSurface", void 0);
  46842. __decorate([
  46843. BABYLON.serialize(),
  46844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46845. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46846. __decorate([
  46847. BABYLON.serialize(),
  46848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46849. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46850. __decorate([
  46851. BABYLON.serialize(),
  46852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46853. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46854. __decorate([
  46855. BABYLON.serialize(),
  46856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46857. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46858. __decorate([
  46859. BABYLON.serialize(),
  46860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46861. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46862. __decorate([
  46863. BABYLON.serialize(),
  46864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46865. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46866. __decorate([
  46867. BABYLON.serialize(),
  46868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46869. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46870. __decorate([
  46871. BABYLON.serialize(),
  46872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46873. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46874. __decorate([
  46875. BABYLON.serialize(),
  46876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46877. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46878. __decorate([
  46879. BABYLON.serialize(),
  46880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46881. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46882. __decorate([
  46883. BABYLON.serialize(),
  46884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46885. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46886. __decorate([
  46887. BABYLON.serialize(),
  46888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46889. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46890. __decorate([
  46891. BABYLON.serialize(),
  46892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46893. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46894. __decorate([
  46895. BABYLON.serialize(),
  46896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46897. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46898. __decorate([
  46899. BABYLON.serialize(),
  46900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46901. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46902. __decorate([
  46903. BABYLON.serialize()
  46904. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  46905. __decorate([
  46906. BABYLON.serialize()
  46907. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  46908. __decorate([
  46909. BABYLON.serialize(),
  46910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46911. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46912. __decorate([
  46913. BABYLON.serialize(),
  46914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46915. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46916. __decorate([
  46917. BABYLON.serialize(),
  46918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46919. ], PBRMaterial.prototype, "useParallax", void 0);
  46920. __decorate([
  46921. BABYLON.serialize(),
  46922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46923. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46924. __decorate([
  46925. BABYLON.serialize(),
  46926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46927. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46928. __decorate([
  46929. BABYLON.serialize(),
  46930. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46931. ], PBRMaterial.prototype, "disableLighting", void 0);
  46932. __decorate([
  46933. BABYLON.serialize(),
  46934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46935. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46936. __decorate([
  46937. BABYLON.serialize(),
  46938. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46939. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46940. __decorate([
  46941. BABYLON.serialize(),
  46942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46943. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46944. __decorate([
  46945. BABYLON.serialize(),
  46946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46947. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46948. __decorate([
  46949. BABYLON.serialize(),
  46950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46951. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46952. __decorate([
  46953. BABYLON.serialize(),
  46954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46955. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46956. __decorate([
  46957. BABYLON.serialize(),
  46958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46959. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46960. __decorate([
  46961. BABYLON.serializeAsTexture(),
  46962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46963. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46964. __decorate([
  46965. BABYLON.serialize(),
  46966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46967. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46968. __decorate([
  46969. BABYLON.serialize(),
  46970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46971. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46972. __decorate([
  46973. BABYLON.serialize(),
  46974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46975. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46976. __decorate([
  46977. BABYLON.serialize(),
  46978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46979. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46980. __decorate([
  46981. BABYLON.serialize(),
  46982. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46983. ], PBRMaterial.prototype, "unlit", void 0);
  46984. return PBRMaterial;
  46985. }(BABYLON.PBRBaseMaterial));
  46986. BABYLON.PBRMaterial = PBRMaterial;
  46987. })(BABYLON || (BABYLON = {}));
  46988. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46989. var BABYLON;
  46990. (function (BABYLON) {
  46991. /**
  46992. * The PBR material of BJS following the metal roughness convention.
  46993. *
  46994. * This fits to the PBR convention in the GLTF definition:
  46995. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46996. */
  46997. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46998. __extends(PBRMetallicRoughnessMaterial, _super);
  46999. /**
  47000. * Instantiates a new PBRMetalRoughnessMaterial instance.
  47001. *
  47002. * @param name The material name
  47003. * @param scene The scene the material will be use in.
  47004. */
  47005. function PBRMetallicRoughnessMaterial(name, scene) {
  47006. var _this = _super.call(this, name, scene) || this;
  47007. _this._useRoughnessFromMetallicTextureAlpha = false;
  47008. _this._useRoughnessFromMetallicTextureGreen = true;
  47009. _this._useMetallnessFromMetallicTextureBlue = true;
  47010. _this.metallic = 1.0;
  47011. _this.roughness = 1.0;
  47012. return _this;
  47013. }
  47014. /**
  47015. * Return the currrent class name of the material.
  47016. */
  47017. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  47018. return "PBRMetallicRoughnessMaterial";
  47019. };
  47020. /**
  47021. * Return the active textures of the material.
  47022. */
  47023. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  47024. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47025. if (this.baseTexture) {
  47026. activeTextures.push(this.baseTexture);
  47027. }
  47028. if (this.metallicRoughnessTexture) {
  47029. activeTextures.push(this.metallicRoughnessTexture);
  47030. }
  47031. return activeTextures;
  47032. };
  47033. /**
  47034. * Checks to see if a texture is used in the material.
  47035. * @param texture - Base texture to use.
  47036. * @returns - Boolean specifying if a texture is used in the material.
  47037. */
  47038. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  47039. if (_super.prototype.hasTexture.call(this, texture)) {
  47040. return true;
  47041. }
  47042. if (this.baseTexture === texture) {
  47043. return true;
  47044. }
  47045. if (this.metallicRoughnessTexture === texture) {
  47046. return true;
  47047. }
  47048. return false;
  47049. };
  47050. /**
  47051. * Makes a duplicate of the current material.
  47052. * @param name - name to use for the new material.
  47053. */
  47054. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47055. var _this = this;
  47056. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47057. clone.id = name;
  47058. clone.name = name;
  47059. return clone;
  47060. };
  47061. /**
  47062. * Serialize the material to a parsable JSON object.
  47063. */
  47064. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47065. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47066. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47067. return serializationObject;
  47068. };
  47069. /**
  47070. * Parses a JSON object correponding to the serialize function.
  47071. */
  47072. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47073. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47074. };
  47075. __decorate([
  47076. BABYLON.serializeAsColor3(),
  47077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47078. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47079. __decorate([
  47080. BABYLON.serializeAsTexture(),
  47081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47082. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47083. __decorate([
  47084. BABYLON.serialize(),
  47085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47086. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47087. __decorate([
  47088. BABYLON.serialize(),
  47089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47090. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47091. __decorate([
  47092. BABYLON.serializeAsTexture(),
  47093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47094. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47095. return PBRMetallicRoughnessMaterial;
  47096. }(BABYLON.PBRBaseSimpleMaterial));
  47097. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47098. })(BABYLON || (BABYLON = {}));
  47099. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47100. var BABYLON;
  47101. (function (BABYLON) {
  47102. /**
  47103. * The PBR material of BJS following the specular glossiness convention.
  47104. *
  47105. * This fits to the PBR convention in the GLTF definition:
  47106. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47107. */
  47108. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47109. __extends(PBRSpecularGlossinessMaterial, _super);
  47110. /**
  47111. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47112. *
  47113. * @param name The material name
  47114. * @param scene The scene the material will be use in.
  47115. */
  47116. function PBRSpecularGlossinessMaterial(name, scene) {
  47117. var _this = _super.call(this, name, scene) || this;
  47118. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47119. return _this;
  47120. }
  47121. /**
  47122. * Return the currrent class name of the material.
  47123. */
  47124. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47125. return "PBRSpecularGlossinessMaterial";
  47126. };
  47127. /**
  47128. * Return the active textures of the material.
  47129. */
  47130. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47131. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47132. if (this.diffuseTexture) {
  47133. activeTextures.push(this.diffuseTexture);
  47134. }
  47135. if (this.specularGlossinessTexture) {
  47136. activeTextures.push(this.specularGlossinessTexture);
  47137. }
  47138. return activeTextures;
  47139. };
  47140. /**
  47141. * Checks to see if a texture is used in the material.
  47142. * @param texture - Base texture to use.
  47143. * @returns - Boolean specifying if a texture is used in the material.
  47144. */
  47145. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47146. if (_super.prototype.hasTexture.call(this, texture)) {
  47147. return true;
  47148. }
  47149. if (this.diffuseTexture === texture) {
  47150. return true;
  47151. }
  47152. if (this.specularGlossinessTexture === texture) {
  47153. return true;
  47154. }
  47155. return false;
  47156. };
  47157. /**
  47158. * Makes a duplicate of the current material.
  47159. * @param name - name to use for the new material.
  47160. */
  47161. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47162. var _this = this;
  47163. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47164. clone.id = name;
  47165. clone.name = name;
  47166. return clone;
  47167. };
  47168. /**
  47169. * Serialize the material to a parsable JSON object.
  47170. */
  47171. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47172. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47173. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47174. return serializationObject;
  47175. };
  47176. /**
  47177. * Parses a JSON object correponding to the serialize function.
  47178. */
  47179. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47180. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47181. };
  47182. __decorate([
  47183. BABYLON.serializeAsColor3("diffuse"),
  47184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47185. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47186. __decorate([
  47187. BABYLON.serializeAsTexture(),
  47188. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47189. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47190. __decorate([
  47191. BABYLON.serializeAsColor3("specular"),
  47192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47193. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47194. __decorate([
  47195. BABYLON.serialize(),
  47196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47197. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47198. __decorate([
  47199. BABYLON.serializeAsTexture(),
  47200. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47201. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47202. return PBRSpecularGlossinessMaterial;
  47203. }(BABYLON.PBRBaseSimpleMaterial));
  47204. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47205. })(BABYLON || (BABYLON = {}));
  47206. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47207. var BABYLON;
  47208. (function (BABYLON) {
  47209. /**
  47210. * This is a list of all the different input types that are available in the application.
  47211. * Fo instance: ArcRotateCameraGamepadInput...
  47212. */
  47213. BABYLON.CameraInputTypes = {};
  47214. /**
  47215. * This represents the input manager used within a camera.
  47216. * It helps dealing with all the different kind of input attached to a camera.
  47217. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47218. */
  47219. var CameraInputsManager = /** @class */ (function () {
  47220. /**
  47221. * Instantiate a new Camera Input Manager.
  47222. * @param camera Defines the camera the input manager blongs to
  47223. */
  47224. function CameraInputsManager(camera) {
  47225. this.attached = {};
  47226. this.camera = camera;
  47227. this.checkInputs = function () { };
  47228. }
  47229. /**
  47230. * Add an input method to a camera
  47231. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47232. * @param input camera input method
  47233. */
  47234. CameraInputsManager.prototype.add = function (input) {
  47235. var type = input.getSimpleName();
  47236. if (this.attached[type]) {
  47237. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47238. return;
  47239. }
  47240. this.attached[type] = input;
  47241. input.camera = this.camera;
  47242. //for checkInputs, we are dynamically creating a function
  47243. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47244. if (input.checkInputs) {
  47245. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47246. }
  47247. if (this.attachedElement) {
  47248. input.attachControl(this.attachedElement);
  47249. }
  47250. };
  47251. /**
  47252. * Remove a specific input method from a camera
  47253. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47254. * @param inputToRemove camera input method
  47255. */
  47256. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47257. for (var cam in this.attached) {
  47258. var input = this.attached[cam];
  47259. if (input === inputToRemove) {
  47260. input.detachControl(this.attachedElement);
  47261. input.camera = null;
  47262. delete this.attached[cam];
  47263. this.rebuildInputCheck();
  47264. }
  47265. }
  47266. };
  47267. /**
  47268. * Remove a specific input type from a camera
  47269. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  47270. * @param inputType the type of the input to remove
  47271. */
  47272. CameraInputsManager.prototype.removeByType = function (inputType) {
  47273. for (var cam in this.attached) {
  47274. var input = this.attached[cam];
  47275. if (input.getClassName() === inputType) {
  47276. input.detachControl(this.attachedElement);
  47277. input.camera = null;
  47278. delete this.attached[cam];
  47279. this.rebuildInputCheck();
  47280. }
  47281. }
  47282. };
  47283. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47284. var current = this.checkInputs;
  47285. return function () {
  47286. current();
  47287. fn();
  47288. };
  47289. };
  47290. /**
  47291. * Attach the input controls to the currently attached dom element to listen the events from.
  47292. * @param input Defines the input to attach
  47293. */
  47294. CameraInputsManager.prototype.attachInput = function (input) {
  47295. if (this.attachedElement) {
  47296. input.attachControl(this.attachedElement, this.noPreventDefault);
  47297. }
  47298. };
  47299. /**
  47300. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  47301. * @param element Defines the dom element to collect the events from
  47302. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47303. */
  47304. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47305. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47306. if (this.attachedElement) {
  47307. return;
  47308. }
  47309. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47310. this.attachedElement = element;
  47311. this.noPreventDefault = noPreventDefault;
  47312. for (var cam in this.attached) {
  47313. this.attached[cam].attachControl(element, noPreventDefault);
  47314. }
  47315. };
  47316. /**
  47317. * Detach the current manager inputs controls from a specific dom element.
  47318. * @param element Defines the dom element to collect the events from
  47319. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  47320. */
  47321. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47322. if (disconnect === void 0) { disconnect = false; }
  47323. if (this.attachedElement !== element) {
  47324. return;
  47325. }
  47326. for (var cam in this.attached) {
  47327. this.attached[cam].detachControl(element);
  47328. if (disconnect) {
  47329. this.attached[cam].camera = null;
  47330. }
  47331. }
  47332. this.attachedElement = null;
  47333. };
  47334. /**
  47335. * Rebuild the dynamic inputCheck function from the current list of
  47336. * defined inputs in the manager.
  47337. */
  47338. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47339. this.checkInputs = function () { };
  47340. for (var cam in this.attached) {
  47341. var input = this.attached[cam];
  47342. if (input.checkInputs) {
  47343. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47344. }
  47345. }
  47346. };
  47347. /**
  47348. * Remove all attached input methods from a camera
  47349. */
  47350. CameraInputsManager.prototype.clear = function () {
  47351. if (this.attachedElement) {
  47352. this.detachElement(this.attachedElement, true);
  47353. }
  47354. this.attached = {};
  47355. this.attachedElement = null;
  47356. this.checkInputs = function () { };
  47357. };
  47358. /**
  47359. * Serialize the current input manager attached to a camera.
  47360. * This ensures than once parsed,
  47361. * the input associated to the camera will be identical to the current ones
  47362. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  47363. */
  47364. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47365. var inputs = {};
  47366. for (var cam in this.attached) {
  47367. var input = this.attached[cam];
  47368. var res = BABYLON.SerializationHelper.Serialize(input);
  47369. inputs[input.getClassName()] = res;
  47370. }
  47371. serializedCamera.inputsmgr = inputs;
  47372. };
  47373. /**
  47374. * Parses an input manager serialized JSON to restore the previous list of inputs
  47375. * and states associated to a camera.
  47376. * @param parsedCamera Defines the JSON to parse
  47377. */
  47378. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47379. var parsedInputs = parsedCamera.inputsmgr;
  47380. if (parsedInputs) {
  47381. this.clear();
  47382. for (var n in parsedInputs) {
  47383. var construct = BABYLON.CameraInputTypes[n];
  47384. if (construct) {
  47385. var parsedinput = parsedInputs[n];
  47386. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47387. this.add(input);
  47388. }
  47389. }
  47390. }
  47391. else {
  47392. //2016-03-08 this part is for managing backward compatibility
  47393. for (var n in this.attached) {
  47394. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47395. if (construct) {
  47396. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47397. this.remove(this.attached[n]);
  47398. this.add(input);
  47399. }
  47400. }
  47401. }
  47402. };
  47403. return CameraInputsManager;
  47404. }());
  47405. BABYLON.CameraInputsManager = CameraInputsManager;
  47406. })(BABYLON || (BABYLON = {}));
  47407. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47408. var BABYLON;
  47409. (function (BABYLON) {
  47410. /**
  47411. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  47412. * This is the base of the follow, arc rotate cameras and Free camera
  47413. * @see http://doc.babylonjs.com/features/cameras
  47414. */
  47415. var TargetCamera = /** @class */ (function (_super) {
  47416. __extends(TargetCamera, _super);
  47417. /**
  47418. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  47419. * This is the base of the follow, arc rotate cameras and Free camera
  47420. * @see http://doc.babylonjs.com/features/cameras
  47421. * @param name Defines the name of the camera in the scene
  47422. * @param position Defines the start position of the camera in the scene
  47423. * @param scene Defines the scene the camera belongs to
  47424. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47425. */
  47426. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47427. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47428. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47429. /**
  47430. * Define the current direction the camera is moving to
  47431. */
  47432. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47433. /**
  47434. * Define the current rotation the camera is rotating to
  47435. */
  47436. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47437. /**
  47438. * Define the current rotation of the camera
  47439. */
  47440. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47441. /**
  47442. * Define the current speed of the camera
  47443. */
  47444. _this.speed = 2.0;
  47445. /**
  47446. * Add cconstraint to the camera to prevent it to move freely in all directions and
  47447. * around all axis.
  47448. */
  47449. _this.noRotationConstraint = false;
  47450. /**
  47451. * Define the current target of the camera as an object or a position.
  47452. */
  47453. _this.lockedTarget = null;
  47454. /** @hidden */
  47455. _this._currentTarget = BABYLON.Vector3.Zero();
  47456. /** @hidden */
  47457. _this._viewMatrix = BABYLON.Matrix.Zero();
  47458. /** @hidden */
  47459. _this._camMatrix = BABYLON.Matrix.Zero();
  47460. /** @hidden */
  47461. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47462. /** @hidden */
  47463. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47464. /** @hidden */
  47465. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47466. /** @hidden */
  47467. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47468. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47469. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47470. _this._defaultUp = BABYLON.Vector3.Up();
  47471. _this._cachedRotationZ = 0;
  47472. return _this;
  47473. }
  47474. /**
  47475. * Gets the position in front of the camera at a given distance.
  47476. * @param distance The distance from the camera we want the position to be
  47477. * @returns the position
  47478. */
  47479. TargetCamera.prototype.getFrontPosition = function (distance) {
  47480. this.getWorldMatrix();
  47481. var direction = this.getTarget().subtract(this.position);
  47482. direction.normalize();
  47483. direction.scaleInPlace(distance);
  47484. return this.globalPosition.add(direction);
  47485. };
  47486. /** @hidden */
  47487. TargetCamera.prototype._getLockedTargetPosition = function () {
  47488. if (!this.lockedTarget) {
  47489. return null;
  47490. }
  47491. if (this.lockedTarget.absolutePosition) {
  47492. this.lockedTarget.computeWorldMatrix();
  47493. }
  47494. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47495. };
  47496. /**
  47497. * Store current camera state of the camera (fov, position, rotation, etc..)
  47498. * @returns the camera
  47499. */
  47500. TargetCamera.prototype.storeState = function () {
  47501. this._storedPosition = this.position.clone();
  47502. this._storedRotation = this.rotation.clone();
  47503. if (this.rotationQuaternion) {
  47504. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47505. }
  47506. return _super.prototype.storeState.call(this);
  47507. };
  47508. /**
  47509. * Restored camera state. You must call storeState() first
  47510. * @returns whether it was successful or not
  47511. * @hidden
  47512. */
  47513. TargetCamera.prototype._restoreStateValues = function () {
  47514. if (!_super.prototype._restoreStateValues.call(this)) {
  47515. return false;
  47516. }
  47517. this.position = this._storedPosition.clone();
  47518. this.rotation = this._storedRotation.clone();
  47519. if (this.rotationQuaternion) {
  47520. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47521. }
  47522. this.cameraDirection.copyFromFloats(0, 0, 0);
  47523. this.cameraRotation.copyFromFloats(0, 0);
  47524. return true;
  47525. };
  47526. /** @hidden */
  47527. TargetCamera.prototype._initCache = function () {
  47528. _super.prototype._initCache.call(this);
  47529. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47530. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47531. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47532. };
  47533. /** @hidden */
  47534. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47535. if (!ignoreParentClass) {
  47536. _super.prototype._updateCache.call(this);
  47537. }
  47538. var lockedTargetPosition = this._getLockedTargetPosition();
  47539. if (!lockedTargetPosition) {
  47540. this._cache.lockedTarget = null;
  47541. }
  47542. else {
  47543. if (!this._cache.lockedTarget) {
  47544. this._cache.lockedTarget = lockedTargetPosition.clone();
  47545. }
  47546. else {
  47547. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47548. }
  47549. }
  47550. this._cache.rotation.copyFrom(this.rotation);
  47551. if (this.rotationQuaternion)
  47552. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47553. };
  47554. // Synchronized
  47555. /** @hidden */
  47556. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47557. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47558. return false;
  47559. }
  47560. var lockedTargetPosition = this._getLockedTargetPosition();
  47561. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47562. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47563. };
  47564. // Methods
  47565. /** @hidden */
  47566. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47567. var engine = this.getEngine();
  47568. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47569. };
  47570. // Target
  47571. /** @hidden */
  47572. TargetCamera.prototype.setTarget = function (target) {
  47573. this.upVector.normalize();
  47574. if (this.position.z === target.z) {
  47575. this.position.z += BABYLON.Epsilon;
  47576. }
  47577. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  47578. this._camMatrix.invert();
  47579. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47580. var vDir = target.subtract(this.position);
  47581. if (vDir.x >= 0.0) {
  47582. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47583. }
  47584. else {
  47585. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47586. }
  47587. this.rotation.z = 0;
  47588. if (isNaN(this.rotation.x)) {
  47589. this.rotation.x = 0;
  47590. }
  47591. if (isNaN(this.rotation.y)) {
  47592. this.rotation.y = 0;
  47593. }
  47594. if (isNaN(this.rotation.z)) {
  47595. this.rotation.z = 0;
  47596. }
  47597. if (this.rotationQuaternion) {
  47598. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47599. }
  47600. };
  47601. /**
  47602. * Return the current target position of the camera. This value is expressed in local space.
  47603. * @returns the target position
  47604. */
  47605. TargetCamera.prototype.getTarget = function () {
  47606. return this._currentTarget;
  47607. };
  47608. /** @hidden */
  47609. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47610. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47611. };
  47612. /** @hidden */
  47613. TargetCamera.prototype._updatePosition = function () {
  47614. if (this.parent) {
  47615. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47616. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47617. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47618. return;
  47619. }
  47620. this.position.addInPlace(this.cameraDirection);
  47621. };
  47622. /** @hidden */
  47623. TargetCamera.prototype._checkInputs = function () {
  47624. var needToMove = this._decideIfNeedsToMove();
  47625. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47626. // Move
  47627. if (needToMove) {
  47628. this._updatePosition();
  47629. }
  47630. // Rotate
  47631. if (needToRotate) {
  47632. this.rotation.x += this.cameraRotation.x;
  47633. this.rotation.y += this.cameraRotation.y;
  47634. //rotate, if quaternion is set and rotation was used
  47635. if (this.rotationQuaternion) {
  47636. var len = this.rotation.lengthSquared();
  47637. if (len) {
  47638. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47639. }
  47640. }
  47641. if (!this.noRotationConstraint) {
  47642. var limit = (Math.PI / 2) * 0.95;
  47643. if (this.rotation.x > limit)
  47644. this.rotation.x = limit;
  47645. if (this.rotation.x < -limit)
  47646. this.rotation.x = -limit;
  47647. }
  47648. }
  47649. // Inertia
  47650. if (needToMove) {
  47651. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47652. this.cameraDirection.x = 0;
  47653. }
  47654. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47655. this.cameraDirection.y = 0;
  47656. }
  47657. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47658. this.cameraDirection.z = 0;
  47659. }
  47660. this.cameraDirection.scaleInPlace(this.inertia);
  47661. }
  47662. if (needToRotate) {
  47663. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47664. this.cameraRotation.x = 0;
  47665. }
  47666. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47667. this.cameraRotation.y = 0;
  47668. }
  47669. this.cameraRotation.scaleInPlace(this.inertia);
  47670. }
  47671. _super.prototype._checkInputs.call(this);
  47672. };
  47673. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47674. if (this.rotationQuaternion) {
  47675. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47676. }
  47677. else {
  47678. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47679. }
  47680. };
  47681. /**
  47682. * 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)
  47683. * @returns the current camera
  47684. */
  47685. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  47686. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  47687. return this;
  47688. };
  47689. /** @hidden */
  47690. TargetCamera.prototype._getViewMatrix = function () {
  47691. if (this.lockedTarget) {
  47692. this.setTarget(this._getLockedTargetPosition());
  47693. }
  47694. // Compute
  47695. this._updateCameraRotationMatrix();
  47696. // Apply the changed rotation to the upVector.
  47697. if (this._cachedRotationZ != this.rotation.z) {
  47698. this._rotateUpVectorWithCameraRotationMatrix();
  47699. this._cachedRotationZ = this.rotation.z;
  47700. }
  47701. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47702. // Computing target and final matrix
  47703. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47704. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  47705. return this._viewMatrix;
  47706. };
  47707. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47708. if (this.parent) {
  47709. var parentWorldMatrix = this.parent.getWorldMatrix();
  47710. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  47711. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47712. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47713. this._markSyncedWithParent();
  47714. }
  47715. else {
  47716. this._globalPosition.copyFrom(position);
  47717. this._globalCurrentTarget.copyFrom(target);
  47718. this._globalCurrentUpVector.copyFrom(up);
  47719. }
  47720. if (this.getScene().useRightHandedSystem) {
  47721. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47722. }
  47723. else {
  47724. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47725. }
  47726. };
  47727. /**
  47728. * @hidden
  47729. */
  47730. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47731. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47732. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47733. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47734. if (!this.rotationQuaternion) {
  47735. this.rotationQuaternion = new BABYLON.Quaternion();
  47736. }
  47737. rigCamera._cameraRigParams = {};
  47738. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47739. }
  47740. return rigCamera;
  47741. }
  47742. return null;
  47743. };
  47744. /**
  47745. * @hidden
  47746. */
  47747. TargetCamera.prototype._updateRigCameras = function () {
  47748. var camLeft = this._rigCameras[0];
  47749. var camRight = this._rigCameras[1];
  47750. switch (this.cameraRigMode) {
  47751. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47752. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47753. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47754. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47755. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47756. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47757. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47758. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47759. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47760. camLeft.setTarget(this.getTarget());
  47761. camRight.setTarget(this.getTarget());
  47762. break;
  47763. case BABYLON.Camera.RIG_MODE_VR:
  47764. if (camLeft.rotationQuaternion) {
  47765. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47766. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47767. }
  47768. else {
  47769. camLeft.rotation.copyFrom(this.rotation);
  47770. camRight.rotation.copyFrom(this.rotation);
  47771. }
  47772. camLeft.position.copyFrom(this.position);
  47773. camRight.position.copyFrom(this.position);
  47774. break;
  47775. }
  47776. _super.prototype._updateRigCameras.call(this);
  47777. };
  47778. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47779. if (!this._rigCamTransformMatrix) {
  47780. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47781. }
  47782. var target = this.getTarget();
  47783. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47784. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47785. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47786. };
  47787. /**
  47788. * Gets the current object class name.
  47789. * @return the class name
  47790. */
  47791. TargetCamera.prototype.getClassName = function () {
  47792. return "TargetCamera";
  47793. };
  47794. __decorate([
  47795. BABYLON.serializeAsVector3()
  47796. ], TargetCamera.prototype, "rotation", void 0);
  47797. __decorate([
  47798. BABYLON.serialize()
  47799. ], TargetCamera.prototype, "speed", void 0);
  47800. __decorate([
  47801. BABYLON.serializeAsMeshReference("lockedTargetId")
  47802. ], TargetCamera.prototype, "lockedTarget", void 0);
  47803. return TargetCamera;
  47804. }(BABYLON.Camera));
  47805. BABYLON.TargetCamera = TargetCamera;
  47806. })(BABYLON || (BABYLON = {}));
  47807. //# sourceMappingURL=babylon.targetCamera.js.map
  47808. var BABYLON;
  47809. (function (BABYLON) {
  47810. /**
  47811. * Manage the mouse inputs to control the movement of a free camera.
  47812. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47813. */
  47814. var FreeCameraMouseInput = /** @class */ (function () {
  47815. /**
  47816. * Manage the mouse inputs to control the movement of a free camera.
  47817. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47818. * @param touchEnabled Defines if touch is enabled or not
  47819. */
  47820. function FreeCameraMouseInput(
  47821. /**
  47822. * Define if touch is enabled in the mouse input
  47823. */
  47824. touchEnabled) {
  47825. if (touchEnabled === void 0) { touchEnabled = true; }
  47826. this.touchEnabled = touchEnabled;
  47827. /**
  47828. * Defines the buttons associated with the input to handle camera move.
  47829. */
  47830. this.buttons = [0, 1, 2];
  47831. /**
  47832. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  47833. */
  47834. this.angularSensibility = 2000.0;
  47835. this.previousPosition = null;
  47836. }
  47837. /**
  47838. * Attach the input controls to a specific dom element to get the input from.
  47839. * @param element Defines the element the controls should be listened from
  47840. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47841. */
  47842. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47843. var _this = this;
  47844. var engine = this.camera.getEngine();
  47845. if (!this._pointerInput) {
  47846. this._pointerInput = function (p, s) {
  47847. var evt = p.event;
  47848. if (engine.isInVRExclusivePointerMode) {
  47849. return;
  47850. }
  47851. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47852. return;
  47853. }
  47854. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47855. return;
  47856. }
  47857. var srcElement = (evt.srcElement || evt.target);
  47858. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47859. try {
  47860. srcElement.setPointerCapture(evt.pointerId);
  47861. }
  47862. catch (e) {
  47863. //Nothing to do with the error. Execution will continue.
  47864. }
  47865. _this.previousPosition = {
  47866. x: evt.clientX,
  47867. y: evt.clientY
  47868. };
  47869. if (!noPreventDefault) {
  47870. evt.preventDefault();
  47871. element.focus();
  47872. }
  47873. }
  47874. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47875. try {
  47876. srcElement.releasePointerCapture(evt.pointerId);
  47877. }
  47878. catch (e) {
  47879. //Nothing to do with the error.
  47880. }
  47881. _this.previousPosition = null;
  47882. if (!noPreventDefault) {
  47883. evt.preventDefault();
  47884. }
  47885. }
  47886. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47887. if (!_this.previousPosition || engine.isPointerLock) {
  47888. return;
  47889. }
  47890. var offsetX = evt.clientX - _this.previousPosition.x;
  47891. if (_this.camera.getScene().useRightHandedSystem)
  47892. offsetX *= -1;
  47893. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47894. offsetX *= -1;
  47895. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47896. var offsetY = evt.clientY - _this.previousPosition.y;
  47897. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47898. _this.previousPosition = {
  47899. x: evt.clientX,
  47900. y: evt.clientY
  47901. };
  47902. if (!noPreventDefault) {
  47903. evt.preventDefault();
  47904. }
  47905. }
  47906. };
  47907. }
  47908. this._onMouseMove = function (evt) {
  47909. if (!engine.isPointerLock) {
  47910. return;
  47911. }
  47912. if (engine.isInVRExclusivePointerMode) {
  47913. return;
  47914. }
  47915. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47916. if (_this.camera.getScene().useRightHandedSystem)
  47917. offsetX *= -1;
  47918. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47919. offsetX *= -1;
  47920. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47921. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47922. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47923. _this.previousPosition = null;
  47924. if (!noPreventDefault) {
  47925. evt.preventDefault();
  47926. }
  47927. };
  47928. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47929. element.addEventListener("mousemove", this._onMouseMove, false);
  47930. };
  47931. /**
  47932. * Detach the current controls from the specified dom element.
  47933. * @param element Defines the element to stop listening the inputs from
  47934. */
  47935. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47936. if (this._observer && element) {
  47937. this.camera.getScene().onPointerObservable.remove(this._observer);
  47938. if (this._onMouseMove) {
  47939. element.removeEventListener("mousemove", this._onMouseMove);
  47940. }
  47941. this._observer = null;
  47942. this._onMouseMove = null;
  47943. this.previousPosition = null;
  47944. }
  47945. };
  47946. /**
  47947. * Gets the class name of the current intput.
  47948. * @returns the class name
  47949. */
  47950. FreeCameraMouseInput.prototype.getClassName = function () {
  47951. return "FreeCameraMouseInput";
  47952. };
  47953. /**
  47954. * Get the friendly name associated with the input class.
  47955. * @returns the input friendly name
  47956. */
  47957. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47958. return "mouse";
  47959. };
  47960. __decorate([
  47961. BABYLON.serialize()
  47962. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47963. __decorate([
  47964. BABYLON.serialize()
  47965. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47966. return FreeCameraMouseInput;
  47967. }());
  47968. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47969. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47970. })(BABYLON || (BABYLON = {}));
  47971. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47972. var BABYLON;
  47973. (function (BABYLON) {
  47974. /**
  47975. * Manage the keyboard inputs to control the movement of a free camera.
  47976. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47977. */
  47978. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47979. function FreeCameraKeyboardMoveInput() {
  47980. /**
  47981. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  47982. */
  47983. this.keysUp = [38];
  47984. /**
  47985. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  47986. */
  47987. this.keysDown = [40];
  47988. /**
  47989. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  47990. */
  47991. this.keysLeft = [37];
  47992. /**
  47993. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  47994. */
  47995. this.keysRight = [39];
  47996. this._keys = new Array();
  47997. }
  47998. /**
  47999. * Attach the input controls to a specific dom element to get the input from.
  48000. * @param element Defines the element the controls should be listened from
  48001. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48002. */
  48003. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48004. var _this = this;
  48005. if (this._onCanvasBlurObserver) {
  48006. return;
  48007. }
  48008. this._scene = this.camera.getScene();
  48009. this._engine = this._scene.getEngine();
  48010. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48011. _this._keys = [];
  48012. });
  48013. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48014. var evt = info.event;
  48015. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48016. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48017. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48018. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48019. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48020. var index = _this._keys.indexOf(evt.keyCode);
  48021. if (index === -1) {
  48022. _this._keys.push(evt.keyCode);
  48023. }
  48024. if (!noPreventDefault) {
  48025. evt.preventDefault();
  48026. }
  48027. }
  48028. }
  48029. else {
  48030. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48031. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48032. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48033. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48034. var index = _this._keys.indexOf(evt.keyCode);
  48035. if (index >= 0) {
  48036. _this._keys.splice(index, 1);
  48037. }
  48038. if (!noPreventDefault) {
  48039. evt.preventDefault();
  48040. }
  48041. }
  48042. }
  48043. });
  48044. };
  48045. /**
  48046. * Detach the current controls from the specified dom element.
  48047. * @param element Defines the element to stop listening the inputs from
  48048. */
  48049. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48050. if (this._scene) {
  48051. if (this._onKeyboardObserver) {
  48052. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48053. }
  48054. if (this._onCanvasBlurObserver) {
  48055. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48056. }
  48057. this._onKeyboardObserver = null;
  48058. this._onCanvasBlurObserver = null;
  48059. }
  48060. this._keys = [];
  48061. };
  48062. /**
  48063. * Update the current camera state depending on the inputs that have been used this frame.
  48064. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  48065. */
  48066. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48067. if (this._onKeyboardObserver) {
  48068. var camera = this.camera;
  48069. // Keyboard
  48070. for (var index = 0; index < this._keys.length; index++) {
  48071. var keyCode = this._keys[index];
  48072. var speed = camera._computeLocalCameraSpeed();
  48073. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48074. camera._localDirection.copyFromFloats(-speed, 0, 0);
  48075. }
  48076. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48077. camera._localDirection.copyFromFloats(0, 0, speed);
  48078. }
  48079. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48080. camera._localDirection.copyFromFloats(speed, 0, 0);
  48081. }
  48082. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48083. camera._localDirection.copyFromFloats(0, 0, -speed);
  48084. }
  48085. if (camera.getScene().useRightHandedSystem) {
  48086. camera._localDirection.z *= -1;
  48087. }
  48088. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  48089. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  48090. camera.cameraDirection.addInPlace(camera._transformedDirection);
  48091. }
  48092. }
  48093. };
  48094. /**
  48095. * Gets the class name of the current intput.
  48096. * @returns the class name
  48097. */
  48098. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  48099. return "FreeCameraKeyboardMoveInput";
  48100. };
  48101. /** @hidden */
  48102. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  48103. this._keys = [];
  48104. };
  48105. /**
  48106. * Get the friendly name associated with the input class.
  48107. * @returns the input friendly name
  48108. */
  48109. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48110. return "keyboard";
  48111. };
  48112. __decorate([
  48113. BABYLON.serialize()
  48114. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48115. __decorate([
  48116. BABYLON.serialize()
  48117. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48118. __decorate([
  48119. BABYLON.serialize()
  48120. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48121. __decorate([
  48122. BABYLON.serialize()
  48123. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48124. return FreeCameraKeyboardMoveInput;
  48125. }());
  48126. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  48127. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  48128. })(BABYLON || (BABYLON = {}));
  48129. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  48130. var BABYLON;
  48131. (function (BABYLON) {
  48132. /**
  48133. * Default Inputs manager for the FreeCamera.
  48134. * It groups all the default supported inputs for ease of use.
  48135. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48136. */
  48137. var FreeCameraInputsManager = /** @class */ (function (_super) {
  48138. __extends(FreeCameraInputsManager, _super);
  48139. /**
  48140. * Instantiates a new FreeCameraInputsManager.
  48141. * @param camera Defines the camera the inputs belong to
  48142. */
  48143. function FreeCameraInputsManager(camera) {
  48144. return _super.call(this, camera) || this;
  48145. }
  48146. /**
  48147. * Add keyboard input support to the input manager.
  48148. * @returns the current input manager
  48149. */
  48150. FreeCameraInputsManager.prototype.addKeyboard = function () {
  48151. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  48152. return this;
  48153. };
  48154. /**
  48155. * Add mouse input support to the input manager.
  48156. * @returns the current input manager
  48157. */
  48158. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  48159. if (touchEnabled === void 0) { touchEnabled = true; }
  48160. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  48161. return this;
  48162. };
  48163. /**
  48164. * Add orientation input support to the input manager.
  48165. * @returns the current input manager
  48166. */
  48167. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  48168. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  48169. return this;
  48170. };
  48171. /**
  48172. * Add touch input support to the input manager.
  48173. * @returns the current input manager
  48174. */
  48175. FreeCameraInputsManager.prototype.addTouch = function () {
  48176. this.add(new BABYLON.FreeCameraTouchInput());
  48177. return this;
  48178. };
  48179. /**
  48180. * Add virtual joystick input support to the input manager.
  48181. * @returns the current input manager
  48182. */
  48183. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  48184. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  48185. return this;
  48186. };
  48187. return FreeCameraInputsManager;
  48188. }(BABYLON.CameraInputsManager));
  48189. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  48190. })(BABYLON || (BABYLON = {}));
  48191. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  48192. var BABYLON;
  48193. (function (BABYLON) {
  48194. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  48195. // Forcing to use the Universal camera
  48196. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  48197. });
  48198. /**
  48199. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  48200. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  48201. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  48202. */
  48203. var FreeCamera = /** @class */ (function (_super) {
  48204. __extends(FreeCamera, _super);
  48205. /**
  48206. * Instantiates a Free Camera.
  48207. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  48208. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  48209. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  48210. * @param name Define the name of the camera in the scene
  48211. * @param position Define the start position of the camera in the scene
  48212. * @param scene Define the scene the camera belongs to
  48213. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48214. */
  48215. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48216. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48217. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48218. /**
  48219. * Define the collision ellipsoid of the camera.
  48220. * This is helpful to simulate a camera body like the player body around the camera
  48221. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  48222. */
  48223. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  48224. /**
  48225. * Define an offset for the position of the ellipsoid around the camera.
  48226. * This can be helpful to determine the center of the body near the gravity center of the body
  48227. * instead of its head.
  48228. */
  48229. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  48230. /**
  48231. * Enable or disable collisions of the camera with the rest of the scene objects.
  48232. */
  48233. _this.checkCollisions = false;
  48234. /**
  48235. * Enable or disable gravity on the camera.
  48236. */
  48237. _this.applyGravity = false;
  48238. _this._needMoveForGravity = false;
  48239. _this._oldPosition = BABYLON.Vector3.Zero();
  48240. _this._diffPosition = BABYLON.Vector3.Zero();
  48241. _this._newPosition = BABYLON.Vector3.Zero();
  48242. // Collisions
  48243. _this._collisionMask = -1;
  48244. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48245. if (collidedMesh === void 0) { collidedMesh = null; }
  48246. //TODO move this to the collision coordinator!
  48247. if (_this.getScene().workerCollisions)
  48248. newPosition.multiplyInPlace(_this._collider._radius);
  48249. var updatePosition = function (newPos) {
  48250. _this._newPosition.copyFrom(newPos);
  48251. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  48252. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  48253. _this.position.addInPlace(_this._diffPosition);
  48254. if (_this.onCollide && collidedMesh) {
  48255. _this.onCollide(collidedMesh);
  48256. }
  48257. }
  48258. };
  48259. updatePosition(newPosition);
  48260. };
  48261. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  48262. _this.inputs.addKeyboard().addMouse();
  48263. return _this;
  48264. }
  48265. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  48266. /**
  48267. * Gets the input sensibility for a mouse input. (default is 2000.0)
  48268. * Higher values reduce sensitivity.
  48269. */
  48270. get: function () {
  48271. var mouse = this.inputs.attached["mouse"];
  48272. if (mouse)
  48273. return mouse.angularSensibility;
  48274. return 0;
  48275. },
  48276. /**
  48277. * Sets the input sensibility for a mouse input. (default is 2000.0)
  48278. * Higher values reduce sensitivity.
  48279. */
  48280. set: function (value) {
  48281. var mouse = this.inputs.attached["mouse"];
  48282. if (mouse)
  48283. mouse.angularSensibility = value;
  48284. },
  48285. enumerable: true,
  48286. configurable: true
  48287. });
  48288. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  48289. /**
  48290. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48291. */
  48292. get: function () {
  48293. var keyboard = this.inputs.attached["keyboard"];
  48294. if (keyboard)
  48295. return keyboard.keysUp;
  48296. return [];
  48297. },
  48298. set: function (value) {
  48299. var keyboard = this.inputs.attached["keyboard"];
  48300. if (keyboard)
  48301. keyboard.keysUp = value;
  48302. },
  48303. enumerable: true,
  48304. configurable: true
  48305. });
  48306. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  48307. /**
  48308. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48309. */
  48310. get: function () {
  48311. var keyboard = this.inputs.attached["keyboard"];
  48312. if (keyboard)
  48313. return keyboard.keysDown;
  48314. return [];
  48315. },
  48316. set: function (value) {
  48317. var keyboard = this.inputs.attached["keyboard"];
  48318. if (keyboard)
  48319. keyboard.keysDown = value;
  48320. },
  48321. enumerable: true,
  48322. configurable: true
  48323. });
  48324. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  48325. /**
  48326. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48327. */
  48328. get: function () {
  48329. var keyboard = this.inputs.attached["keyboard"];
  48330. if (keyboard)
  48331. return keyboard.keysLeft;
  48332. return [];
  48333. },
  48334. set: function (value) {
  48335. var keyboard = this.inputs.attached["keyboard"];
  48336. if (keyboard)
  48337. keyboard.keysLeft = value;
  48338. },
  48339. enumerable: true,
  48340. configurable: true
  48341. });
  48342. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  48343. /**
  48344. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48345. */
  48346. get: function () {
  48347. var keyboard = this.inputs.attached["keyboard"];
  48348. if (keyboard)
  48349. return keyboard.keysRight;
  48350. return [];
  48351. },
  48352. set: function (value) {
  48353. var keyboard = this.inputs.attached["keyboard"];
  48354. if (keyboard)
  48355. keyboard.keysRight = value;
  48356. },
  48357. enumerable: true,
  48358. configurable: true
  48359. });
  48360. /**
  48361. * Attached controls to the current camera.
  48362. * @param element Defines the element the controls should be listened from
  48363. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48364. */
  48365. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48366. this.inputs.attachElement(element, noPreventDefault);
  48367. };
  48368. /**
  48369. * Detach the current controls from the camera.
  48370. * The camera will stop reacting to inputs.
  48371. * @param element Defines the element to stop listening the inputs from
  48372. */
  48373. FreeCamera.prototype.detachControl = function (element) {
  48374. this.inputs.detachElement(element);
  48375. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48376. this.cameraRotation = new BABYLON.Vector2(0, 0);
  48377. };
  48378. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  48379. /**
  48380. * Define a collision mask to limit the list of object the camera can collide with
  48381. */
  48382. get: function () {
  48383. return this._collisionMask;
  48384. },
  48385. set: function (mask) {
  48386. this._collisionMask = !isNaN(mask) ? mask : -1;
  48387. },
  48388. enumerable: true,
  48389. configurable: true
  48390. });
  48391. /** @hidden */
  48392. FreeCamera.prototype._collideWithWorld = function (displacement) {
  48393. var globalPosition;
  48394. if (this.parent) {
  48395. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  48396. }
  48397. else {
  48398. globalPosition = this.position;
  48399. }
  48400. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  48401. this._oldPosition.addInPlace(this.ellipsoidOffset);
  48402. if (!this._collider) {
  48403. this._collider = new BABYLON.Collider();
  48404. }
  48405. this._collider._radius = this.ellipsoid;
  48406. this._collider.collisionMask = this._collisionMask;
  48407. //no need for clone, as long as gravity is not on.
  48408. var actualDisplacement = displacement;
  48409. //add gravity to the direction to prevent the dual-collision checking
  48410. if (this.applyGravity) {
  48411. //this prevents mending with cameraDirection, a global variable of the free camera class.
  48412. actualDisplacement = displacement.add(this.getScene().gravity);
  48413. }
  48414. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48415. };
  48416. /** @hidden */
  48417. FreeCamera.prototype._checkInputs = function () {
  48418. if (!this._localDirection) {
  48419. this._localDirection = BABYLON.Vector3.Zero();
  48420. this._transformedDirection = BABYLON.Vector3.Zero();
  48421. }
  48422. this.inputs.checkInputs();
  48423. _super.prototype._checkInputs.call(this);
  48424. };
  48425. /** @hidden */
  48426. FreeCamera.prototype._decideIfNeedsToMove = function () {
  48427. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48428. };
  48429. /** @hidden */
  48430. FreeCamera.prototype._updatePosition = function () {
  48431. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  48432. this._collideWithWorld(this.cameraDirection);
  48433. }
  48434. else {
  48435. _super.prototype._updatePosition.call(this);
  48436. }
  48437. };
  48438. /**
  48439. * Destroy the camera and release the current resources hold by it.
  48440. */
  48441. FreeCamera.prototype.dispose = function () {
  48442. this.inputs.clear();
  48443. _super.prototype.dispose.call(this);
  48444. };
  48445. /**
  48446. * Gets the current object class name.
  48447. * @return the class name
  48448. */
  48449. FreeCamera.prototype.getClassName = function () {
  48450. return "FreeCamera";
  48451. };
  48452. __decorate([
  48453. BABYLON.serializeAsVector3()
  48454. ], FreeCamera.prototype, "ellipsoid", void 0);
  48455. __decorate([
  48456. BABYLON.serializeAsVector3()
  48457. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  48458. __decorate([
  48459. BABYLON.serialize()
  48460. ], FreeCamera.prototype, "checkCollisions", void 0);
  48461. __decorate([
  48462. BABYLON.serialize()
  48463. ], FreeCamera.prototype, "applyGravity", void 0);
  48464. return FreeCamera;
  48465. }(BABYLON.TargetCamera));
  48466. BABYLON.FreeCamera = FreeCamera;
  48467. })(BABYLON || (BABYLON = {}));
  48468. //# sourceMappingURL=babylon.freeCamera.js.map
  48469. var BABYLON;
  48470. (function (BABYLON) {
  48471. /**
  48472. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  48473. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48474. */
  48475. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48476. function ArcRotateCameraKeyboardMoveInput() {
  48477. /**
  48478. * Defines the list of key codes associated with the up action (increase alpha)
  48479. */
  48480. this.keysUp = [38];
  48481. /**
  48482. * Defines the list of key codes associated with the down action (decrease alpha)
  48483. */
  48484. this.keysDown = [40];
  48485. /**
  48486. * Defines the list of key codes associated with the left action (increase beta)
  48487. */
  48488. this.keysLeft = [37];
  48489. /**
  48490. * Defines the list of key codes associated with the right action (decrease beta)
  48491. */
  48492. this.keysRight = [39];
  48493. /**
  48494. * Defines the list of key codes associated with the reset action.
  48495. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  48496. */
  48497. this.keysReset = [220];
  48498. /**
  48499. * Defines the panning sensibility of the inputs.
  48500. * (How fast is the camera paning)
  48501. */
  48502. this.panningSensibility = 50.0;
  48503. /**
  48504. * Defines the zooming sensibility of the inputs.
  48505. * (How fast is the camera zooming)
  48506. */
  48507. this.zoomingSensibility = 25.0;
  48508. /**
  48509. * Defines wether maintaining the alt key down switch the movement mode from
  48510. * orientation to zoom.
  48511. */
  48512. this.useAltToZoom = true;
  48513. /**
  48514. * Rotation speed of the camera
  48515. */
  48516. this.angularSpeed = 0.01;
  48517. this._keys = new Array();
  48518. }
  48519. /**
  48520. * Attach the input controls to a specific dom element to get the input from.
  48521. * @param element Defines the element the controls should be listened from
  48522. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48523. */
  48524. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48525. var _this = this;
  48526. if (this._onCanvasBlurObserver) {
  48527. return;
  48528. }
  48529. this._scene = this.camera.getScene();
  48530. this._engine = this._scene.getEngine();
  48531. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48532. _this._keys = [];
  48533. });
  48534. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48535. var evt = info.event;
  48536. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48537. _this._ctrlPressed = evt.ctrlKey;
  48538. _this._altPressed = evt.altKey;
  48539. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48540. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48541. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48542. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48543. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48544. var index = _this._keys.indexOf(evt.keyCode);
  48545. if (index === -1) {
  48546. _this._keys.push(evt.keyCode);
  48547. }
  48548. if (evt.preventDefault) {
  48549. if (!noPreventDefault) {
  48550. evt.preventDefault();
  48551. }
  48552. }
  48553. }
  48554. }
  48555. else {
  48556. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48557. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48558. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48559. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48560. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48561. var index = _this._keys.indexOf(evt.keyCode);
  48562. if (index >= 0) {
  48563. _this._keys.splice(index, 1);
  48564. }
  48565. if (evt.preventDefault) {
  48566. if (!noPreventDefault) {
  48567. evt.preventDefault();
  48568. }
  48569. }
  48570. }
  48571. }
  48572. });
  48573. };
  48574. /**
  48575. * Detach the current controls from the specified dom element.
  48576. * @param element Defines the element to stop listening the inputs from
  48577. */
  48578. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48579. if (this._scene) {
  48580. if (this._onKeyboardObserver) {
  48581. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48582. }
  48583. if (this._onCanvasBlurObserver) {
  48584. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48585. }
  48586. this._onKeyboardObserver = null;
  48587. this._onCanvasBlurObserver = null;
  48588. }
  48589. this._keys = [];
  48590. };
  48591. /**
  48592. * Update the current camera state depending on the inputs that have been used this frame.
  48593. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  48594. */
  48595. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48596. if (this._onKeyboardObserver) {
  48597. var camera = this.camera;
  48598. for (var index = 0; index < this._keys.length; index++) {
  48599. var keyCode = this._keys[index];
  48600. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48601. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48602. camera.inertialPanningX -= 1 / this.panningSensibility;
  48603. }
  48604. else {
  48605. camera.inertialAlphaOffset -= this.angularSpeed;
  48606. }
  48607. }
  48608. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48609. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48610. camera.inertialPanningY += 1 / this.panningSensibility;
  48611. }
  48612. else if (this._altPressed && this.useAltToZoom) {
  48613. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48614. }
  48615. else {
  48616. camera.inertialBetaOffset -= this.angularSpeed;
  48617. }
  48618. }
  48619. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48620. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48621. camera.inertialPanningX += 1 / this.panningSensibility;
  48622. }
  48623. else {
  48624. camera.inertialAlphaOffset += this.angularSpeed;
  48625. }
  48626. }
  48627. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48628. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48629. camera.inertialPanningY -= 1 / this.panningSensibility;
  48630. }
  48631. else if (this._altPressed && this.useAltToZoom) {
  48632. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48633. }
  48634. else {
  48635. camera.inertialBetaOffset += this.angularSpeed;
  48636. }
  48637. }
  48638. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48639. if (camera.useInputToRestoreState) {
  48640. camera.restoreState();
  48641. }
  48642. }
  48643. }
  48644. }
  48645. };
  48646. /**
  48647. * Gets the class name of the current intput.
  48648. * @returns the class name
  48649. */
  48650. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48651. return "ArcRotateCameraKeyboardMoveInput";
  48652. };
  48653. /**
  48654. * Get the friendly name associated with the input class.
  48655. * @returns the input friendly name
  48656. */
  48657. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48658. return "keyboard";
  48659. };
  48660. __decorate([
  48661. BABYLON.serialize()
  48662. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48663. __decorate([
  48664. BABYLON.serialize()
  48665. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48666. __decorate([
  48667. BABYLON.serialize()
  48668. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48669. __decorate([
  48670. BABYLON.serialize()
  48671. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48672. __decorate([
  48673. BABYLON.serialize()
  48674. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48675. __decorate([
  48676. BABYLON.serialize()
  48677. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48678. __decorate([
  48679. BABYLON.serialize()
  48680. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48681. __decorate([
  48682. BABYLON.serialize()
  48683. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48684. __decorate([
  48685. BABYLON.serialize()
  48686. ], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0);
  48687. return ArcRotateCameraKeyboardMoveInput;
  48688. }());
  48689. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48690. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48691. })(BABYLON || (BABYLON = {}));
  48692. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48693. var BABYLON;
  48694. (function (BABYLON) {
  48695. /**
  48696. * Manage the mouse wheel inputs to control an arc rotate camera.
  48697. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48698. */
  48699. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48700. function ArcRotateCameraMouseWheelInput() {
  48701. /**
  48702. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  48703. */
  48704. this.wheelPrecision = 3.0;
  48705. /**
  48706. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48707. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48708. */
  48709. this.wheelDeltaPercentage = 0;
  48710. }
  48711. /**
  48712. * Attach the input controls to a specific dom element to get the input from.
  48713. * @param element Defines the element the controls should be listened from
  48714. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48715. */
  48716. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48717. var _this = this;
  48718. this._wheel = function (p, s) {
  48719. //sanity check - this should be a PointerWheel event.
  48720. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48721. return;
  48722. var event = p.event;
  48723. var delta = 0;
  48724. if (event.wheelDelta) {
  48725. if (_this.wheelDeltaPercentage) {
  48726. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48727. if (event.wheelDelta > 0) {
  48728. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48729. }
  48730. else {
  48731. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48732. }
  48733. }
  48734. else {
  48735. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48736. }
  48737. }
  48738. else if (event.detail) {
  48739. delta = -event.detail / _this.wheelPrecision;
  48740. }
  48741. if (delta)
  48742. _this.camera.inertialRadiusOffset += delta;
  48743. if (event.preventDefault) {
  48744. if (!noPreventDefault) {
  48745. event.preventDefault();
  48746. }
  48747. }
  48748. };
  48749. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48750. };
  48751. /**
  48752. * Detach the current controls from the specified dom element.
  48753. * @param element Defines the element to stop listening the inputs from
  48754. */
  48755. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48756. if (this._observer && element) {
  48757. this.camera.getScene().onPointerObservable.remove(this._observer);
  48758. this._observer = null;
  48759. this._wheel = null;
  48760. }
  48761. };
  48762. /**
  48763. * Gets the class name of the current intput.
  48764. * @returns the class name
  48765. */
  48766. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48767. return "ArcRotateCameraMouseWheelInput";
  48768. };
  48769. /**
  48770. * Get the friendly name associated with the input class.
  48771. * @returns the input friendly name
  48772. */
  48773. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48774. return "mousewheel";
  48775. };
  48776. __decorate([
  48777. BABYLON.serialize()
  48778. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48779. __decorate([
  48780. BABYLON.serialize()
  48781. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48782. return ArcRotateCameraMouseWheelInput;
  48783. }());
  48784. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48785. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48786. })(BABYLON || (BABYLON = {}));
  48787. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48788. var BABYLON;
  48789. (function (BABYLON) {
  48790. /**
  48791. * Manage the pointers inputs to control an arc rotate camera.
  48792. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48793. */
  48794. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48795. function ArcRotateCameraPointersInput() {
  48796. /**
  48797. * Defines the buttons associated with the input to handle camera move.
  48798. */
  48799. this.buttons = [0, 1, 2];
  48800. /**
  48801. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  48802. */
  48803. this.angularSensibilityX = 1000.0;
  48804. /**
  48805. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  48806. */
  48807. this.angularSensibilityY = 1000.0;
  48808. /**
  48809. * Defines the pointer pinch precision or how fast is the camera zooming.
  48810. */
  48811. this.pinchPrecision = 12.0;
  48812. /**
  48813. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48814. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48815. */
  48816. this.pinchDeltaPercentage = 0;
  48817. /**
  48818. * Defines the pointer panning sensibility or how fast is the camera moving.
  48819. */
  48820. this.panningSensibility = 1000.0;
  48821. /**
  48822. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  48823. */
  48824. this.multiTouchPanning = true;
  48825. /**
  48826. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  48827. */
  48828. this.multiTouchPanAndZoom = true;
  48829. /**
  48830. * Revers pinch action direction.
  48831. */
  48832. this.pinchInwards = true;
  48833. this._isPanClick = false;
  48834. }
  48835. /**
  48836. * Attach the input controls to a specific dom element to get the input from.
  48837. * @param element Defines the element the controls should be listened from
  48838. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48839. */
  48840. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48841. var _this = this;
  48842. var engine = this.camera.getEngine();
  48843. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48844. var pointA = null;
  48845. var pointB = null;
  48846. var previousPinchSquaredDistance = 0;
  48847. var initialDistance = 0;
  48848. var twoFingerActivityCount = 0;
  48849. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48850. this._pointerInput = function (p, s) {
  48851. var evt = p.event;
  48852. var isTouch = p.event.pointerType === "touch";
  48853. if (engine.isInVRExclusivePointerMode) {
  48854. return;
  48855. }
  48856. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48857. return;
  48858. }
  48859. var srcElement = (evt.srcElement || evt.target);
  48860. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48861. try {
  48862. srcElement.setPointerCapture(evt.pointerId);
  48863. }
  48864. catch (e) {
  48865. //Nothing to do with the error. Execution will continue.
  48866. }
  48867. // Manage panning with pan button click
  48868. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48869. // manage pointers
  48870. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48871. if (pointA === null) {
  48872. pointA = cacheSoloPointer;
  48873. }
  48874. else if (pointB === null) {
  48875. pointB = cacheSoloPointer;
  48876. }
  48877. if (!noPreventDefault) {
  48878. evt.preventDefault();
  48879. element.focus();
  48880. }
  48881. }
  48882. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48883. if (_this.camera.useInputToRestoreState) {
  48884. _this.camera.restoreState();
  48885. }
  48886. }
  48887. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48888. try {
  48889. srcElement.releasePointerCapture(evt.pointerId);
  48890. }
  48891. catch (e) {
  48892. //Nothing to do with the error.
  48893. }
  48894. cacheSoloPointer = null;
  48895. previousPinchSquaredDistance = 0;
  48896. previousMultiTouchPanPosition.isPaning = false;
  48897. previousMultiTouchPanPosition.isPinching = false;
  48898. twoFingerActivityCount = 0;
  48899. initialDistance = 0;
  48900. if (!isTouch) {
  48901. pointB = null; // Mouse and pen are mono pointer
  48902. }
  48903. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48904. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48905. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48906. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48907. if (engine._badOS) {
  48908. pointA = pointB = null;
  48909. }
  48910. else {
  48911. //only remove the impacted pointer in case of multitouch allowing on most
  48912. //platforms switching from rotate to zoom and pan seamlessly.
  48913. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48914. pointA = pointB;
  48915. pointB = null;
  48916. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48917. }
  48918. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48919. pointB = null;
  48920. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48921. }
  48922. else {
  48923. pointA = pointB = null;
  48924. }
  48925. }
  48926. if (!noPreventDefault) {
  48927. evt.preventDefault();
  48928. }
  48929. }
  48930. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48931. if (!noPreventDefault) {
  48932. evt.preventDefault();
  48933. }
  48934. // One button down
  48935. if (pointA && pointB === null && cacheSoloPointer) {
  48936. if (_this.panningSensibility !== 0 &&
  48937. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48938. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48939. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48940. }
  48941. else {
  48942. var offsetX = evt.clientX - cacheSoloPointer.x;
  48943. var offsetY = evt.clientY - cacheSoloPointer.y;
  48944. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48945. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48946. }
  48947. cacheSoloPointer.x = evt.clientX;
  48948. cacheSoloPointer.y = evt.clientY;
  48949. }
  48950. // Two buttons down: pinch/pan
  48951. else if (pointA && pointB) {
  48952. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48953. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48954. ed.x = evt.clientX;
  48955. ed.y = evt.clientY;
  48956. var direction = _this.pinchInwards ? 1 : -1;
  48957. var distX = pointA.x - pointB.x;
  48958. var distY = pointA.y - pointB.y;
  48959. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48960. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48961. if (previousPinchSquaredDistance === 0) {
  48962. initialDistance = pinchDistance;
  48963. previousPinchSquaredDistance = pinchSquaredDistance;
  48964. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48965. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48966. return;
  48967. }
  48968. if (_this.multiTouchPanAndZoom) {
  48969. if (_this.pinchDeltaPercentage) {
  48970. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48971. }
  48972. else {
  48973. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48974. (_this.pinchPrecision *
  48975. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48976. direction);
  48977. }
  48978. if (_this.panningSensibility !== 0) {
  48979. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48980. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48981. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48982. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48983. previousMultiTouchPanPosition.x = pointersCenterX;
  48984. previousMultiTouchPanPosition.y = pointersCenterY;
  48985. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48986. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48987. }
  48988. }
  48989. else {
  48990. twoFingerActivityCount++;
  48991. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48992. if (_this.pinchDeltaPercentage) {
  48993. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48994. }
  48995. else {
  48996. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48997. (_this.pinchPrecision *
  48998. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48999. direction);
  49000. }
  49001. previousMultiTouchPanPosition.isPaning = false;
  49002. previousMultiTouchPanPosition.isPinching = true;
  49003. }
  49004. else {
  49005. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  49006. if (!previousMultiTouchPanPosition.isPaning) {
  49007. previousMultiTouchPanPosition.isPaning = true;
  49008. previousMultiTouchPanPosition.isPinching = false;
  49009. previousMultiTouchPanPosition.x = ed.x;
  49010. previousMultiTouchPanPosition.y = ed.y;
  49011. return;
  49012. }
  49013. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  49014. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  49015. }
  49016. }
  49017. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  49018. previousMultiTouchPanPosition.x = ed.x;
  49019. previousMultiTouchPanPosition.y = ed.y;
  49020. }
  49021. }
  49022. previousPinchSquaredDistance = pinchSquaredDistance;
  49023. }
  49024. }
  49025. };
  49026. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  49027. this._onContextMenu = function (evt) {
  49028. evt.preventDefault();
  49029. };
  49030. if (!this.camera._useCtrlForPanning) {
  49031. element.addEventListener("contextmenu", this._onContextMenu, false);
  49032. }
  49033. this._onLostFocus = function () {
  49034. //this._keys = [];
  49035. pointA = pointB = null;
  49036. previousPinchSquaredDistance = 0;
  49037. previousMultiTouchPanPosition.isPaning = false;
  49038. previousMultiTouchPanPosition.isPinching = false;
  49039. twoFingerActivityCount = 0;
  49040. cacheSoloPointer = null;
  49041. initialDistance = 0;
  49042. };
  49043. this._onMouseMove = function (evt) {
  49044. if (!engine.isPointerLock) {
  49045. return;
  49046. }
  49047. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  49048. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  49049. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  49050. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  49051. if (!noPreventDefault) {
  49052. evt.preventDefault();
  49053. }
  49054. };
  49055. this._onGestureStart = function (e) {
  49056. if (window.MSGesture === undefined) {
  49057. return;
  49058. }
  49059. if (!_this._MSGestureHandler) {
  49060. _this._MSGestureHandler = new MSGesture();
  49061. _this._MSGestureHandler.target = element;
  49062. }
  49063. _this._MSGestureHandler.addPointer(e.pointerId);
  49064. };
  49065. this._onGesture = function (e) {
  49066. _this.camera.radius *= e.scale;
  49067. if (e.preventDefault) {
  49068. if (!noPreventDefault) {
  49069. e.stopPropagation();
  49070. e.preventDefault();
  49071. }
  49072. }
  49073. };
  49074. element.addEventListener("mousemove", this._onMouseMove, false);
  49075. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  49076. element.addEventListener("MSGestureChange", this._onGesture, false);
  49077. BABYLON.Tools.RegisterTopRootEvents([
  49078. { name: "blur", handler: this._onLostFocus }
  49079. ]);
  49080. };
  49081. /**
  49082. * Detach the current controls from the specified dom element.
  49083. * @param element Defines the element to stop listening the inputs from
  49084. */
  49085. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  49086. if (this._onLostFocus) {
  49087. BABYLON.Tools.UnregisterTopRootEvents([
  49088. { name: "blur", handler: this._onLostFocus }
  49089. ]);
  49090. }
  49091. if (element && this._observer) {
  49092. this.camera.getScene().onPointerObservable.remove(this._observer);
  49093. this._observer = null;
  49094. if (this._onContextMenu) {
  49095. element.removeEventListener("contextmenu", this._onContextMenu);
  49096. }
  49097. if (this._onMouseMove) {
  49098. element.removeEventListener("mousemove", this._onMouseMove);
  49099. }
  49100. if (this._onGestureStart) {
  49101. element.removeEventListener("MSPointerDown", this._onGestureStart);
  49102. }
  49103. if (this._onGesture) {
  49104. element.removeEventListener("MSGestureChange", this._onGesture);
  49105. }
  49106. this._isPanClick = false;
  49107. this.pinchInwards = true;
  49108. this._onMouseMove = null;
  49109. this._onGestureStart = null;
  49110. this._onGesture = null;
  49111. this._MSGestureHandler = null;
  49112. this._onLostFocus = null;
  49113. this._onContextMenu = null;
  49114. }
  49115. };
  49116. /**
  49117. * Gets the class name of the current intput.
  49118. * @returns the class name
  49119. */
  49120. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  49121. return "ArcRotateCameraPointersInput";
  49122. };
  49123. /**
  49124. * Get the friendly name associated with the input class.
  49125. * @returns the input friendly name
  49126. */
  49127. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  49128. return "pointers";
  49129. };
  49130. __decorate([
  49131. BABYLON.serialize()
  49132. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  49133. __decorate([
  49134. BABYLON.serialize()
  49135. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  49136. __decorate([
  49137. BABYLON.serialize()
  49138. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  49139. __decorate([
  49140. BABYLON.serialize()
  49141. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  49142. __decorate([
  49143. BABYLON.serialize()
  49144. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  49145. __decorate([
  49146. BABYLON.serialize()
  49147. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  49148. __decorate([
  49149. BABYLON.serialize()
  49150. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  49151. __decorate([
  49152. BABYLON.serialize()
  49153. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  49154. return ArcRotateCameraPointersInput;
  49155. }());
  49156. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  49157. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  49158. })(BABYLON || (BABYLON = {}));
  49159. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  49160. var BABYLON;
  49161. (function (BABYLON) {
  49162. /**
  49163. * Default Inputs manager for the ArcRotateCamera.
  49164. * It groups all the default supported inputs for ease of use.
  49165. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49166. */
  49167. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  49168. __extends(ArcRotateCameraInputsManager, _super);
  49169. /**
  49170. * Instantiates a new ArcRotateCameraInputsManager.
  49171. * @param camera Defines the camera the inputs belong to
  49172. */
  49173. function ArcRotateCameraInputsManager(camera) {
  49174. return _super.call(this, camera) || this;
  49175. }
  49176. /**
  49177. * Add mouse wheel input support to the input manager.
  49178. * @returns the current input manager
  49179. */
  49180. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  49181. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  49182. return this;
  49183. };
  49184. /**
  49185. * Add pointers input support to the input manager.
  49186. * @returns the current input manager
  49187. */
  49188. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  49189. this.add(new BABYLON.ArcRotateCameraPointersInput());
  49190. return this;
  49191. };
  49192. /**
  49193. * Add keyboard input support to the input manager.
  49194. * @returns the current input manager
  49195. */
  49196. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  49197. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  49198. return this;
  49199. };
  49200. /**
  49201. * Add orientation input support to the input manager.
  49202. * @returns the current input manager
  49203. */
  49204. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  49205. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  49206. return this;
  49207. };
  49208. return ArcRotateCameraInputsManager;
  49209. }(BABYLON.CameraInputsManager));
  49210. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  49211. })(BABYLON || (BABYLON = {}));
  49212. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  49213. var BABYLON;
  49214. (function (BABYLON) {
  49215. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  49216. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  49217. });
  49218. /**
  49219. * This represents an orbital type of camera.
  49220. *
  49221. * 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.
  49222. * 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.
  49223. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  49224. */
  49225. var ArcRotateCamera = /** @class */ (function (_super) {
  49226. __extends(ArcRotateCamera, _super);
  49227. /**
  49228. * Instantiates a new ArcRotateCamera in a given scene
  49229. * @param name Defines the name of the camera
  49230. * @param alpha Defines the camera rotation along the logitudinal axis
  49231. * @param beta Defines the camera rotation along the latitudinal axis
  49232. * @param radius Defines the camera distance from its target
  49233. * @param target Defines the camera target
  49234. * @param scene Defines the scene the camera belongs to
  49235. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  49236. */
  49237. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  49238. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49239. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  49240. /**
  49241. * Current inertia value on the longitudinal axis.
  49242. * The bigger this number the longer it will take for the camera to stop.
  49243. */
  49244. _this.inertialAlphaOffset = 0;
  49245. /**
  49246. * Current inertia value on the latitudinal axis.
  49247. * The bigger this number the longer it will take for the camera to stop.
  49248. */
  49249. _this.inertialBetaOffset = 0;
  49250. /**
  49251. * Current inertia value on the radius axis.
  49252. * The bigger this number the longer it will take for the camera to stop.
  49253. */
  49254. _this.inertialRadiusOffset = 0;
  49255. /**
  49256. * Minimum allowed angle on the longitudinal axis.
  49257. * This can help limiting how the Camera is able to move in the scene.
  49258. */
  49259. _this.lowerAlphaLimit = null;
  49260. /**
  49261. * Maximum allowed angle on the longitudinal axis.
  49262. * This can help limiting how the Camera is able to move in the scene.
  49263. */
  49264. _this.upperAlphaLimit = null;
  49265. /**
  49266. * Minimum allowed angle on the latitudinal axis.
  49267. * This can help limiting how the Camera is able to move in the scene.
  49268. */
  49269. _this.lowerBetaLimit = 0.01;
  49270. /**
  49271. * Maximum allowed angle on the latitudinal axis.
  49272. * This can help limiting how the Camera is able to move in the scene.
  49273. */
  49274. _this.upperBetaLimit = Math.PI;
  49275. /**
  49276. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  49277. * This can help limiting how the Camera is able to move in the scene.
  49278. */
  49279. _this.lowerRadiusLimit = null;
  49280. /**
  49281. * Maximum allowed distance of the camera to the target (The camera can not get further).
  49282. * This can help limiting how the Camera is able to move in the scene.
  49283. */
  49284. _this.upperRadiusLimit = null;
  49285. /**
  49286. * Defines the current inertia value used during panning of the camera along the X axis.
  49287. */
  49288. _this.inertialPanningX = 0;
  49289. /**
  49290. * Defines the current inertia value used during panning of the camera along the Y axis.
  49291. */
  49292. _this.inertialPanningY = 0;
  49293. /**
  49294. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  49295. * Basically if your fingers moves away from more than this distance you will be considered
  49296. * in pinch mode.
  49297. */
  49298. _this.pinchToPanMaxDistance = 20;
  49299. /**
  49300. * Defines the maximum distance the camera can pan.
  49301. * This could help keeping the cammera always in your scene.
  49302. */
  49303. _this.panningDistanceLimit = null;
  49304. /**
  49305. * Defines the target of the camera before paning.
  49306. */
  49307. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  49308. /**
  49309. * Defines the value of the inertia used during panning.
  49310. * 0 would mean stop inertia and one would mean no decelleration at all.
  49311. */
  49312. _this.panningInertia = 0.9;
  49313. //-- end properties for backward compatibility for inputs
  49314. /**
  49315. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  49316. */
  49317. _this.zoomOnFactor = 1;
  49318. /**
  49319. * Defines a screen offset for the camera position.
  49320. */
  49321. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  49322. /**
  49323. * Allows the camera to be completely reversed.
  49324. * If false the camera can not arrive upside down.
  49325. */
  49326. _this.allowUpsideDown = true;
  49327. /**
  49328. * Define if double tap/click is used to restore the previously saved state of the camera.
  49329. */
  49330. _this.useInputToRestoreState = true;
  49331. /** @hidden */
  49332. _this._viewMatrix = new BABYLON.Matrix();
  49333. /**
  49334. * Defines the allowed panning axis.
  49335. */
  49336. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  49337. /**
  49338. * Observable triggered when the mesh target has been changed on the camera.
  49339. */
  49340. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  49341. /**
  49342. * Defines whether the camera should check collision with the objects oh the scene.
  49343. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  49344. */
  49345. _this.checkCollisions = false;
  49346. /**
  49347. * Defines the collision radius of the camera.
  49348. * This simulates a sphere around the camera.
  49349. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49350. */
  49351. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  49352. _this._previousPosition = BABYLON.Vector3.Zero();
  49353. _this._collisionVelocity = BABYLON.Vector3.Zero();
  49354. _this._newPosition = BABYLON.Vector3.Zero();
  49355. _this._computationVector = BABYLON.Vector3.Zero();
  49356. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49357. if (collidedMesh === void 0) { collidedMesh = null; }
  49358. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  49359. newPosition.multiplyInPlace(_this._collider._radius);
  49360. }
  49361. if (!collidedMesh) {
  49362. _this._previousPosition.copyFrom(_this.position);
  49363. }
  49364. else {
  49365. _this.setPosition(newPosition);
  49366. if (_this.onCollide) {
  49367. _this.onCollide(collidedMesh);
  49368. }
  49369. }
  49370. // Recompute because of constraints
  49371. var cosa = Math.cos(_this.alpha);
  49372. var sina = Math.sin(_this.alpha);
  49373. var cosb = Math.cos(_this.beta);
  49374. var sinb = Math.sin(_this.beta);
  49375. if (sinb === 0) {
  49376. sinb = 0.0001;
  49377. }
  49378. var target = _this._getTargetPosition();
  49379. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  49380. target.addToRef(_this._computationVector, _this._newPosition);
  49381. _this.position.copyFrom(_this._newPosition);
  49382. var up = _this.upVector;
  49383. if (_this.allowUpsideDown && _this.beta < 0) {
  49384. up = up.clone();
  49385. up = up.negate();
  49386. }
  49387. _this._computeViewMatrix(_this.position, target, up);
  49388. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  49389. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  49390. _this._collisionTriggered = false;
  49391. };
  49392. _this._target = BABYLON.Vector3.Zero();
  49393. if (target) {
  49394. _this.setTarget(target);
  49395. }
  49396. _this.alpha = alpha;
  49397. _this.beta = beta;
  49398. _this.radius = radius;
  49399. _this.getViewMatrix();
  49400. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  49401. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  49402. return _this;
  49403. }
  49404. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  49405. /**
  49406. * Defines the target point of the camera.
  49407. * The camera looks towards it form the radius distance.
  49408. */
  49409. get: function () {
  49410. return this._target;
  49411. },
  49412. set: function (value) {
  49413. this.setTarget(value);
  49414. },
  49415. enumerable: true,
  49416. configurable: true
  49417. });
  49418. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  49419. //-- begin properties for backward compatibility for inputs
  49420. /**
  49421. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  49422. */
  49423. get: function () {
  49424. var pointers = this.inputs.attached["pointers"];
  49425. if (pointers)
  49426. return pointers.angularSensibilityX;
  49427. return 0;
  49428. },
  49429. set: function (value) {
  49430. var pointers = this.inputs.attached["pointers"];
  49431. if (pointers) {
  49432. pointers.angularSensibilityX = value;
  49433. }
  49434. },
  49435. enumerable: true,
  49436. configurable: true
  49437. });
  49438. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  49439. /**
  49440. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  49441. */
  49442. get: function () {
  49443. var pointers = this.inputs.attached["pointers"];
  49444. if (pointers)
  49445. return pointers.angularSensibilityY;
  49446. return 0;
  49447. },
  49448. set: function (value) {
  49449. var pointers = this.inputs.attached["pointers"];
  49450. if (pointers) {
  49451. pointers.angularSensibilityY = value;
  49452. }
  49453. },
  49454. enumerable: true,
  49455. configurable: true
  49456. });
  49457. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  49458. /**
  49459. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  49460. */
  49461. get: function () {
  49462. var pointers = this.inputs.attached["pointers"];
  49463. if (pointers)
  49464. return pointers.pinchPrecision;
  49465. return 0;
  49466. },
  49467. set: function (value) {
  49468. var pointers = this.inputs.attached["pointers"];
  49469. if (pointers) {
  49470. pointers.pinchPrecision = value;
  49471. }
  49472. },
  49473. enumerable: true,
  49474. configurable: true
  49475. });
  49476. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  49477. /**
  49478. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  49479. * It will be used instead of pinchDeltaPrecision if different from 0.
  49480. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  49481. */
  49482. get: function () {
  49483. var pointers = this.inputs.attached["pointers"];
  49484. if (pointers)
  49485. return pointers.pinchDeltaPercentage;
  49486. return 0;
  49487. },
  49488. set: function (value) {
  49489. var pointers = this.inputs.attached["pointers"];
  49490. if (pointers) {
  49491. pointers.pinchDeltaPercentage = value;
  49492. }
  49493. },
  49494. enumerable: true,
  49495. configurable: true
  49496. });
  49497. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  49498. /**
  49499. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  49500. */
  49501. get: function () {
  49502. var pointers = this.inputs.attached["pointers"];
  49503. if (pointers)
  49504. return pointers.panningSensibility;
  49505. return 0;
  49506. },
  49507. set: function (value) {
  49508. var pointers = this.inputs.attached["pointers"];
  49509. if (pointers) {
  49510. pointers.panningSensibility = value;
  49511. }
  49512. },
  49513. enumerable: true,
  49514. configurable: true
  49515. });
  49516. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  49517. /**
  49518. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  49519. */
  49520. get: function () {
  49521. var keyboard = this.inputs.attached["keyboard"];
  49522. if (keyboard)
  49523. return keyboard.keysUp;
  49524. return [];
  49525. },
  49526. set: function (value) {
  49527. var keyboard = this.inputs.attached["keyboard"];
  49528. if (keyboard)
  49529. keyboard.keysUp = value;
  49530. },
  49531. enumerable: true,
  49532. configurable: true
  49533. });
  49534. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  49535. /**
  49536. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  49537. */
  49538. get: function () {
  49539. var keyboard = this.inputs.attached["keyboard"];
  49540. if (keyboard)
  49541. return keyboard.keysDown;
  49542. return [];
  49543. },
  49544. set: function (value) {
  49545. var keyboard = this.inputs.attached["keyboard"];
  49546. if (keyboard)
  49547. keyboard.keysDown = value;
  49548. },
  49549. enumerable: true,
  49550. configurable: true
  49551. });
  49552. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  49553. /**
  49554. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  49555. */
  49556. get: function () {
  49557. var keyboard = this.inputs.attached["keyboard"];
  49558. if (keyboard)
  49559. return keyboard.keysLeft;
  49560. return [];
  49561. },
  49562. set: function (value) {
  49563. var keyboard = this.inputs.attached["keyboard"];
  49564. if (keyboard)
  49565. keyboard.keysLeft = value;
  49566. },
  49567. enumerable: true,
  49568. configurable: true
  49569. });
  49570. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  49571. /**
  49572. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  49573. */
  49574. get: function () {
  49575. var keyboard = this.inputs.attached["keyboard"];
  49576. if (keyboard)
  49577. return keyboard.keysRight;
  49578. return [];
  49579. },
  49580. set: function (value) {
  49581. var keyboard = this.inputs.attached["keyboard"];
  49582. if (keyboard)
  49583. keyboard.keysRight = value;
  49584. },
  49585. enumerable: true,
  49586. configurable: true
  49587. });
  49588. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  49589. /**
  49590. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  49591. */
  49592. get: function () {
  49593. var mousewheel = this.inputs.attached["mousewheel"];
  49594. if (mousewheel)
  49595. return mousewheel.wheelPrecision;
  49596. return 0;
  49597. },
  49598. set: function (value) {
  49599. var mousewheel = this.inputs.attached["mousewheel"];
  49600. if (mousewheel)
  49601. mousewheel.wheelPrecision = value;
  49602. },
  49603. enumerable: true,
  49604. configurable: true
  49605. });
  49606. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  49607. /**
  49608. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  49609. * It will be used instead of pinchDeltaPrecision if different from 0.
  49610. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  49611. */
  49612. get: function () {
  49613. var mousewheel = this.inputs.attached["mousewheel"];
  49614. if (mousewheel)
  49615. return mousewheel.wheelDeltaPercentage;
  49616. return 0;
  49617. },
  49618. set: function (value) {
  49619. var mousewheel = this.inputs.attached["mousewheel"];
  49620. if (mousewheel)
  49621. mousewheel.wheelDeltaPercentage = value;
  49622. },
  49623. enumerable: true,
  49624. configurable: true
  49625. });
  49626. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  49627. /**
  49628. * Gets the bouncing behavior of the camera if it has been enabled.
  49629. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  49630. */
  49631. get: function () {
  49632. return this._bouncingBehavior;
  49633. },
  49634. enumerable: true,
  49635. configurable: true
  49636. });
  49637. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  49638. /**
  49639. * Defines if the bouncing behavior of the camera is enabled on the camera.
  49640. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  49641. */
  49642. get: function () {
  49643. return this._bouncingBehavior != null;
  49644. },
  49645. set: function (value) {
  49646. if (value === this.useBouncingBehavior) {
  49647. return;
  49648. }
  49649. if (value) {
  49650. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  49651. this.addBehavior(this._bouncingBehavior);
  49652. }
  49653. else if (this._bouncingBehavior) {
  49654. this.removeBehavior(this._bouncingBehavior);
  49655. this._bouncingBehavior = null;
  49656. }
  49657. },
  49658. enumerable: true,
  49659. configurable: true
  49660. });
  49661. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  49662. /**
  49663. * Gets the framing behavior of the camera if it has been enabled.
  49664. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  49665. */
  49666. get: function () {
  49667. return this._framingBehavior;
  49668. },
  49669. enumerable: true,
  49670. configurable: true
  49671. });
  49672. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  49673. /**
  49674. * Defines if the framing behavior of the camera is enabled on the camera.
  49675. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  49676. */
  49677. get: function () {
  49678. return this._framingBehavior != null;
  49679. },
  49680. set: function (value) {
  49681. if (value === this.useFramingBehavior) {
  49682. return;
  49683. }
  49684. if (value) {
  49685. this._framingBehavior = new BABYLON.FramingBehavior();
  49686. this.addBehavior(this._framingBehavior);
  49687. }
  49688. else if (this._framingBehavior) {
  49689. this.removeBehavior(this._framingBehavior);
  49690. this._framingBehavior = null;
  49691. }
  49692. },
  49693. enumerable: true,
  49694. configurable: true
  49695. });
  49696. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  49697. /**
  49698. * Gets the auto rotation behavior of the camera if it has been enabled.
  49699. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  49700. */
  49701. get: function () {
  49702. return this._autoRotationBehavior;
  49703. },
  49704. enumerable: true,
  49705. configurable: true
  49706. });
  49707. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  49708. /**
  49709. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  49710. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  49711. */
  49712. get: function () {
  49713. return this._autoRotationBehavior != null;
  49714. },
  49715. set: function (value) {
  49716. if (value === this.useAutoRotationBehavior) {
  49717. return;
  49718. }
  49719. if (value) {
  49720. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  49721. this.addBehavior(this._autoRotationBehavior);
  49722. }
  49723. else if (this._autoRotationBehavior) {
  49724. this.removeBehavior(this._autoRotationBehavior);
  49725. this._autoRotationBehavior = null;
  49726. }
  49727. },
  49728. enumerable: true,
  49729. configurable: true
  49730. });
  49731. // Cache
  49732. /** @hidden */
  49733. ArcRotateCamera.prototype._initCache = function () {
  49734. _super.prototype._initCache.call(this);
  49735. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  49736. this._cache.alpha = undefined;
  49737. this._cache.beta = undefined;
  49738. this._cache.radius = undefined;
  49739. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  49740. };
  49741. /** @hidden */
  49742. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  49743. if (!ignoreParentClass) {
  49744. _super.prototype._updateCache.call(this);
  49745. }
  49746. this._cache._target.copyFrom(this._getTargetPosition());
  49747. this._cache.alpha = this.alpha;
  49748. this._cache.beta = this.beta;
  49749. this._cache.radius = this.radius;
  49750. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  49751. };
  49752. ArcRotateCamera.prototype._getTargetPosition = function () {
  49753. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  49754. var pos = this._targetHost.getAbsolutePosition();
  49755. if (this._targetBoundingCenter) {
  49756. pos.addToRef(this._targetBoundingCenter, this._target);
  49757. }
  49758. else {
  49759. this._target.copyFrom(pos);
  49760. }
  49761. }
  49762. var lockedTargetPosition = this._getLockedTargetPosition();
  49763. if (lockedTargetPosition) {
  49764. return lockedTargetPosition;
  49765. }
  49766. return this._target;
  49767. };
  49768. /**
  49769. * Stores the current state of the camera (alpha, beta, radius and target)
  49770. * @returns the camera itself
  49771. */
  49772. ArcRotateCamera.prototype.storeState = function () {
  49773. this._storedAlpha = this.alpha;
  49774. this._storedBeta = this.beta;
  49775. this._storedRadius = this.radius;
  49776. this._storedTarget = this._getTargetPosition().clone();
  49777. return _super.prototype.storeState.call(this);
  49778. };
  49779. /**
  49780. * @hidden
  49781. * Restored camera state. You must call storeState() first
  49782. */
  49783. ArcRotateCamera.prototype._restoreStateValues = function () {
  49784. if (!_super.prototype._restoreStateValues.call(this)) {
  49785. return false;
  49786. }
  49787. this.alpha = this._storedAlpha;
  49788. this.beta = this._storedBeta;
  49789. this.radius = this._storedRadius;
  49790. this.setTarget(this._storedTarget.clone());
  49791. this.inertialAlphaOffset = 0;
  49792. this.inertialBetaOffset = 0;
  49793. this.inertialRadiusOffset = 0;
  49794. this.inertialPanningX = 0;
  49795. this.inertialPanningY = 0;
  49796. return true;
  49797. };
  49798. // Synchronized
  49799. /** @hidden */
  49800. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  49801. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  49802. return false;
  49803. return this._cache._target.equals(this._getTargetPosition())
  49804. && this._cache.alpha === this.alpha
  49805. && this._cache.beta === this.beta
  49806. && this._cache.radius === this.radius
  49807. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  49808. };
  49809. /**
  49810. * Attached controls to the current camera.
  49811. * @param element Defines the element the controls should be listened from
  49812. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49813. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  49814. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  49815. */
  49816. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  49817. var _this = this;
  49818. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  49819. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  49820. this._useCtrlForPanning = useCtrlForPanning;
  49821. this._panningMouseButton = panningMouseButton;
  49822. this.inputs.attachElement(element, noPreventDefault);
  49823. this._reset = function () {
  49824. _this.inertialAlphaOffset = 0;
  49825. _this.inertialBetaOffset = 0;
  49826. _this.inertialRadiusOffset = 0;
  49827. _this.inertialPanningX = 0;
  49828. _this.inertialPanningY = 0;
  49829. };
  49830. };
  49831. /**
  49832. * Detach the current controls from the camera.
  49833. * The camera will stop reacting to inputs.
  49834. * @param element Defines the element to stop listening the inputs from
  49835. */
  49836. ArcRotateCamera.prototype.detachControl = function (element) {
  49837. this.inputs.detachElement(element);
  49838. if (this._reset) {
  49839. this._reset();
  49840. }
  49841. };
  49842. /** @hidden */
  49843. ArcRotateCamera.prototype._checkInputs = function () {
  49844. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  49845. if (this._collisionTriggered) {
  49846. return;
  49847. }
  49848. this.inputs.checkInputs();
  49849. // Inertia
  49850. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  49851. var inertialAlphaOffset = this.inertialAlphaOffset;
  49852. if (this.beta <= 0)
  49853. inertialAlphaOffset *= -1;
  49854. if (this.getScene().useRightHandedSystem)
  49855. inertialAlphaOffset *= -1;
  49856. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  49857. inertialAlphaOffset *= -1;
  49858. this.alpha += inertialAlphaOffset;
  49859. this.beta += this.inertialBetaOffset;
  49860. this.radius -= this.inertialRadiusOffset;
  49861. this.inertialAlphaOffset *= this.inertia;
  49862. this.inertialBetaOffset *= this.inertia;
  49863. this.inertialRadiusOffset *= this.inertia;
  49864. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49865. this.inertialAlphaOffset = 0;
  49866. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49867. this.inertialBetaOffset = 0;
  49868. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49869. this.inertialRadiusOffset = 0;
  49870. }
  49871. // Panning inertia
  49872. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49873. if (!this._localDirection) {
  49874. this._localDirection = BABYLON.Vector3.Zero();
  49875. this._transformedDirection = BABYLON.Vector3.Zero();
  49876. }
  49877. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49878. this._localDirection.multiplyInPlace(this.panningAxis);
  49879. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49880. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49881. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49882. if (!this.panningAxis.y) {
  49883. this._transformedDirection.y = 0;
  49884. }
  49885. if (!this._targetHost) {
  49886. if (this.panningDistanceLimit) {
  49887. this._transformedDirection.addInPlace(this._target);
  49888. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49889. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49890. this._target.copyFrom(this._transformedDirection);
  49891. }
  49892. }
  49893. else {
  49894. this._target.addInPlace(this._transformedDirection);
  49895. }
  49896. }
  49897. this.inertialPanningX *= this.panningInertia;
  49898. this.inertialPanningY *= this.panningInertia;
  49899. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49900. this.inertialPanningX = 0;
  49901. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49902. this.inertialPanningY = 0;
  49903. }
  49904. // Limits
  49905. this._checkLimits();
  49906. _super.prototype._checkInputs.call(this);
  49907. };
  49908. ArcRotateCamera.prototype._checkLimits = function () {
  49909. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49910. if (this.allowUpsideDown && this.beta > Math.PI) {
  49911. this.beta = this.beta - (2 * Math.PI);
  49912. }
  49913. }
  49914. else {
  49915. if (this.beta < this.lowerBetaLimit) {
  49916. this.beta = this.lowerBetaLimit;
  49917. }
  49918. }
  49919. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49920. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49921. this.beta = this.beta + (2 * Math.PI);
  49922. }
  49923. }
  49924. else {
  49925. if (this.beta > this.upperBetaLimit) {
  49926. this.beta = this.upperBetaLimit;
  49927. }
  49928. }
  49929. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  49930. this.alpha = this.lowerAlphaLimit;
  49931. }
  49932. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  49933. this.alpha = this.upperAlphaLimit;
  49934. }
  49935. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  49936. this.radius = this.lowerRadiusLimit;
  49937. }
  49938. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  49939. this.radius = this.upperRadiusLimit;
  49940. }
  49941. };
  49942. /**
  49943. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  49944. */
  49945. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49946. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49947. this.radius = this._computationVector.length();
  49948. if (this.radius === 0) {
  49949. this.radius = 0.0001; // Just to avoid division by zero
  49950. }
  49951. // Alpha
  49952. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49953. if (this._computationVector.z < 0) {
  49954. this.alpha = 2 * Math.PI - this.alpha;
  49955. }
  49956. // Beta
  49957. this.beta = Math.acos(this._computationVector.y / this.radius);
  49958. this._checkLimits();
  49959. };
  49960. /**
  49961. * Use a position to define the current camera related information like aplha, beta and radius
  49962. * @param position Defines the position to set the camera at
  49963. */
  49964. ArcRotateCamera.prototype.setPosition = function (position) {
  49965. if (this.position.equals(position)) {
  49966. return;
  49967. }
  49968. this.position.copyFrom(position);
  49969. this.rebuildAnglesAndRadius();
  49970. };
  49971. /**
  49972. * Defines the target the camera should look at.
  49973. * This will automatically adapt alpha beta and radius to fit within the new target.
  49974. * @param target Defines the new target as a Vector or a mesh
  49975. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  49976. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  49977. */
  49978. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49979. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49980. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49981. if (target.getBoundingInfo) {
  49982. if (toBoundingCenter) {
  49983. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49984. }
  49985. else {
  49986. this._targetBoundingCenter = null;
  49987. }
  49988. this._targetHost = target;
  49989. this._target = this._getTargetPosition();
  49990. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49991. }
  49992. else {
  49993. var newTarget = target;
  49994. var currentTarget = this._getTargetPosition();
  49995. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49996. return;
  49997. }
  49998. this._targetHost = null;
  49999. this._target = newTarget;
  50000. this._targetBoundingCenter = null;
  50001. this.onMeshTargetChangedObservable.notifyObservers(null);
  50002. }
  50003. this.rebuildAnglesAndRadius();
  50004. };
  50005. /** @hidden */
  50006. ArcRotateCamera.prototype._getViewMatrix = function () {
  50007. // Compute
  50008. var cosa = Math.cos(this.alpha);
  50009. var sina = Math.sin(this.alpha);
  50010. var cosb = Math.cos(this.beta);
  50011. var sinb = Math.sin(this.beta);
  50012. if (sinb === 0) {
  50013. sinb = 0.0001;
  50014. }
  50015. var target = this._getTargetPosition();
  50016. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  50017. target.addToRef(this._computationVector, this._newPosition);
  50018. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  50019. if (!this._collider) {
  50020. this._collider = new BABYLON.Collider();
  50021. }
  50022. this._collider._radius = this.collisionRadius;
  50023. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  50024. this._collisionTriggered = true;
  50025. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  50026. }
  50027. else {
  50028. this.position.copyFrom(this._newPosition);
  50029. var up = this.upVector;
  50030. if (this.allowUpsideDown && sinb < 0) {
  50031. up = up.clone();
  50032. up = up.negate();
  50033. }
  50034. this._computeViewMatrix(this.position, target, up);
  50035. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  50036. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  50037. }
  50038. this._currentTarget = target;
  50039. return this._viewMatrix;
  50040. };
  50041. /**
  50042. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  50043. * @param meshes Defines the mesh to zoom on
  50044. * @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)
  50045. */
  50046. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  50047. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  50048. meshes = meshes || this.getScene().meshes;
  50049. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  50050. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  50051. this.radius = distance * this.zoomOnFactor;
  50052. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  50053. };
  50054. /**
  50055. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  50056. * The target will be changed but the radius
  50057. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  50058. * @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)
  50059. */
  50060. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  50061. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  50062. var meshesOrMinMaxVector;
  50063. var distance;
  50064. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  50065. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  50066. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  50067. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  50068. }
  50069. else { //minMaxVector and distance
  50070. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  50071. meshesOrMinMaxVector = minMaxVectorAndDistance;
  50072. distance = minMaxVectorAndDistance.distance;
  50073. }
  50074. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  50075. if (!doNotUpdateMaxZ) {
  50076. this.maxZ = distance * 2;
  50077. }
  50078. };
  50079. /**
  50080. * @override
  50081. * Override Camera.createRigCamera
  50082. */
  50083. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  50084. var alphaShift = 0;
  50085. switch (this.cameraRigMode) {
  50086. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  50087. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  50088. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  50089. case BABYLON.Camera.RIG_MODE_VR:
  50090. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  50091. break;
  50092. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  50093. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  50094. break;
  50095. }
  50096. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  50097. rigCam._cameraRigParams = {};
  50098. return rigCam;
  50099. };
  50100. /**
  50101. * @hidden
  50102. * @override
  50103. * Override Camera._updateRigCameras
  50104. */
  50105. ArcRotateCamera.prototype._updateRigCameras = function () {
  50106. var camLeft = this._rigCameras[0];
  50107. var camRight = this._rigCameras[1];
  50108. camLeft.beta = camRight.beta = this.beta;
  50109. camLeft.radius = camRight.radius = this.radius;
  50110. switch (this.cameraRigMode) {
  50111. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  50112. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  50113. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  50114. case BABYLON.Camera.RIG_MODE_VR:
  50115. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  50116. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  50117. break;
  50118. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  50119. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  50120. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  50121. break;
  50122. }
  50123. _super.prototype._updateRigCameras.call(this);
  50124. };
  50125. /**
  50126. * Destroy the camera and release the current resources hold by it.
  50127. */
  50128. ArcRotateCamera.prototype.dispose = function () {
  50129. this.inputs.clear();
  50130. _super.prototype.dispose.call(this);
  50131. };
  50132. /**
  50133. * Gets the current object class name.
  50134. * @return the class name
  50135. */
  50136. ArcRotateCamera.prototype.getClassName = function () {
  50137. return "ArcRotateCamera";
  50138. };
  50139. __decorate([
  50140. BABYLON.serialize()
  50141. ], ArcRotateCamera.prototype, "alpha", void 0);
  50142. __decorate([
  50143. BABYLON.serialize()
  50144. ], ArcRotateCamera.prototype, "beta", void 0);
  50145. __decorate([
  50146. BABYLON.serialize()
  50147. ], ArcRotateCamera.prototype, "radius", void 0);
  50148. __decorate([
  50149. BABYLON.serializeAsVector3("target")
  50150. ], ArcRotateCamera.prototype, "_target", void 0);
  50151. __decorate([
  50152. BABYLON.serialize()
  50153. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  50154. __decorate([
  50155. BABYLON.serialize()
  50156. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  50157. __decorate([
  50158. BABYLON.serialize()
  50159. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  50160. __decorate([
  50161. BABYLON.serialize()
  50162. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  50163. __decorate([
  50164. BABYLON.serialize()
  50165. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  50166. __decorate([
  50167. BABYLON.serialize()
  50168. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  50169. __decorate([
  50170. BABYLON.serialize()
  50171. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  50172. __decorate([
  50173. BABYLON.serialize()
  50174. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  50175. __decorate([
  50176. BABYLON.serialize()
  50177. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  50178. __decorate([
  50179. BABYLON.serialize()
  50180. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  50181. __decorate([
  50182. BABYLON.serialize()
  50183. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  50184. __decorate([
  50185. BABYLON.serialize()
  50186. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  50187. __decorate([
  50188. BABYLON.serialize()
  50189. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  50190. __decorate([
  50191. BABYLON.serializeAsVector3()
  50192. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  50193. __decorate([
  50194. BABYLON.serialize()
  50195. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  50196. __decorate([
  50197. BABYLON.serialize()
  50198. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  50199. __decorate([
  50200. BABYLON.serialize()
  50201. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  50202. __decorate([
  50203. BABYLON.serialize()
  50204. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  50205. __decorate([
  50206. BABYLON.serialize()
  50207. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  50208. return ArcRotateCamera;
  50209. }(BABYLON.TargetCamera));
  50210. BABYLON.ArcRotateCamera = ArcRotateCamera;
  50211. })(BABYLON || (BABYLON = {}));
  50212. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  50213. var BABYLON;
  50214. (function (BABYLON) {
  50215. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  50216. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  50217. });
  50218. /**
  50219. * The HemisphericLight simulates the ambient environment light,
  50220. * so the passed direction is the light reflection direction, not the incoming direction.
  50221. */
  50222. var HemisphericLight = /** @class */ (function (_super) {
  50223. __extends(HemisphericLight, _super);
  50224. /**
  50225. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  50226. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  50227. * The HemisphericLight can't cast shadows.
  50228. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50229. * @param name The friendly name of the light
  50230. * @param direction The direction of the light reflection
  50231. * @param scene The scene the light belongs to
  50232. */
  50233. function HemisphericLight(name, direction, scene) {
  50234. var _this = _super.call(this, name, scene) || this;
  50235. /**
  50236. * The groundColor is the light in the opposite direction to the one specified during creation.
  50237. * 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.
  50238. */
  50239. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  50240. _this.direction = direction || BABYLON.Vector3.Up();
  50241. return _this;
  50242. }
  50243. HemisphericLight.prototype._buildUniformLayout = function () {
  50244. this._uniformBuffer.addUniform("vLightData", 4);
  50245. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50246. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50247. this._uniformBuffer.addUniform("vLightGround", 3);
  50248. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50249. this._uniformBuffer.addUniform("depthValues", 2);
  50250. this._uniformBuffer.create();
  50251. };
  50252. /**
  50253. * Returns the string "HemisphericLight".
  50254. * @return The class name
  50255. */
  50256. HemisphericLight.prototype.getClassName = function () {
  50257. return "HemisphericLight";
  50258. };
  50259. /**
  50260. * Sets the HemisphericLight direction towards the passed target (Vector3).
  50261. * Returns the updated direction.
  50262. * @param target The target the direction should point to
  50263. * @return The computed direction
  50264. */
  50265. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  50266. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  50267. return this.direction;
  50268. };
  50269. /**
  50270. * Returns the shadow generator associated to the light.
  50271. * @returns Always null for hemispheric lights because it does not support shadows.
  50272. */
  50273. HemisphericLight.prototype.getShadowGenerator = function () {
  50274. return null;
  50275. };
  50276. /**
  50277. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  50278. * @param effect The effect to update
  50279. * @param lightIndex The index of the light in the effect to update
  50280. * @returns The hemispheric light
  50281. */
  50282. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  50283. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50284. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  50285. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  50286. return this;
  50287. };
  50288. /**
  50289. * Computes the world matrix of the node
  50290. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  50291. * @param useWasUpdatedFlag defines a reserved property
  50292. * @returns the world matrix
  50293. */
  50294. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  50295. if (!this._worldMatrix) {
  50296. this._worldMatrix = BABYLON.Matrix.Identity();
  50297. }
  50298. return this._worldMatrix;
  50299. };
  50300. /**
  50301. * Returns the integer 3.
  50302. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50303. */
  50304. HemisphericLight.prototype.getTypeID = function () {
  50305. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  50306. };
  50307. /**
  50308. * Prepares the list of defines specific to the light type.
  50309. * @param defines the list of defines
  50310. * @param lightIndex defines the index of the light for the effect
  50311. */
  50312. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50313. defines["HEMILIGHT" + lightIndex] = true;
  50314. };
  50315. __decorate([
  50316. BABYLON.serializeAsColor3()
  50317. ], HemisphericLight.prototype, "groundColor", void 0);
  50318. __decorate([
  50319. BABYLON.serializeAsVector3()
  50320. ], HemisphericLight.prototype, "direction", void 0);
  50321. return HemisphericLight;
  50322. }(BABYLON.Light));
  50323. BABYLON.HemisphericLight = HemisphericLight;
  50324. })(BABYLON || (BABYLON = {}));
  50325. //# sourceMappingURL=babylon.hemisphericLight.js.map
  50326. var BABYLON;
  50327. (function (BABYLON) {
  50328. /**
  50329. * Base implementation IShadowLight
  50330. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  50331. */
  50332. var ShadowLight = /** @class */ (function (_super) {
  50333. __extends(ShadowLight, _super);
  50334. function ShadowLight() {
  50335. var _this = _super !== null && _super.apply(this, arguments) || this;
  50336. _this._needProjectionMatrixCompute = true;
  50337. return _this;
  50338. }
  50339. ShadowLight.prototype._setPosition = function (value) {
  50340. this._position = value;
  50341. };
  50342. Object.defineProperty(ShadowLight.prototype, "position", {
  50343. /**
  50344. * Sets the position the shadow will be casted from. Also use as the light position for both
  50345. * point and spot lights.
  50346. */
  50347. get: function () {
  50348. return this._position;
  50349. },
  50350. /**
  50351. * Sets the position the shadow will be casted from. Also use as the light position for both
  50352. * point and spot lights.
  50353. */
  50354. set: function (value) {
  50355. this._setPosition(value);
  50356. },
  50357. enumerable: true,
  50358. configurable: true
  50359. });
  50360. ShadowLight.prototype._setDirection = function (value) {
  50361. this._direction = value;
  50362. };
  50363. Object.defineProperty(ShadowLight.prototype, "direction", {
  50364. /**
  50365. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  50366. * Also use as the light direction on spot and directional lights.
  50367. */
  50368. get: function () {
  50369. return this._direction;
  50370. },
  50371. /**
  50372. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  50373. * Also use as the light direction on spot and directional lights.
  50374. */
  50375. set: function (value) {
  50376. this._setDirection(value);
  50377. },
  50378. enumerable: true,
  50379. configurable: true
  50380. });
  50381. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  50382. /**
  50383. * Gets the shadow projection clipping minimum z value.
  50384. */
  50385. get: function () {
  50386. return this._shadowMinZ;
  50387. },
  50388. /**
  50389. * Sets the shadow projection clipping minimum z value.
  50390. */
  50391. set: function (value) {
  50392. this._shadowMinZ = value;
  50393. this.forceProjectionMatrixCompute();
  50394. },
  50395. enumerable: true,
  50396. configurable: true
  50397. });
  50398. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  50399. /**
  50400. * Sets the shadow projection clipping maximum z value.
  50401. */
  50402. get: function () {
  50403. return this._shadowMaxZ;
  50404. },
  50405. /**
  50406. * Gets the shadow projection clipping maximum z value.
  50407. */
  50408. set: function (value) {
  50409. this._shadowMaxZ = value;
  50410. this.forceProjectionMatrixCompute();
  50411. },
  50412. enumerable: true,
  50413. configurable: true
  50414. });
  50415. /**
  50416. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  50417. * @returns true if the information has been computed, false if it does not need to (no parenting)
  50418. */
  50419. ShadowLight.prototype.computeTransformedInformation = function () {
  50420. if (this.parent && this.parent.getWorldMatrix) {
  50421. if (!this.transformedPosition) {
  50422. this.transformedPosition = BABYLON.Vector3.Zero();
  50423. }
  50424. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  50425. // In case the direction is present.
  50426. if (this.direction) {
  50427. if (!this.transformedDirection) {
  50428. this.transformedDirection = BABYLON.Vector3.Zero();
  50429. }
  50430. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  50431. }
  50432. return true;
  50433. }
  50434. return false;
  50435. };
  50436. /**
  50437. * Return the depth scale used for the shadow map.
  50438. * @returns the depth scale.
  50439. */
  50440. ShadowLight.prototype.getDepthScale = function () {
  50441. return 50.0;
  50442. };
  50443. /**
  50444. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  50445. * @param faceIndex The index of the face we are computed the direction to generate shadow
  50446. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  50447. */
  50448. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  50449. return this.transformedDirection ? this.transformedDirection : this.direction;
  50450. };
  50451. /**
  50452. * Returns the ShadowLight absolute position in the World.
  50453. * @returns the position vector in world space
  50454. */
  50455. ShadowLight.prototype.getAbsolutePosition = function () {
  50456. return this.transformedPosition ? this.transformedPosition : this.position;
  50457. };
  50458. /**
  50459. * Sets the ShadowLight direction toward the passed target.
  50460. * @param target The point tot target in local space
  50461. * @returns the updated ShadowLight direction
  50462. */
  50463. ShadowLight.prototype.setDirectionToTarget = function (target) {
  50464. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  50465. return this.direction;
  50466. };
  50467. /**
  50468. * Returns the light rotation in euler definition.
  50469. * @returns the x y z rotation in local space.
  50470. */
  50471. ShadowLight.prototype.getRotation = function () {
  50472. this.direction.normalize();
  50473. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  50474. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  50475. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  50476. };
  50477. /**
  50478. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  50479. * @returns true if a cube texture needs to be use
  50480. */
  50481. ShadowLight.prototype.needCube = function () {
  50482. return false;
  50483. };
  50484. /**
  50485. * Detects if the projection matrix requires to be recomputed this frame.
  50486. * @returns true if it requires to be recomputed otherwise, false.
  50487. */
  50488. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  50489. return this._needProjectionMatrixCompute;
  50490. };
  50491. /**
  50492. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  50493. */
  50494. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  50495. this._needProjectionMatrixCompute = true;
  50496. };
  50497. /** @hidden */
  50498. ShadowLight.prototype._initCache = function () {
  50499. _super.prototype._initCache.call(this);
  50500. this._cache.position = BABYLON.Vector3.Zero();
  50501. };
  50502. /** @hidden */
  50503. ShadowLight.prototype._isSynchronized = function () {
  50504. if (!this._cache.position.equals(this.position))
  50505. return false;
  50506. return true;
  50507. };
  50508. /**
  50509. * Computes the world matrix of the node
  50510. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  50511. * @returns the world matrix
  50512. */
  50513. ShadowLight.prototype.computeWorldMatrix = function (force) {
  50514. if (!force && this.isSynchronized()) {
  50515. this._currentRenderId = this.getScene().getRenderId();
  50516. return this._worldMatrix;
  50517. }
  50518. this._updateCache();
  50519. this._cache.position.copyFrom(this.position);
  50520. if (!this._worldMatrix) {
  50521. this._worldMatrix = BABYLON.Matrix.Identity();
  50522. }
  50523. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  50524. if (this.parent && this.parent.getWorldMatrix) {
  50525. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  50526. this._markSyncedWithParent();
  50527. }
  50528. // Cache the determinant
  50529. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  50530. return this._worldMatrix;
  50531. };
  50532. /**
  50533. * Gets the minZ used for shadow according to both the scene and the light.
  50534. * @param activeCamera The camera we are returning the min for
  50535. * @returns the depth min z
  50536. */
  50537. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  50538. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  50539. };
  50540. /**
  50541. * Gets the maxZ used for shadow according to both the scene and the light.
  50542. * @param activeCamera The camera we are returning the max for
  50543. * @returns the depth max z
  50544. */
  50545. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  50546. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  50547. };
  50548. /**
  50549. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  50550. * @param matrix The materix to updated with the projection information
  50551. * @param viewMatrix The transform matrix of the light
  50552. * @param renderList The list of mesh to render in the map
  50553. * @returns The current light
  50554. */
  50555. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50556. if (this.customProjectionMatrixBuilder) {
  50557. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  50558. }
  50559. else {
  50560. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50561. }
  50562. return this;
  50563. };
  50564. __decorate([
  50565. BABYLON.serializeAsVector3()
  50566. ], ShadowLight.prototype, "position", null);
  50567. __decorate([
  50568. BABYLON.serializeAsVector3()
  50569. ], ShadowLight.prototype, "direction", null);
  50570. __decorate([
  50571. BABYLON.serialize()
  50572. ], ShadowLight.prototype, "shadowMinZ", null);
  50573. __decorate([
  50574. BABYLON.serialize()
  50575. ], ShadowLight.prototype, "shadowMaxZ", null);
  50576. return ShadowLight;
  50577. }(BABYLON.Light));
  50578. BABYLON.ShadowLight = ShadowLight;
  50579. })(BABYLON || (BABYLON = {}));
  50580. //# sourceMappingURL=babylon.shadowLight.js.map
  50581. var BABYLON;
  50582. (function (BABYLON) {
  50583. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  50584. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  50585. });
  50586. /**
  50587. * A point light is a light defined by an unique point in world space.
  50588. * The light is emitted in every direction from this point.
  50589. * A good example of a point light is a standard light bulb.
  50590. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50591. */
  50592. var PointLight = /** @class */ (function (_super) {
  50593. __extends(PointLight, _super);
  50594. /**
  50595. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  50596. * A PointLight emits the light in every direction.
  50597. * It can cast shadows.
  50598. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  50599. * ```javascript
  50600. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  50601. * ```
  50602. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50603. * @param name The light friendly name
  50604. * @param position The position of the point light in the scene
  50605. * @param scene The scene the lights belongs to
  50606. */
  50607. function PointLight(name, position, scene) {
  50608. var _this = _super.call(this, name, scene) || this;
  50609. _this._shadowAngle = Math.PI / 2;
  50610. _this.position = position;
  50611. return _this;
  50612. }
  50613. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  50614. /**
  50615. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50616. * This specifies what angle the shadow will use to be created.
  50617. *
  50618. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  50619. */
  50620. get: function () {
  50621. return this._shadowAngle;
  50622. },
  50623. /**
  50624. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50625. * This specifies what angle the shadow will use to be created.
  50626. *
  50627. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  50628. */
  50629. set: function (value) {
  50630. this._shadowAngle = value;
  50631. this.forceProjectionMatrixCompute();
  50632. },
  50633. enumerable: true,
  50634. configurable: true
  50635. });
  50636. Object.defineProperty(PointLight.prototype, "direction", {
  50637. /**
  50638. * Gets the direction if it has been set.
  50639. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50640. */
  50641. get: function () {
  50642. return this._direction;
  50643. },
  50644. /**
  50645. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  50646. */
  50647. set: function (value) {
  50648. var previousNeedCube = this.needCube();
  50649. this._direction = value;
  50650. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  50651. this._shadowGenerator.recreateShadowMap();
  50652. }
  50653. },
  50654. enumerable: true,
  50655. configurable: true
  50656. });
  50657. /**
  50658. * Returns the string "PointLight"
  50659. * @returns the class name
  50660. */
  50661. PointLight.prototype.getClassName = function () {
  50662. return "PointLight";
  50663. };
  50664. /**
  50665. * Returns the integer 0.
  50666. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50667. */
  50668. PointLight.prototype.getTypeID = function () {
  50669. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  50670. };
  50671. /**
  50672. * Specifies wether or not the shadowmap should be a cube texture.
  50673. * @returns true if the shadowmap needs to be a cube texture.
  50674. */
  50675. PointLight.prototype.needCube = function () {
  50676. return !this.direction;
  50677. };
  50678. /**
  50679. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  50680. * @param faceIndex The index of the face we are computed the direction to generate shadow
  50681. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  50682. */
  50683. PointLight.prototype.getShadowDirection = function (faceIndex) {
  50684. if (this.direction) {
  50685. return _super.prototype.getShadowDirection.call(this, faceIndex);
  50686. }
  50687. else {
  50688. switch (faceIndex) {
  50689. case 0:
  50690. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  50691. case 1:
  50692. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  50693. case 2:
  50694. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  50695. case 3:
  50696. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  50697. case 4:
  50698. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  50699. case 5:
  50700. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  50701. }
  50702. }
  50703. return BABYLON.Vector3.Zero();
  50704. };
  50705. /**
  50706. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  50707. * - fov = PI / 2
  50708. * - aspect ratio : 1.0
  50709. * - z-near and far equal to the active camera minZ and maxZ.
  50710. * Returns the PointLight.
  50711. */
  50712. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50713. var activeCamera = this.getScene().activeCamera;
  50714. if (!activeCamera) {
  50715. return;
  50716. }
  50717. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50718. };
  50719. PointLight.prototype._buildUniformLayout = function () {
  50720. this._uniformBuffer.addUniform("vLightData", 4);
  50721. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50722. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50723. this._uniformBuffer.addUniform("vLightFalloff", 4);
  50724. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50725. this._uniformBuffer.addUniform("depthValues", 2);
  50726. this._uniformBuffer.create();
  50727. };
  50728. /**
  50729. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  50730. * @param effect The effect to update
  50731. * @param lightIndex The index of the light in the effect to update
  50732. * @returns The point light
  50733. */
  50734. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  50735. if (this.computeTransformedInformation()) {
  50736. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  50737. }
  50738. else {
  50739. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  50740. }
  50741. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  50742. return this;
  50743. };
  50744. /**
  50745. * Prepares the list of defines specific to the light type.
  50746. * @param defines the list of defines
  50747. * @param lightIndex defines the index of the light for the effect
  50748. */
  50749. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50750. defines["POINTLIGHT" + lightIndex] = true;
  50751. };
  50752. __decorate([
  50753. BABYLON.serialize()
  50754. ], PointLight.prototype, "shadowAngle", null);
  50755. return PointLight;
  50756. }(BABYLON.ShadowLight));
  50757. BABYLON.PointLight = PointLight;
  50758. })(BABYLON || (BABYLON = {}));
  50759. //# sourceMappingURL=babylon.pointLight.js.map
  50760. var BABYLON;
  50761. (function (BABYLON) {
  50762. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  50763. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  50764. });
  50765. /**
  50766. * A directional light is defined by a direction (what a surprise!).
  50767. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  50768. * 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.
  50769. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50770. */
  50771. var DirectionalLight = /** @class */ (function (_super) {
  50772. __extends(DirectionalLight, _super);
  50773. /**
  50774. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  50775. * The directional light is emitted from everywhere in the given direction.
  50776. * It can cast shadows.
  50777. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50778. * @param name The friendly name of the light
  50779. * @param direction The direction of the light
  50780. * @param scene The scene the light belongs to
  50781. */
  50782. function DirectionalLight(name, direction, scene) {
  50783. var _this = _super.call(this, name, scene) || this;
  50784. _this._shadowFrustumSize = 0;
  50785. _this._shadowOrthoScale = 0.1;
  50786. /**
  50787. * Automatically compute the projection matrix to best fit (including all the casters)
  50788. * on each frame.
  50789. */
  50790. _this.autoUpdateExtends = true;
  50791. // Cache
  50792. _this._orthoLeft = Number.MAX_VALUE;
  50793. _this._orthoRight = Number.MIN_VALUE;
  50794. _this._orthoTop = Number.MIN_VALUE;
  50795. _this._orthoBottom = Number.MAX_VALUE;
  50796. _this.position = direction.scale(-1.0);
  50797. _this.direction = direction;
  50798. return _this;
  50799. }
  50800. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  50801. /**
  50802. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  50803. */
  50804. get: function () {
  50805. return this._shadowFrustumSize;
  50806. },
  50807. /**
  50808. * Specifies a fix frustum size for the shadow generation.
  50809. */
  50810. set: function (value) {
  50811. this._shadowFrustumSize = value;
  50812. this.forceProjectionMatrixCompute();
  50813. },
  50814. enumerable: true,
  50815. configurable: true
  50816. });
  50817. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  50818. /**
  50819. * Gets the shadow projection scale against the optimal computed one.
  50820. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50821. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50822. */
  50823. get: function () {
  50824. return this._shadowOrthoScale;
  50825. },
  50826. /**
  50827. * Sets the shadow projection scale against the optimal computed one.
  50828. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50829. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50830. */
  50831. set: function (value) {
  50832. this._shadowOrthoScale = value;
  50833. this.forceProjectionMatrixCompute();
  50834. },
  50835. enumerable: true,
  50836. configurable: true
  50837. });
  50838. /**
  50839. * Returns the string "DirectionalLight".
  50840. * @return The class name
  50841. */
  50842. DirectionalLight.prototype.getClassName = function () {
  50843. return "DirectionalLight";
  50844. };
  50845. /**
  50846. * Returns the integer 1.
  50847. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50848. */
  50849. DirectionalLight.prototype.getTypeID = function () {
  50850. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  50851. };
  50852. /**
  50853. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  50854. * Returns the DirectionalLight Shadow projection matrix.
  50855. */
  50856. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50857. if (this.shadowFrustumSize > 0) {
  50858. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  50859. }
  50860. else {
  50861. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50862. }
  50863. };
  50864. /**
  50865. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  50866. * Returns the DirectionalLight Shadow projection matrix.
  50867. */
  50868. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  50869. var activeCamera = this.getScene().activeCamera;
  50870. if (!activeCamera) {
  50871. return;
  50872. }
  50873. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  50874. };
  50875. /**
  50876. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  50877. * Returns the DirectionalLight Shadow projection matrix.
  50878. */
  50879. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50880. var activeCamera = this.getScene().activeCamera;
  50881. if (!activeCamera) {
  50882. return;
  50883. }
  50884. // Check extends
  50885. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  50886. var tempVector3 = BABYLON.Vector3.Zero();
  50887. this._orthoLeft = Number.MAX_VALUE;
  50888. this._orthoRight = Number.MIN_VALUE;
  50889. this._orthoTop = Number.MIN_VALUE;
  50890. this._orthoBottom = Number.MAX_VALUE;
  50891. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  50892. var mesh = renderList[meshIndex];
  50893. if (!mesh) {
  50894. continue;
  50895. }
  50896. var boundingInfo = mesh.getBoundingInfo();
  50897. var boundingBox = boundingInfo.boundingBox;
  50898. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  50899. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  50900. if (tempVector3.x < this._orthoLeft)
  50901. this._orthoLeft = tempVector3.x;
  50902. if (tempVector3.y < this._orthoBottom)
  50903. this._orthoBottom = tempVector3.y;
  50904. if (tempVector3.x > this._orthoRight)
  50905. this._orthoRight = tempVector3.x;
  50906. if (tempVector3.y > this._orthoTop)
  50907. this._orthoTop = tempVector3.y;
  50908. }
  50909. }
  50910. }
  50911. var xOffset = this._orthoRight - this._orthoLeft;
  50912. var yOffset = this._orthoTop - this._orthoBottom;
  50913. 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);
  50914. };
  50915. DirectionalLight.prototype._buildUniformLayout = function () {
  50916. this._uniformBuffer.addUniform("vLightData", 4);
  50917. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50918. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50919. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50920. this._uniformBuffer.addUniform("depthValues", 2);
  50921. this._uniformBuffer.create();
  50922. };
  50923. /**
  50924. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  50925. * @param effect The effect to update
  50926. * @param lightIndex The index of the light in the effect to update
  50927. * @returns The directional light
  50928. */
  50929. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  50930. if (this.computeTransformedInformation()) {
  50931. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  50932. return this;
  50933. }
  50934. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  50935. return this;
  50936. };
  50937. /**
  50938. * Gets the minZ used for shadow according to both the scene and the light.
  50939. *
  50940. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50941. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50942. * @param activeCamera The camera we are returning the min for
  50943. * @returns the depth min z
  50944. */
  50945. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  50946. return 1;
  50947. };
  50948. /**
  50949. * Gets the maxZ used for shadow according to both the scene and the light.
  50950. *
  50951. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50952. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50953. * @param activeCamera The camera we are returning the max for
  50954. * @returns the depth max z
  50955. */
  50956. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50957. return 1;
  50958. };
  50959. /**
  50960. * Prepares the list of defines specific to the light type.
  50961. * @param defines the list of defines
  50962. * @param lightIndex defines the index of the light for the effect
  50963. */
  50964. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50965. defines["DIRLIGHT" + lightIndex] = true;
  50966. };
  50967. __decorate([
  50968. BABYLON.serialize()
  50969. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50970. __decorate([
  50971. BABYLON.serialize()
  50972. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50973. __decorate([
  50974. BABYLON.serialize()
  50975. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50976. return DirectionalLight;
  50977. }(BABYLON.ShadowLight));
  50978. BABYLON.DirectionalLight = DirectionalLight;
  50979. })(BABYLON || (BABYLON = {}));
  50980. //# sourceMappingURL=babylon.directionalLight.js.map
  50981. var BABYLON;
  50982. (function (BABYLON) {
  50983. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  50984. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  50985. });
  50986. /**
  50987. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50988. * These values define a cone of light starting from the position, emitting toward the direction.
  50989. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50990. * and the exponent defines the speed of the decay of the light with distance (reach).
  50991. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50992. */
  50993. var SpotLight = /** @class */ (function (_super) {
  50994. __extends(SpotLight, _super);
  50995. /**
  50996. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50997. * It can cast shadows.
  50998. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50999. * @param name The light friendly name
  51000. * @param position The position of the spot light in the scene
  51001. * @param direction The direction of the light in the scene
  51002. * @param angle The cone angle of the light in Radians
  51003. * @param exponent The light decay speed with the distance from the emission spot
  51004. * @param scene The scene the lights belongs to
  51005. */
  51006. function SpotLight(name, position, direction, angle, exponent, scene) {
  51007. var _this = _super.call(this, name, scene) || this;
  51008. _this._innerAngle = 0;
  51009. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  51010. _this._projectionTextureLightNear = 1e-6;
  51011. _this._projectionTextureLightFar = 1000.0;
  51012. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  51013. _this._projectionTextureViewLightDirty = true;
  51014. _this._projectionTextureProjectionLightDirty = true;
  51015. _this._projectionTextureDirty = true;
  51016. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  51017. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  51018. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  51019. _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);
  51020. _this.position = position;
  51021. _this.direction = direction;
  51022. _this.angle = angle;
  51023. _this.exponent = exponent;
  51024. return _this;
  51025. }
  51026. Object.defineProperty(SpotLight.prototype, "angle", {
  51027. /**
  51028. * Gets the cone angle of the spot light in Radians.
  51029. */
  51030. get: function () {
  51031. return this._angle;
  51032. },
  51033. /**
  51034. * Sets the cone angle of the spot light in Radians.
  51035. */
  51036. set: function (value) {
  51037. this._angle = value;
  51038. this._cosHalfAngle = Math.cos(value * 0.5);
  51039. this._projectionTextureProjectionLightDirty = true;
  51040. this.forceProjectionMatrixCompute();
  51041. this._computeAngleValues();
  51042. },
  51043. enumerable: true,
  51044. configurable: true
  51045. });
  51046. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  51047. /**
  51048. * Only used in gltf falloff mode, this defines the angle where
  51049. * the directional falloff will start before cutting at angle which could be seen
  51050. * as outer angle.
  51051. */
  51052. get: function () {
  51053. return this._innerAngle;
  51054. },
  51055. /**
  51056. * Only used in gltf falloff mode, this defines the angle where
  51057. * the directional falloff will start before cutting at angle which could be seen
  51058. * as outer angle.
  51059. */
  51060. set: function (value) {
  51061. this._innerAngle = value;
  51062. this._computeAngleValues();
  51063. },
  51064. enumerable: true,
  51065. configurable: true
  51066. });
  51067. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  51068. /**
  51069. * Allows scaling the angle of the light for shadow generation only.
  51070. */
  51071. get: function () {
  51072. return this._shadowAngleScale;
  51073. },
  51074. /**
  51075. * Allows scaling the angle of the light for shadow generation only.
  51076. */
  51077. set: function (value) {
  51078. this._shadowAngleScale = value;
  51079. this.forceProjectionMatrixCompute();
  51080. },
  51081. enumerable: true,
  51082. configurable: true
  51083. });
  51084. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  51085. /**
  51086. * Allows reading the projecton texture
  51087. */
  51088. get: function () {
  51089. return this._projectionTextureMatrix;
  51090. },
  51091. enumerable: true,
  51092. configurable: true
  51093. });
  51094. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  51095. /**
  51096. * Gets the near clip of the Spotlight for texture projection.
  51097. */
  51098. get: function () {
  51099. return this._projectionTextureLightNear;
  51100. },
  51101. /**
  51102. * Sets the near clip of the Spotlight for texture projection.
  51103. */
  51104. set: function (value) {
  51105. this._projectionTextureLightNear = value;
  51106. this._projectionTextureProjectionLightDirty = true;
  51107. },
  51108. enumerable: true,
  51109. configurable: true
  51110. });
  51111. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  51112. /**
  51113. * Gets the far clip of the Spotlight for texture projection.
  51114. */
  51115. get: function () {
  51116. return this._projectionTextureLightFar;
  51117. },
  51118. /**
  51119. * Sets the far clip of the Spotlight for texture projection.
  51120. */
  51121. set: function (value) {
  51122. this._projectionTextureLightFar = value;
  51123. this._projectionTextureProjectionLightDirty = true;
  51124. },
  51125. enumerable: true,
  51126. configurable: true
  51127. });
  51128. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  51129. /**
  51130. * Gets the Up vector of the Spotlight for texture projection.
  51131. */
  51132. get: function () {
  51133. return this._projectionTextureUpDirection;
  51134. },
  51135. /**
  51136. * Sets the Up vector of the Spotlight for texture projection.
  51137. */
  51138. set: function (value) {
  51139. this._projectionTextureUpDirection = value;
  51140. this._projectionTextureProjectionLightDirty = true;
  51141. },
  51142. enumerable: true,
  51143. configurable: true
  51144. });
  51145. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  51146. /**
  51147. * Gets the projection texture of the light.
  51148. */
  51149. get: function () {
  51150. return this._projectionTexture;
  51151. },
  51152. /**
  51153. * Sets the projection texture of the light.
  51154. */
  51155. set: function (value) {
  51156. this._projectionTexture = value;
  51157. this._projectionTextureDirty = true;
  51158. },
  51159. enumerable: true,
  51160. configurable: true
  51161. });
  51162. /**
  51163. * Returns the string "SpotLight".
  51164. * @returns the class name
  51165. */
  51166. SpotLight.prototype.getClassName = function () {
  51167. return "SpotLight";
  51168. };
  51169. /**
  51170. * Returns the integer 2.
  51171. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51172. */
  51173. SpotLight.prototype.getTypeID = function () {
  51174. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  51175. };
  51176. /**
  51177. * Overrides the direction setter to recompute the projection texture view light Matrix.
  51178. */
  51179. SpotLight.prototype._setDirection = function (value) {
  51180. _super.prototype._setDirection.call(this, value);
  51181. this._projectionTextureViewLightDirty = true;
  51182. };
  51183. /**
  51184. * Overrides the position setter to recompute the projection texture view light Matrix.
  51185. */
  51186. SpotLight.prototype._setPosition = function (value) {
  51187. _super.prototype._setPosition.call(this, value);
  51188. this._projectionTextureViewLightDirty = true;
  51189. };
  51190. /**
  51191. * 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.
  51192. * Returns the SpotLight.
  51193. */
  51194. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51195. var activeCamera = this.getScene().activeCamera;
  51196. if (!activeCamera) {
  51197. return;
  51198. }
  51199. this._shadowAngleScale = this._shadowAngleScale || 1;
  51200. var angle = this._shadowAngleScale * this._angle;
  51201. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  51202. };
  51203. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  51204. this._projectionTextureViewLightDirty = false;
  51205. this._projectionTextureDirty = true;
  51206. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  51207. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  51208. };
  51209. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  51210. this._projectionTextureProjectionLightDirty = false;
  51211. this._projectionTextureDirty = true;
  51212. var light_far = this.projectionTextureLightFar;
  51213. var light_near = this.projectionTextureLightNear;
  51214. var P = light_far / (light_far - light_near);
  51215. var Q = -P * light_near;
  51216. var S = 1.0 / Math.tan(this._angle / 2.0);
  51217. var A = 1.0;
  51218. 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);
  51219. };
  51220. /**
  51221. * Main function for light texture projection matrix computing.
  51222. */
  51223. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  51224. this._projectionTextureDirty = false;
  51225. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  51226. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  51227. };
  51228. SpotLight.prototype._buildUniformLayout = function () {
  51229. this._uniformBuffer.addUniform("vLightData", 4);
  51230. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51231. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51232. this._uniformBuffer.addUniform("vLightDirection", 3);
  51233. this._uniformBuffer.addUniform("vLightFalloff", 4);
  51234. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51235. this._uniformBuffer.addUniform("depthValues", 2);
  51236. this._uniformBuffer.create();
  51237. };
  51238. SpotLight.prototype._computeAngleValues = function () {
  51239. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  51240. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  51241. };
  51242. /**
  51243. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  51244. * @param effect The effect to update
  51245. * @param lightIndex The index of the light in the effect to update
  51246. * @returns The spot light
  51247. */
  51248. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  51249. var normalizeDirection;
  51250. if (this.computeTransformedInformation()) {
  51251. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  51252. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  51253. }
  51254. else {
  51255. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  51256. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  51257. }
  51258. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  51259. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  51260. if (this.projectionTexture && this.projectionTexture.isReady()) {
  51261. if (this._projectionTextureViewLightDirty) {
  51262. this._computeProjectionTextureViewLightMatrix();
  51263. }
  51264. if (this._projectionTextureProjectionLightDirty) {
  51265. this._computeProjectionTextureProjectionLightMatrix();
  51266. }
  51267. if (this._projectionTextureDirty) {
  51268. this._computeProjectionTextureMatrix();
  51269. }
  51270. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  51271. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  51272. }
  51273. return this;
  51274. };
  51275. /**
  51276. * Disposes the light and the associated resources.
  51277. */
  51278. SpotLight.prototype.dispose = function () {
  51279. _super.prototype.dispose.call(this);
  51280. if (this._projectionTexture) {
  51281. this._projectionTexture.dispose();
  51282. }
  51283. };
  51284. /**
  51285. * Prepares the list of defines specific to the light type.
  51286. * @param defines the list of defines
  51287. * @param lightIndex defines the index of the light for the effect
  51288. */
  51289. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51290. defines["SPOTLIGHT" + lightIndex] = true;
  51291. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  51292. };
  51293. __decorate([
  51294. BABYLON.serialize()
  51295. ], SpotLight.prototype, "angle", null);
  51296. __decorate([
  51297. BABYLON.serialize()
  51298. ], SpotLight.prototype, "innerAngle", null);
  51299. __decorate([
  51300. BABYLON.serialize()
  51301. ], SpotLight.prototype, "shadowAngleScale", null);
  51302. __decorate([
  51303. BABYLON.serialize()
  51304. ], SpotLight.prototype, "exponent", void 0);
  51305. __decorate([
  51306. BABYLON.serialize()
  51307. ], SpotLight.prototype, "projectionTextureLightNear", null);
  51308. __decorate([
  51309. BABYLON.serialize()
  51310. ], SpotLight.prototype, "projectionTextureLightFar", null);
  51311. __decorate([
  51312. BABYLON.serialize()
  51313. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  51314. __decorate([
  51315. BABYLON.serializeAsTexture("projectedLightTexture")
  51316. ], SpotLight.prototype, "_projectionTexture", void 0);
  51317. return SpotLight;
  51318. }(BABYLON.ShadowLight));
  51319. BABYLON.SpotLight = SpotLight;
  51320. })(BABYLON || (BABYLON = {}));
  51321. //# sourceMappingURL=babylon.spotLight.js.map
  51322. var BABYLON;
  51323. (function (BABYLON) {
  51324. /**
  51325. * Class used to override all child animations of a given target
  51326. */
  51327. var AnimationPropertiesOverride = /** @class */ (function () {
  51328. function AnimationPropertiesOverride() {
  51329. /**
  51330. * Gets or sets a value indicating if animation blending must be used
  51331. */
  51332. this.enableBlending = false;
  51333. /**
  51334. * Gets or sets the blending speed to use when enableBlending is true
  51335. */
  51336. this.blendingSpeed = 0.01;
  51337. /**
  51338. * Gets or sets the default loop mode to use
  51339. */
  51340. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  51341. }
  51342. return AnimationPropertiesOverride;
  51343. }());
  51344. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  51345. })(BABYLON || (BABYLON = {}));
  51346. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  51347. var BABYLON;
  51348. (function (BABYLON) {
  51349. /**
  51350. * Represents the range of an animation
  51351. */
  51352. var AnimationRange = /** @class */ (function () {
  51353. /**
  51354. * Initializes the range of an animation
  51355. * @param name The name of the animation range
  51356. * @param from The starting frame of the animation
  51357. * @param to The ending frame of the animation
  51358. */
  51359. function AnimationRange(
  51360. /**The name of the animation range**/
  51361. name,
  51362. /**The starting frame of the animation */
  51363. from,
  51364. /**The ending frame of the animation*/
  51365. to) {
  51366. this.name = name;
  51367. this.from = from;
  51368. this.to = to;
  51369. }
  51370. /**
  51371. * Makes a copy of the animation range
  51372. * @returns A copy of the animation range
  51373. */
  51374. AnimationRange.prototype.clone = function () {
  51375. return new AnimationRange(this.name, this.from, this.to);
  51376. };
  51377. return AnimationRange;
  51378. }());
  51379. BABYLON.AnimationRange = AnimationRange;
  51380. /**
  51381. * Composed of a frame, and an action function
  51382. */
  51383. var AnimationEvent = /** @class */ (function () {
  51384. /**
  51385. * Initializes the animation event
  51386. * @param frame The frame for which the event is triggered
  51387. * @param action The event to perform when triggered
  51388. * @param onlyOnce Specifies if the event should be triggered only once
  51389. */
  51390. function AnimationEvent(
  51391. /** The frame for which the event is triggered **/
  51392. frame,
  51393. /** The event to perform when triggered **/
  51394. action,
  51395. /** Specifies if the event should be triggered only once**/
  51396. onlyOnce) {
  51397. this.frame = frame;
  51398. this.action = action;
  51399. this.onlyOnce = onlyOnce;
  51400. /**
  51401. * Specifies if the animation event is done
  51402. */
  51403. this.isDone = false;
  51404. }
  51405. /** @hidden */
  51406. AnimationEvent.prototype._clone = function () {
  51407. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  51408. };
  51409. return AnimationEvent;
  51410. }());
  51411. BABYLON.AnimationEvent = AnimationEvent;
  51412. /**
  51413. * A cursor which tracks a point on a path
  51414. */
  51415. var PathCursor = /** @class */ (function () {
  51416. /**
  51417. * Initializes the path cursor
  51418. * @param path The path to track
  51419. */
  51420. function PathCursor(path) {
  51421. this.path = path;
  51422. /**
  51423. * Stores path cursor callbacks for when an onchange event is triggered
  51424. */
  51425. this._onchange = new Array();
  51426. /**
  51427. * The value of the path cursor
  51428. */
  51429. this.value = 0;
  51430. /**
  51431. * The animation array of the path cursor
  51432. */
  51433. this.animations = new Array();
  51434. }
  51435. /**
  51436. * Gets the cursor point on the path
  51437. * @returns A point on the path cursor at the cursor location
  51438. */
  51439. PathCursor.prototype.getPoint = function () {
  51440. var point = this.path.getPointAtLengthPosition(this.value);
  51441. return new BABYLON.Vector3(point.x, 0, point.y);
  51442. };
  51443. /**
  51444. * Moves the cursor ahead by the step amount
  51445. * @param step The amount to move the cursor forward
  51446. * @returns This path cursor
  51447. */
  51448. PathCursor.prototype.moveAhead = function (step) {
  51449. if (step === void 0) { step = 0.002; }
  51450. this.move(step);
  51451. return this;
  51452. };
  51453. /**
  51454. * Moves the cursor behind by the step amount
  51455. * @param step The amount to move the cursor back
  51456. * @returns This path cursor
  51457. */
  51458. PathCursor.prototype.moveBack = function (step) {
  51459. if (step === void 0) { step = 0.002; }
  51460. this.move(-step);
  51461. return this;
  51462. };
  51463. /**
  51464. * Moves the cursor by the step amount
  51465. * If the step amount is greater than one, an exception is thrown
  51466. * @param step The amount to move the cursor
  51467. * @returns This path cursor
  51468. */
  51469. PathCursor.prototype.move = function (step) {
  51470. if (Math.abs(step) > 1) {
  51471. throw "step size should be less than 1.";
  51472. }
  51473. this.value += step;
  51474. this.ensureLimits();
  51475. this.raiseOnChange();
  51476. return this;
  51477. };
  51478. /**
  51479. * Ensures that the value is limited between zero and one
  51480. * @returns This path cursor
  51481. */
  51482. PathCursor.prototype.ensureLimits = function () {
  51483. while (this.value > 1) {
  51484. this.value -= 1;
  51485. }
  51486. while (this.value < 0) {
  51487. this.value += 1;
  51488. }
  51489. return this;
  51490. };
  51491. /**
  51492. * Runs onchange callbacks on change (used by the animation engine)
  51493. * @returns This path cursor
  51494. */
  51495. PathCursor.prototype.raiseOnChange = function () {
  51496. var _this = this;
  51497. this._onchange.forEach(function (f) { return f(_this); });
  51498. return this;
  51499. };
  51500. /**
  51501. * Executes a function on change
  51502. * @param f A path cursor onchange callback
  51503. * @returns This path cursor
  51504. */
  51505. PathCursor.prototype.onchange = function (f) {
  51506. this._onchange.push(f);
  51507. return this;
  51508. };
  51509. return PathCursor;
  51510. }());
  51511. BABYLON.PathCursor = PathCursor;
  51512. /**
  51513. * Enum for the animation key frame interpolation type
  51514. */
  51515. var AnimationKeyInterpolation;
  51516. (function (AnimationKeyInterpolation) {
  51517. /**
  51518. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  51519. */
  51520. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  51521. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  51522. /**
  51523. * Class used to store any kind of animation
  51524. */
  51525. var Animation = /** @class */ (function () {
  51526. /**
  51527. * Initializes the animation
  51528. * @param name Name of the animation
  51529. * @param targetProperty Property to animate
  51530. * @param framePerSecond The frames per second of the animation
  51531. * @param dataType The data type of the animation
  51532. * @param loopMode The loop mode of the animation
  51533. * @param enableBlendings Specifies if blending should be enabled
  51534. */
  51535. function Animation(
  51536. /**Name of the animation */
  51537. name,
  51538. /**Property to animate */
  51539. targetProperty,
  51540. /**The frames per second of the animation */
  51541. framePerSecond,
  51542. /**The data type of the animation */
  51543. dataType,
  51544. /**The loop mode of the animation */
  51545. loopMode,
  51546. /**Specifies if blending should be enabled */
  51547. enableBlending) {
  51548. this.name = name;
  51549. this.targetProperty = targetProperty;
  51550. this.framePerSecond = framePerSecond;
  51551. this.dataType = dataType;
  51552. this.loopMode = loopMode;
  51553. this.enableBlending = enableBlending;
  51554. /**
  51555. * @hidden Internal use only
  51556. */
  51557. this._runtimeAnimations = new Array();
  51558. /**
  51559. * The set of event that will be linked to this animation
  51560. */
  51561. this._events = new Array();
  51562. /**
  51563. * Stores the blending speed of the animation
  51564. */
  51565. this.blendingSpeed = 0.01;
  51566. /**
  51567. * Stores the animation ranges for the animation
  51568. */
  51569. this._ranges = {};
  51570. this.targetPropertyPath = targetProperty.split(".");
  51571. this.dataType = dataType;
  51572. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  51573. }
  51574. /**
  51575. * @hidden Internal use
  51576. */
  51577. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  51578. var dataType = undefined;
  51579. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  51580. dataType = Animation.ANIMATIONTYPE_FLOAT;
  51581. }
  51582. else if (from instanceof BABYLON.Quaternion) {
  51583. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  51584. }
  51585. else if (from instanceof BABYLON.Vector3) {
  51586. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  51587. }
  51588. else if (from instanceof BABYLON.Vector2) {
  51589. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  51590. }
  51591. else if (from instanceof BABYLON.Color3) {
  51592. dataType = Animation.ANIMATIONTYPE_COLOR3;
  51593. }
  51594. else if (from instanceof BABYLON.Size) {
  51595. dataType = Animation.ANIMATIONTYPE_SIZE;
  51596. }
  51597. if (dataType == undefined) {
  51598. return null;
  51599. }
  51600. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  51601. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  51602. animation.setKeys(keys);
  51603. if (easingFunction !== undefined) {
  51604. animation.setEasingFunction(easingFunction);
  51605. }
  51606. return animation;
  51607. };
  51608. /**
  51609. * Sets up an animation
  51610. * @param property The property to animate
  51611. * @param animationType The animation type to apply
  51612. * @param framePerSecond The frames per second of the animation
  51613. * @param easingFunction The easing function used in the animation
  51614. * @returns The created animation
  51615. */
  51616. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  51617. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  51618. animation.setEasingFunction(easingFunction);
  51619. return animation;
  51620. };
  51621. /**
  51622. * Create and start an animation on a node
  51623. * @param name defines the name of the global animation that will be run on all nodes
  51624. * @param node defines the root node where the animation will take place
  51625. * @param targetProperty defines property to animate
  51626. * @param framePerSecond defines the number of frame per second yo use
  51627. * @param totalFrame defines the number of frames in total
  51628. * @param from defines the initial value
  51629. * @param to defines the final value
  51630. * @param loopMode defines which loop mode you want to use (off by default)
  51631. * @param easingFunction defines the easing function to use (linear by default)
  51632. * @param onAnimationEnd defines the callback to call when animation end
  51633. * @returns the animatable created for this animation
  51634. */
  51635. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  51636. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  51637. if (!animation) {
  51638. return null;
  51639. }
  51640. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  51641. };
  51642. /**
  51643. * Create and start an animation on a node and its descendants
  51644. * @param name defines the name of the global animation that will be run on all nodes
  51645. * @param node defines the root node where the animation will take place
  51646. * @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
  51647. * @param targetProperty defines property to animate
  51648. * @param framePerSecond defines the number of frame per second to use
  51649. * @param totalFrame defines the number of frames in total
  51650. * @param from defines the initial value
  51651. * @param to defines the final value
  51652. * @param loopMode defines which loop mode you want to use (off by default)
  51653. * @param easingFunction defines the easing function to use (linear by default)
  51654. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  51655. * @returns the list of animatables created for all nodes
  51656. * @example https://www.babylonjs-playground.com/#MH0VLI
  51657. */
  51658. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  51659. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  51660. if (!animation) {
  51661. return null;
  51662. }
  51663. var scene = node.getScene();
  51664. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  51665. };
  51666. /**
  51667. * Creates a new animation, merges it with the existing animations and starts it
  51668. * @param name Name of the animation
  51669. * @param node Node which contains the scene that begins the animations
  51670. * @param targetProperty Specifies which property to animate
  51671. * @param framePerSecond The frames per second of the animation
  51672. * @param totalFrame The total number of frames
  51673. * @param from The frame at the beginning of the animation
  51674. * @param to The frame at the end of the animation
  51675. * @param loopMode Specifies the loop mode of the animation
  51676. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  51677. * @param onAnimationEnd Callback to run once the animation is complete
  51678. * @returns Nullable animation
  51679. */
  51680. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  51681. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  51682. if (!animation) {
  51683. return null;
  51684. }
  51685. node.animations.push(animation);
  51686. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  51687. };
  51688. /**
  51689. * Transition property of an host to the target Value
  51690. * @param property The property to transition
  51691. * @param targetValue The target Value of the property
  51692. * @param host The object where the property to animate belongs
  51693. * @param scene Scene used to run the animation
  51694. * @param frameRate Framerate (in frame/s) to use
  51695. * @param transition The transition type we want to use
  51696. * @param duration The duration of the animation, in milliseconds
  51697. * @param onAnimationEnd Callback trigger at the end of the animation
  51698. * @returns Nullable animation
  51699. */
  51700. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  51701. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  51702. if (duration <= 0) {
  51703. host[property] = targetValue;
  51704. if (onAnimationEnd) {
  51705. onAnimationEnd();
  51706. }
  51707. return null;
  51708. }
  51709. var endFrame = frameRate * (duration / 1000);
  51710. transition.setKeys([{
  51711. frame: 0,
  51712. value: host[property].clone ? host[property].clone() : host[property]
  51713. },
  51714. {
  51715. frame: endFrame,
  51716. value: targetValue
  51717. }]);
  51718. if (!host.animations) {
  51719. host.animations = [];
  51720. }
  51721. host.animations.push(transition);
  51722. var animation = scene.beginAnimation(host, 0, endFrame, false);
  51723. animation.onAnimationEnd = onAnimationEnd;
  51724. return animation;
  51725. };
  51726. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  51727. /**
  51728. * Return the array of runtime animations currently using this animation
  51729. */
  51730. get: function () {
  51731. return this._runtimeAnimations;
  51732. },
  51733. enumerable: true,
  51734. configurable: true
  51735. });
  51736. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  51737. /**
  51738. * Specifies if any of the runtime animations are currently running
  51739. */
  51740. get: function () {
  51741. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  51742. var runtimeAnimation = _a[_i];
  51743. if (!runtimeAnimation.isStopped) {
  51744. return true;
  51745. }
  51746. }
  51747. return false;
  51748. },
  51749. enumerable: true,
  51750. configurable: true
  51751. });
  51752. // Methods
  51753. /**
  51754. * Converts the animation to a string
  51755. * @param fullDetails support for multiple levels of logging within scene loading
  51756. * @returns String form of the animation
  51757. */
  51758. Animation.prototype.toString = function (fullDetails) {
  51759. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  51760. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  51761. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  51762. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  51763. if (fullDetails) {
  51764. ret += ", Ranges: {";
  51765. var first = true;
  51766. for (var name in this._ranges) {
  51767. if (first) {
  51768. ret += ", ";
  51769. first = false;
  51770. }
  51771. ret += name;
  51772. }
  51773. ret += "}";
  51774. }
  51775. return ret;
  51776. };
  51777. /**
  51778. * Add an event to this animation
  51779. * @param event Event to add
  51780. */
  51781. Animation.prototype.addEvent = function (event) {
  51782. this._events.push(event);
  51783. };
  51784. /**
  51785. * Remove all events found at the given frame
  51786. * @param frame The frame to remove events from
  51787. */
  51788. Animation.prototype.removeEvents = function (frame) {
  51789. for (var index = 0; index < this._events.length; index++) {
  51790. if (this._events[index].frame === frame) {
  51791. this._events.splice(index, 1);
  51792. index--;
  51793. }
  51794. }
  51795. };
  51796. /**
  51797. * Retrieves all the events from the animation
  51798. * @returns Events from the animation
  51799. */
  51800. Animation.prototype.getEvents = function () {
  51801. return this._events;
  51802. };
  51803. /**
  51804. * Creates an animation range
  51805. * @param name Name of the animation range
  51806. * @param from Starting frame of the animation range
  51807. * @param to Ending frame of the animation
  51808. */
  51809. Animation.prototype.createRange = function (name, from, to) {
  51810. // check name not already in use; could happen for bones after serialized
  51811. if (!this._ranges[name]) {
  51812. this._ranges[name] = new AnimationRange(name, from, to);
  51813. }
  51814. };
  51815. /**
  51816. * Deletes an animation range by name
  51817. * @param name Name of the animation range to delete
  51818. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  51819. */
  51820. Animation.prototype.deleteRange = function (name, deleteFrames) {
  51821. if (deleteFrames === void 0) { deleteFrames = true; }
  51822. var range = this._ranges[name];
  51823. if (!range) {
  51824. return;
  51825. }
  51826. if (deleteFrames) {
  51827. var from = range.from;
  51828. var to = range.to;
  51829. // this loop MUST go high to low for multiple splices to work
  51830. for (var key = this._keys.length - 1; key >= 0; key--) {
  51831. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  51832. this._keys.splice(key, 1);
  51833. }
  51834. }
  51835. }
  51836. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  51837. };
  51838. /**
  51839. * Gets the animation range by name, or null if not defined
  51840. * @param name Name of the animation range
  51841. * @returns Nullable animation range
  51842. */
  51843. Animation.prototype.getRange = function (name) {
  51844. return this._ranges[name];
  51845. };
  51846. /**
  51847. * Gets the key frames from the animation
  51848. * @returns The key frames of the animation
  51849. */
  51850. Animation.prototype.getKeys = function () {
  51851. return this._keys;
  51852. };
  51853. /**
  51854. * Gets the highest frame rate of the animation
  51855. * @returns Highest frame rate of the animation
  51856. */
  51857. Animation.prototype.getHighestFrame = function () {
  51858. var ret = 0;
  51859. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  51860. if (ret < this._keys[key].frame) {
  51861. ret = this._keys[key].frame;
  51862. }
  51863. }
  51864. return ret;
  51865. };
  51866. /**
  51867. * Gets the easing function of the animation
  51868. * @returns Easing function of the animation
  51869. */
  51870. Animation.prototype.getEasingFunction = function () {
  51871. return this._easingFunction;
  51872. };
  51873. /**
  51874. * Sets the easing function of the animation
  51875. * @param easingFunction A custom mathematical formula for animation
  51876. */
  51877. Animation.prototype.setEasingFunction = function (easingFunction) {
  51878. this._easingFunction = easingFunction;
  51879. };
  51880. /**
  51881. * Interpolates a scalar linearly
  51882. * @param startValue Start value of the animation curve
  51883. * @param endValue End value of the animation curve
  51884. * @param gradient Scalar amount to interpolate
  51885. * @returns Interpolated scalar value
  51886. */
  51887. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  51888. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  51889. };
  51890. /**
  51891. * Interpolates a scalar cubically
  51892. * @param startValue Start value of the animation curve
  51893. * @param outTangent End tangent of the animation
  51894. * @param endValue End value of the animation curve
  51895. * @param inTangent Start tangent of the animation curve
  51896. * @param gradient Scalar amount to interpolate
  51897. * @returns Interpolated scalar value
  51898. */
  51899. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51900. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51901. };
  51902. /**
  51903. * Interpolates a quaternion using a spherical linear interpolation
  51904. * @param startValue Start value of the animation curve
  51905. * @param endValue End value of the animation curve
  51906. * @param gradient Scalar amount to interpolate
  51907. * @returns Interpolated quaternion value
  51908. */
  51909. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  51910. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  51911. };
  51912. /**
  51913. * Interpolates a quaternion cubically
  51914. * @param startValue Start value of the animation curve
  51915. * @param outTangent End tangent of the animation curve
  51916. * @param endValue End value of the animation curve
  51917. * @param inTangent Start tangent of the animation curve
  51918. * @param gradient Scalar amount to interpolate
  51919. * @returns Interpolated quaternion value
  51920. */
  51921. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51922. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  51923. };
  51924. /**
  51925. * Interpolates a Vector3 linearl
  51926. * @param startValue Start value of the animation curve
  51927. * @param endValue End value of the animation curve
  51928. * @param gradient Scalar amount to interpolate
  51929. * @returns Interpolated scalar value
  51930. */
  51931. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  51932. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  51933. };
  51934. /**
  51935. * Interpolates a Vector3 cubically
  51936. * @param startValue Start value of the animation curve
  51937. * @param outTangent End tangent of the animation
  51938. * @param endValue End value of the animation curve
  51939. * @param inTangent Start tangent of the animation curve
  51940. * @param gradient Scalar amount to interpolate
  51941. * @returns InterpolatedVector3 value
  51942. */
  51943. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51944. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51945. };
  51946. /**
  51947. * Interpolates a Vector2 linearly
  51948. * @param startValue Start value of the animation curve
  51949. * @param endValue End value of the animation curve
  51950. * @param gradient Scalar amount to interpolate
  51951. * @returns Interpolated Vector2 value
  51952. */
  51953. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  51954. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  51955. };
  51956. /**
  51957. * Interpolates a Vector2 cubically
  51958. * @param startValue Start value of the animation curve
  51959. * @param outTangent End tangent of the animation
  51960. * @param endValue End value of the animation curve
  51961. * @param inTangent Start tangent of the animation curve
  51962. * @param gradient Scalar amount to interpolate
  51963. * @returns Interpolated Vector2 value
  51964. */
  51965. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51966. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51967. };
  51968. /**
  51969. * Interpolates a size linearly
  51970. * @param startValue Start value of the animation curve
  51971. * @param endValue End value of the animation curve
  51972. * @param gradient Scalar amount to interpolate
  51973. * @returns Interpolated Size value
  51974. */
  51975. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  51976. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  51977. };
  51978. /**
  51979. * Interpolates a Color3 linearly
  51980. * @param startValue Start value of the animation curve
  51981. * @param endValue End value of the animation curve
  51982. * @param gradient Scalar amount to interpolate
  51983. * @returns Interpolated Color3 value
  51984. */
  51985. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51986. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51987. };
  51988. /**
  51989. * @hidden Internal use only
  51990. */
  51991. Animation.prototype._getKeyValue = function (value) {
  51992. if (typeof value === "function") {
  51993. return value();
  51994. }
  51995. return value;
  51996. };
  51997. /**
  51998. * @hidden Internal use only
  51999. */
  52000. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  52001. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  52002. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  52003. }
  52004. var keys = this.getKeys();
  52005. // Try to get a hash to find the right key
  52006. 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));
  52007. if (keys[startKeyIndex].frame >= currentFrame) {
  52008. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  52009. startKeyIndex--;
  52010. }
  52011. }
  52012. for (var key = startKeyIndex; key < keys.length; key++) {
  52013. var endKey = keys[key + 1];
  52014. if (endKey.frame >= currentFrame) {
  52015. var startKey = keys[key];
  52016. var startValue = this._getKeyValue(startKey.value);
  52017. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  52018. return startValue;
  52019. }
  52020. var endValue = this._getKeyValue(endKey.value);
  52021. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  52022. var frameDelta = endKey.frame - startKey.frame;
  52023. // gradient : percent of currentFrame between the frame inf and the frame sup
  52024. var gradient = (currentFrame - startKey.frame) / frameDelta;
  52025. // check for easingFunction and correction of gradient
  52026. var easingFunction = this.getEasingFunction();
  52027. if (easingFunction != null) {
  52028. gradient = easingFunction.ease(gradient);
  52029. }
  52030. switch (this.dataType) {
  52031. // Float
  52032. case Animation.ANIMATIONTYPE_FLOAT:
  52033. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  52034. switch (loopMode) {
  52035. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52036. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52037. return floatValue;
  52038. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52039. return offsetValue * repeatCount + floatValue;
  52040. }
  52041. break;
  52042. // Quaternion
  52043. case Animation.ANIMATIONTYPE_QUATERNION:
  52044. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  52045. switch (loopMode) {
  52046. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52047. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52048. return quatValue;
  52049. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52050. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  52051. }
  52052. return quatValue;
  52053. // Vector3
  52054. case Animation.ANIMATIONTYPE_VECTOR3:
  52055. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  52056. switch (loopMode) {
  52057. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52058. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52059. return vec3Value;
  52060. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52061. return vec3Value.add(offsetValue.scale(repeatCount));
  52062. }
  52063. // Vector2
  52064. case Animation.ANIMATIONTYPE_VECTOR2:
  52065. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  52066. switch (loopMode) {
  52067. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52068. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52069. return vec2Value;
  52070. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52071. return vec2Value.add(offsetValue.scale(repeatCount));
  52072. }
  52073. // Size
  52074. case Animation.ANIMATIONTYPE_SIZE:
  52075. switch (loopMode) {
  52076. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52077. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52078. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  52079. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52080. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  52081. }
  52082. // Color3
  52083. case Animation.ANIMATIONTYPE_COLOR3:
  52084. switch (loopMode) {
  52085. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52086. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52087. return this.color3InterpolateFunction(startValue, endValue, gradient);
  52088. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52089. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  52090. }
  52091. // Matrix
  52092. case Animation.ANIMATIONTYPE_MATRIX:
  52093. switch (loopMode) {
  52094. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52095. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52096. if (Animation.AllowMatricesInterpolation) {
  52097. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  52098. }
  52099. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52100. return startValue;
  52101. }
  52102. default:
  52103. break;
  52104. }
  52105. break;
  52106. }
  52107. }
  52108. return this._getKeyValue(keys[keys.length - 1].value);
  52109. };
  52110. /**
  52111. * Defines the function to use to interpolate matrices
  52112. * @param startValue defines the start matrix
  52113. * @param endValue defines the end matrix
  52114. * @param gradient defines the gradient between both matrices
  52115. * @param result defines an optional target matrix where to store the interpolation
  52116. * @returns the interpolated matrix
  52117. */
  52118. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  52119. if (Animation.AllowMatrixDecomposeForInterpolation) {
  52120. if (result) {
  52121. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  52122. return result;
  52123. }
  52124. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  52125. }
  52126. if (result) {
  52127. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  52128. return result;
  52129. }
  52130. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  52131. };
  52132. /**
  52133. * Makes a copy of the animation
  52134. * @returns Cloned animation
  52135. */
  52136. Animation.prototype.clone = function () {
  52137. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  52138. clone.enableBlending = this.enableBlending;
  52139. clone.blendingSpeed = this.blendingSpeed;
  52140. if (this._keys) {
  52141. clone.setKeys(this._keys);
  52142. }
  52143. if (this._ranges) {
  52144. clone._ranges = {};
  52145. for (var name in this._ranges) {
  52146. var range = this._ranges[name];
  52147. if (!range) {
  52148. continue;
  52149. }
  52150. clone._ranges[name] = range.clone();
  52151. }
  52152. }
  52153. return clone;
  52154. };
  52155. /**
  52156. * Sets the key frames of the animation
  52157. * @param values The animation key frames to set
  52158. */
  52159. Animation.prototype.setKeys = function (values) {
  52160. this._keys = values.slice(0);
  52161. };
  52162. /**
  52163. * Serializes the animation to an object
  52164. * @returns Serialized object
  52165. */
  52166. Animation.prototype.serialize = function () {
  52167. var serializationObject = {};
  52168. serializationObject.name = this.name;
  52169. serializationObject.property = this.targetProperty;
  52170. serializationObject.framePerSecond = this.framePerSecond;
  52171. serializationObject.dataType = this.dataType;
  52172. serializationObject.loopBehavior = this.loopMode;
  52173. serializationObject.enableBlending = this.enableBlending;
  52174. serializationObject.blendingSpeed = this.blendingSpeed;
  52175. var dataType = this.dataType;
  52176. serializationObject.keys = [];
  52177. var keys = this.getKeys();
  52178. for (var index = 0; index < keys.length; index++) {
  52179. var animationKey = keys[index];
  52180. var key = {};
  52181. key.frame = animationKey.frame;
  52182. switch (dataType) {
  52183. case Animation.ANIMATIONTYPE_FLOAT:
  52184. key.values = [animationKey.value];
  52185. break;
  52186. case Animation.ANIMATIONTYPE_QUATERNION:
  52187. case Animation.ANIMATIONTYPE_MATRIX:
  52188. case Animation.ANIMATIONTYPE_VECTOR3:
  52189. case Animation.ANIMATIONTYPE_COLOR3:
  52190. key.values = animationKey.value.asArray();
  52191. break;
  52192. }
  52193. serializationObject.keys.push(key);
  52194. }
  52195. serializationObject.ranges = [];
  52196. for (var name in this._ranges) {
  52197. var source = this._ranges[name];
  52198. if (!source) {
  52199. continue;
  52200. }
  52201. var range = {};
  52202. range.name = name;
  52203. range.from = source.from;
  52204. range.to = source.to;
  52205. serializationObject.ranges.push(range);
  52206. }
  52207. return serializationObject;
  52208. };
  52209. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  52210. /**
  52211. * Get the float animation type
  52212. */
  52213. get: function () {
  52214. return Animation._ANIMATIONTYPE_FLOAT;
  52215. },
  52216. enumerable: true,
  52217. configurable: true
  52218. });
  52219. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  52220. /**
  52221. * Get the Vector3 animation type
  52222. */
  52223. get: function () {
  52224. return Animation._ANIMATIONTYPE_VECTOR3;
  52225. },
  52226. enumerable: true,
  52227. configurable: true
  52228. });
  52229. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  52230. /**
  52231. * Get the Vector2 animation type
  52232. */
  52233. get: function () {
  52234. return Animation._ANIMATIONTYPE_VECTOR2;
  52235. },
  52236. enumerable: true,
  52237. configurable: true
  52238. });
  52239. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  52240. /**
  52241. * Get the Size animation type
  52242. */
  52243. get: function () {
  52244. return Animation._ANIMATIONTYPE_SIZE;
  52245. },
  52246. enumerable: true,
  52247. configurable: true
  52248. });
  52249. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  52250. /**
  52251. * Get the Quaternion animation type
  52252. */
  52253. get: function () {
  52254. return Animation._ANIMATIONTYPE_QUATERNION;
  52255. },
  52256. enumerable: true,
  52257. configurable: true
  52258. });
  52259. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  52260. /**
  52261. * Get the Matrix animation type
  52262. */
  52263. get: function () {
  52264. return Animation._ANIMATIONTYPE_MATRIX;
  52265. },
  52266. enumerable: true,
  52267. configurable: true
  52268. });
  52269. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  52270. /**
  52271. * Get the Color3 animation type
  52272. */
  52273. get: function () {
  52274. return Animation._ANIMATIONTYPE_COLOR3;
  52275. },
  52276. enumerable: true,
  52277. configurable: true
  52278. });
  52279. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  52280. /**
  52281. * Get the Relative Loop Mode
  52282. */
  52283. get: function () {
  52284. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  52285. },
  52286. enumerable: true,
  52287. configurable: true
  52288. });
  52289. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  52290. /**
  52291. * Get the Cycle Loop Mode
  52292. */
  52293. get: function () {
  52294. return Animation._ANIMATIONLOOPMODE_CYCLE;
  52295. },
  52296. enumerable: true,
  52297. configurable: true
  52298. });
  52299. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  52300. /**
  52301. * Get the Constant Loop Mode
  52302. */
  52303. get: function () {
  52304. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  52305. },
  52306. enumerable: true,
  52307. configurable: true
  52308. });
  52309. /** @hidden */
  52310. Animation._UniversalLerp = function (left, right, amount) {
  52311. var constructor = left.constructor;
  52312. if (constructor.Lerp) { // Lerp supported
  52313. return constructor.Lerp(left, right, amount);
  52314. }
  52315. else if (constructor.Slerp) { // Slerp supported
  52316. return constructor.Slerp(left, right, amount);
  52317. }
  52318. else if (left.toFixed) { // Number
  52319. return left * (1.0 - amount) + amount * right;
  52320. }
  52321. else { // Blending not supported
  52322. return right;
  52323. }
  52324. };
  52325. /**
  52326. * Parses an animation object and creates an animation
  52327. * @param parsedAnimation Parsed animation object
  52328. * @returns Animation object
  52329. */
  52330. Animation.Parse = function (parsedAnimation) {
  52331. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  52332. var dataType = parsedAnimation.dataType;
  52333. var keys = [];
  52334. var data;
  52335. var index;
  52336. if (parsedAnimation.enableBlending) {
  52337. animation.enableBlending = parsedAnimation.enableBlending;
  52338. }
  52339. if (parsedAnimation.blendingSpeed) {
  52340. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  52341. }
  52342. for (index = 0; index < parsedAnimation.keys.length; index++) {
  52343. var key = parsedAnimation.keys[index];
  52344. var inTangent;
  52345. var outTangent;
  52346. switch (dataType) {
  52347. case Animation.ANIMATIONTYPE_FLOAT:
  52348. data = key.values[0];
  52349. if (key.values.length >= 1) {
  52350. inTangent = key.values[1];
  52351. }
  52352. if (key.values.length >= 2) {
  52353. outTangent = key.values[2];
  52354. }
  52355. break;
  52356. case Animation.ANIMATIONTYPE_QUATERNION:
  52357. data = BABYLON.Quaternion.FromArray(key.values);
  52358. if (key.values.length >= 8) {
  52359. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  52360. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  52361. inTangent = _inTangent;
  52362. }
  52363. }
  52364. if (key.values.length >= 12) {
  52365. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  52366. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  52367. outTangent = _outTangent;
  52368. }
  52369. }
  52370. break;
  52371. case Animation.ANIMATIONTYPE_MATRIX:
  52372. data = BABYLON.Matrix.FromArray(key.values);
  52373. break;
  52374. case Animation.ANIMATIONTYPE_COLOR3:
  52375. data = BABYLON.Color3.FromArray(key.values);
  52376. break;
  52377. case Animation.ANIMATIONTYPE_VECTOR3:
  52378. default:
  52379. data = BABYLON.Vector3.FromArray(key.values);
  52380. break;
  52381. }
  52382. var keyData = {};
  52383. keyData.frame = key.frame;
  52384. keyData.value = data;
  52385. if (inTangent != undefined) {
  52386. keyData.inTangent = inTangent;
  52387. }
  52388. if (outTangent != undefined) {
  52389. keyData.outTangent = outTangent;
  52390. }
  52391. keys.push(keyData);
  52392. }
  52393. animation.setKeys(keys);
  52394. if (parsedAnimation.ranges) {
  52395. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  52396. data = parsedAnimation.ranges[index];
  52397. animation.createRange(data.name, data.from, data.to);
  52398. }
  52399. }
  52400. return animation;
  52401. };
  52402. /**
  52403. * Appends the serialized animations from the source animations
  52404. * @param source Source containing the animations
  52405. * @param destination Target to store the animations
  52406. */
  52407. Animation.AppendSerializedAnimations = function (source, destination) {
  52408. if (source.animations) {
  52409. destination.animations = [];
  52410. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  52411. var animation = source.animations[animationIndex];
  52412. destination.animations.push(animation.serialize());
  52413. }
  52414. }
  52415. };
  52416. /**
  52417. * Use matrix interpolation instead of using direct key value when animating matrices
  52418. */
  52419. Animation.AllowMatricesInterpolation = false;
  52420. /**
  52421. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  52422. */
  52423. Animation.AllowMatrixDecomposeForInterpolation = true;
  52424. // Statics
  52425. /**
  52426. * Float animation type
  52427. */
  52428. Animation._ANIMATIONTYPE_FLOAT = 0;
  52429. /**
  52430. * Vector3 animation type
  52431. */
  52432. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  52433. /**
  52434. * Quaternion animation type
  52435. */
  52436. Animation._ANIMATIONTYPE_QUATERNION = 2;
  52437. /**
  52438. * Matrix animation type
  52439. */
  52440. Animation._ANIMATIONTYPE_MATRIX = 3;
  52441. /**
  52442. * Color3 animation type
  52443. */
  52444. Animation._ANIMATIONTYPE_COLOR3 = 4;
  52445. /**
  52446. * Vector2 animation type
  52447. */
  52448. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  52449. /**
  52450. * Size animation type
  52451. */
  52452. Animation._ANIMATIONTYPE_SIZE = 6;
  52453. /**
  52454. * Relative Loop Mode
  52455. */
  52456. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  52457. /**
  52458. * Cycle Loop Mode
  52459. */
  52460. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  52461. /**
  52462. * Constant Loop Mode
  52463. */
  52464. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  52465. return Animation;
  52466. }());
  52467. BABYLON.Animation = Animation;
  52468. })(BABYLON || (BABYLON = {}));
  52469. //# sourceMappingURL=babylon.animation.js.map
  52470. var BABYLON;
  52471. (function (BABYLON) {
  52472. /**
  52473. * This class defines the direct association between an animation and a target
  52474. */
  52475. var TargetedAnimation = /** @class */ (function () {
  52476. function TargetedAnimation() {
  52477. }
  52478. return TargetedAnimation;
  52479. }());
  52480. BABYLON.TargetedAnimation = TargetedAnimation;
  52481. /**
  52482. * Use this class to create coordinated animations on multiple targets
  52483. */
  52484. var AnimationGroup = /** @class */ (function () {
  52485. /**
  52486. * Instantiates a new Animation Group.
  52487. * This helps managing several animations at once.
  52488. * @see http://doc.babylonjs.com/how_to/group
  52489. * @param name Defines the name of the group
  52490. * @param scene Defines the scene the group belongs to
  52491. */
  52492. function AnimationGroup(
  52493. /** The name of the animation group */
  52494. name, scene) {
  52495. if (scene === void 0) { scene = null; }
  52496. this.name = name;
  52497. this._targetedAnimations = new Array();
  52498. this._animatables = new Array();
  52499. this._from = Number.MAX_VALUE;
  52500. this._to = -Number.MAX_VALUE;
  52501. this._speedRatio = 1;
  52502. /**
  52503. * This observable will notify when one animation have ended.
  52504. */
  52505. this.onAnimationEndObservable = new BABYLON.Observable();
  52506. /**
  52507. * This observable will notify when all animations have ended.
  52508. */
  52509. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  52510. /**
  52511. * This observable will notify when all animations have paused.
  52512. */
  52513. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  52514. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52515. this._scene.animationGroups.push(this);
  52516. }
  52517. Object.defineProperty(AnimationGroup.prototype, "from", {
  52518. /**
  52519. * Gets the first frame
  52520. */
  52521. get: function () {
  52522. return this._from;
  52523. },
  52524. enumerable: true,
  52525. configurable: true
  52526. });
  52527. Object.defineProperty(AnimationGroup.prototype, "to", {
  52528. /**
  52529. * Gets the last frame
  52530. */
  52531. get: function () {
  52532. return this._to;
  52533. },
  52534. enumerable: true,
  52535. configurable: true
  52536. });
  52537. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  52538. /**
  52539. * Define if the animations are started
  52540. */
  52541. get: function () {
  52542. return this._isStarted;
  52543. },
  52544. enumerable: true,
  52545. configurable: true
  52546. });
  52547. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  52548. /**
  52549. * Gets or sets the speed ratio to use for all animations
  52550. */
  52551. get: function () {
  52552. return this._speedRatio;
  52553. },
  52554. /**
  52555. * Gets or sets the speed ratio to use for all animations
  52556. */
  52557. set: function (value) {
  52558. if (this._speedRatio === value) {
  52559. return;
  52560. }
  52561. this._speedRatio = value;
  52562. for (var index = 0; index < this._animatables.length; index++) {
  52563. var animatable = this._animatables[index];
  52564. animatable.speedRatio = this._speedRatio;
  52565. }
  52566. },
  52567. enumerable: true,
  52568. configurable: true
  52569. });
  52570. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  52571. /**
  52572. * Gets the targeted animations for this animation group
  52573. */
  52574. get: function () {
  52575. return this._targetedAnimations;
  52576. },
  52577. enumerable: true,
  52578. configurable: true
  52579. });
  52580. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  52581. /**
  52582. * returning the list of animatables controlled by this animation group.
  52583. */
  52584. get: function () {
  52585. return this._animatables;
  52586. },
  52587. enumerable: true,
  52588. configurable: true
  52589. });
  52590. /**
  52591. * Add an animation (with its target) in the group
  52592. * @param animation defines the animation we want to add
  52593. * @param target defines the target of the animation
  52594. * @returns the {BABYLON.TargetedAnimation} object
  52595. */
  52596. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  52597. var targetedAnimation = {
  52598. animation: animation,
  52599. target: target
  52600. };
  52601. var keys = animation.getKeys();
  52602. if (this._from > keys[0].frame) {
  52603. this._from = keys[0].frame;
  52604. }
  52605. if (this._to < keys[keys.length - 1].frame) {
  52606. this._to = keys[keys.length - 1].frame;
  52607. }
  52608. this._targetedAnimations.push(targetedAnimation);
  52609. return targetedAnimation;
  52610. };
  52611. /**
  52612. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  52613. * It can add constant keys at begin or end
  52614. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  52615. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  52616. * @returns the animation group
  52617. */
  52618. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  52619. if (beginFrame === void 0) { beginFrame = null; }
  52620. if (endFrame === void 0) { endFrame = null; }
  52621. if (beginFrame == null)
  52622. beginFrame = this._from;
  52623. if (endFrame == null)
  52624. endFrame = this._to;
  52625. for (var index = 0; index < this._targetedAnimations.length; index++) {
  52626. var targetedAnimation = this._targetedAnimations[index];
  52627. var keys = targetedAnimation.animation.getKeys();
  52628. var startKey = keys[0];
  52629. var endKey = keys[keys.length - 1];
  52630. if (startKey.frame > beginFrame) {
  52631. var newKey = {
  52632. frame: beginFrame,
  52633. value: startKey.value,
  52634. inTangent: startKey.inTangent,
  52635. outTangent: startKey.outTangent,
  52636. interpolation: startKey.interpolation
  52637. };
  52638. keys.splice(0, 0, newKey);
  52639. }
  52640. if (endKey.frame < endFrame) {
  52641. var newKey = {
  52642. frame: endFrame,
  52643. value: endKey.value,
  52644. inTangent: endKey.outTangent,
  52645. outTangent: endKey.outTangent,
  52646. interpolation: endKey.interpolation
  52647. };
  52648. keys.push(newKey);
  52649. }
  52650. }
  52651. this._from = beginFrame;
  52652. this._to = endFrame;
  52653. return this;
  52654. };
  52655. /**
  52656. * Start all animations on given targets
  52657. * @param loop defines if animations must loop
  52658. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  52659. * @param from defines the from key (optional)
  52660. * @param to defines the to key (optional)
  52661. * @returns the current animation group
  52662. */
  52663. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  52664. var _this = this;
  52665. if (loop === void 0) { loop = false; }
  52666. if (speedRatio === void 0) { speedRatio = 1; }
  52667. if (this._isStarted || this._targetedAnimations.length === 0) {
  52668. return this;
  52669. }
  52670. var _loop_1 = function (targetedAnimation) {
  52671. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  52672. animatable.onAnimationEnd = function () {
  52673. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  52674. _this._checkAnimationGroupEnded(animatable);
  52675. };
  52676. this_1._animatables.push(animatable);
  52677. };
  52678. var this_1 = this;
  52679. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  52680. var targetedAnimation = _a[_i];
  52681. _loop_1(targetedAnimation);
  52682. }
  52683. this._speedRatio = speedRatio;
  52684. this._isStarted = true;
  52685. return this;
  52686. };
  52687. /**
  52688. * Pause all animations
  52689. * @returns the animation group
  52690. */
  52691. AnimationGroup.prototype.pause = function () {
  52692. if (!this._isStarted) {
  52693. return this;
  52694. }
  52695. for (var index = 0; index < this._animatables.length; index++) {
  52696. var animatable = this._animatables[index];
  52697. animatable.pause();
  52698. }
  52699. this.onAnimationGroupPauseObservable.notifyObservers(this);
  52700. return this;
  52701. };
  52702. /**
  52703. * Play all animations to initial state
  52704. * This function will start() the animations if they were not started or will restart() them if they were paused
  52705. * @param loop defines if animations must loop
  52706. * @returns the animation group
  52707. */
  52708. AnimationGroup.prototype.play = function (loop) {
  52709. // only if all animatables are ready and exist
  52710. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  52711. if (loop !== undefined) {
  52712. for (var index = 0; index < this._animatables.length; index++) {
  52713. var animatable = this._animatables[index];
  52714. animatable.loopAnimation = loop;
  52715. }
  52716. }
  52717. this.restart();
  52718. }
  52719. else {
  52720. this.stop();
  52721. this.start(loop, this._speedRatio);
  52722. }
  52723. return this;
  52724. };
  52725. /**
  52726. * Reset all animations to initial state
  52727. * @returns the animation group
  52728. */
  52729. AnimationGroup.prototype.reset = function () {
  52730. if (!this._isStarted) {
  52731. return this;
  52732. }
  52733. for (var index = 0; index < this._animatables.length; index++) {
  52734. var animatable = this._animatables[index];
  52735. animatable.reset();
  52736. }
  52737. return this;
  52738. };
  52739. /**
  52740. * Restart animations from key 0
  52741. * @returns the animation group
  52742. */
  52743. AnimationGroup.prototype.restart = function () {
  52744. if (!this._isStarted) {
  52745. return this;
  52746. }
  52747. for (var index = 0; index < this._animatables.length; index++) {
  52748. var animatable = this._animatables[index];
  52749. animatable.restart();
  52750. }
  52751. return this;
  52752. };
  52753. /**
  52754. * Stop all animations
  52755. * @returns the animation group
  52756. */
  52757. AnimationGroup.prototype.stop = function () {
  52758. if (!this._isStarted) {
  52759. return this;
  52760. }
  52761. var list = this._animatables.slice();
  52762. for (var index = 0; index < list.length; index++) {
  52763. list[index].stop();
  52764. }
  52765. this._isStarted = false;
  52766. return this;
  52767. };
  52768. /**
  52769. * Set animation weight for all animatables
  52770. * @param weight defines the weight to use
  52771. * @return the animationGroup
  52772. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52773. */
  52774. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  52775. for (var index = 0; index < this._animatables.length; index++) {
  52776. var animatable = this._animatables[index];
  52777. animatable.weight = weight;
  52778. }
  52779. return this;
  52780. };
  52781. /**
  52782. * Synchronize and normalize all animatables with a source animatable
  52783. * @param root defines the root animatable to synchronize with
  52784. * @return the animationGroup
  52785. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  52786. */
  52787. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  52788. for (var index = 0; index < this._animatables.length; index++) {
  52789. var animatable = this._animatables[index];
  52790. animatable.syncWith(root);
  52791. }
  52792. return this;
  52793. };
  52794. /**
  52795. * Goes to a specific frame in this animation group
  52796. * @param frame the frame number to go to
  52797. * @return the animationGroup
  52798. */
  52799. AnimationGroup.prototype.goToFrame = function (frame) {
  52800. if (!this._isStarted) {
  52801. return this;
  52802. }
  52803. for (var index = 0; index < this._animatables.length; index++) {
  52804. var animatable = this._animatables[index];
  52805. animatable.goToFrame(frame);
  52806. }
  52807. return this;
  52808. };
  52809. /**
  52810. * Dispose all associated resources
  52811. */
  52812. AnimationGroup.prototype.dispose = function () {
  52813. this._targetedAnimations = [];
  52814. this._animatables = [];
  52815. var index = this._scene.animationGroups.indexOf(this);
  52816. if (index > -1) {
  52817. this._scene.animationGroups.splice(index, 1);
  52818. }
  52819. };
  52820. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  52821. // animatable should be taken out of the array
  52822. var idx = this._animatables.indexOf(animatable);
  52823. if (idx > -1) {
  52824. this._animatables.splice(idx, 1);
  52825. }
  52826. // all animatables were removed? animation group ended!
  52827. if (this._animatables.length === 0) {
  52828. this._isStarted = false;
  52829. this.onAnimationGroupEndObservable.notifyObservers(this);
  52830. }
  52831. };
  52832. // Statics
  52833. /**
  52834. * Returns a new AnimationGroup object parsed from the source provided.
  52835. * @param parsedAnimationGroup defines the source
  52836. * @param scene defines the scene that will receive the animationGroup
  52837. * @returns a new AnimationGroup
  52838. */
  52839. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  52840. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  52841. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  52842. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  52843. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  52844. var id = targetedAnimation.targetId;
  52845. var targetNode = scene.getNodeByID(id);
  52846. if (targetNode != null)
  52847. animationGroup.addTargetedAnimation(animation, targetNode);
  52848. }
  52849. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  52850. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  52851. return animationGroup;
  52852. };
  52853. /**
  52854. * Returns the string "AnimationGroup"
  52855. * @returns "AnimationGroup"
  52856. */
  52857. AnimationGroup.prototype.getClassName = function () {
  52858. return "AnimationGroup";
  52859. };
  52860. /**
  52861. * Creates a detailled string about the object
  52862. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  52863. * @returns a string representing the object
  52864. */
  52865. AnimationGroup.prototype.toString = function (fullDetails) {
  52866. var ret = "Name: " + this.name;
  52867. ret += ", type: " + this.getClassName();
  52868. if (fullDetails) {
  52869. ret += ", from: " + this._from;
  52870. ret += ", to: " + this._to;
  52871. ret += ", isStarted: " + this._isStarted;
  52872. ret += ", speedRatio: " + this._speedRatio;
  52873. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  52874. ret += ", animatables length: " + this._animatables;
  52875. }
  52876. return ret;
  52877. };
  52878. return AnimationGroup;
  52879. }());
  52880. BABYLON.AnimationGroup = AnimationGroup;
  52881. })(BABYLON || (BABYLON = {}));
  52882. //# sourceMappingURL=babylon.animationGroup.js.map
  52883. var BABYLON;
  52884. (function (BABYLON) {
  52885. // Static values to help the garbage collector
  52886. // Quaternion
  52887. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  52888. // Vector3
  52889. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  52890. // Vector2
  52891. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  52892. // Size
  52893. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  52894. // Color3
  52895. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  52896. /**
  52897. * Defines a runtime animation
  52898. */
  52899. var RuntimeAnimation = /** @class */ (function () {
  52900. /**
  52901. * Create a new RuntimeAnimation object
  52902. * @param target defines the target of the animation
  52903. * @param animation defines the source animation object
  52904. * @param scene defines the hosting scene
  52905. * @param host defines the initiating Animatable
  52906. */
  52907. function RuntimeAnimation(target, animation, scene, host) {
  52908. var _this = this;
  52909. this._events = new Array();
  52910. /**
  52911. * The current frame of the runtime animation
  52912. */
  52913. this._currentFrame = 0;
  52914. /**
  52915. * The original value of the runtime animation
  52916. */
  52917. this._originalValue = new Array();
  52918. /**
  52919. * The offsets cache of the runtime animation
  52920. */
  52921. this._offsetsCache = {};
  52922. /**
  52923. * The high limits cache of the runtime animation
  52924. */
  52925. this._highLimitsCache = {};
  52926. /**
  52927. * Specifies if the runtime animation has been stopped
  52928. */
  52929. this._stopped = false;
  52930. /**
  52931. * The blending factor of the runtime animation
  52932. */
  52933. this._blendingFactor = 0;
  52934. /**
  52935. * The target path of the runtime animation
  52936. */
  52937. this._targetPath = "";
  52938. /**
  52939. * The weight of the runtime animation
  52940. */
  52941. this._weight = 1.0;
  52942. /**
  52943. * The ratio offset of the runtime animation
  52944. */
  52945. this._ratioOffset = 0;
  52946. /**
  52947. * The previous delay of the runtime animation
  52948. */
  52949. this._previousDelay = 0;
  52950. /**
  52951. * The previous ratio of the runtime animation
  52952. */
  52953. this._previousRatio = 0;
  52954. this._animation = animation;
  52955. this._target = target;
  52956. this._scene = scene;
  52957. this._host = host;
  52958. animation._runtimeAnimations.push(this);
  52959. // Cloning events locally
  52960. var events = animation.getEvents();
  52961. if (events && events.length > 0) {
  52962. events.forEach(function (e) {
  52963. _this._events.push(e._clone());
  52964. });
  52965. }
  52966. }
  52967. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  52968. /**
  52969. * Gets the current frame of the runtime animation
  52970. */
  52971. get: function () {
  52972. return this._currentFrame;
  52973. },
  52974. enumerable: true,
  52975. configurable: true
  52976. });
  52977. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  52978. /**
  52979. * Gets the weight of the runtime animation
  52980. */
  52981. get: function () {
  52982. return this._weight;
  52983. },
  52984. enumerable: true,
  52985. configurable: true
  52986. });
  52987. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  52988. /**
  52989. * Gets the current value of the runtime animation
  52990. */
  52991. get: function () {
  52992. return this._currentValue;
  52993. },
  52994. enumerable: true,
  52995. configurable: true
  52996. });
  52997. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  52998. /**
  52999. * Gets the target path of the runtime animation
  53000. */
  53001. get: function () {
  53002. return this._targetPath;
  53003. },
  53004. enumerable: true,
  53005. configurable: true
  53006. });
  53007. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  53008. /**
  53009. * Gets the actual target of the runtime animation
  53010. */
  53011. get: function () {
  53012. return this._activeTarget;
  53013. },
  53014. enumerable: true,
  53015. configurable: true
  53016. });
  53017. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  53018. /**
  53019. * Gets the animation from the runtime animation
  53020. */
  53021. get: function () {
  53022. return this._animation;
  53023. },
  53024. enumerable: true,
  53025. configurable: true
  53026. });
  53027. /**
  53028. * Resets the runtime animation to the beginning
  53029. * @param restoreOriginal defines whether to restore the target property to the original value
  53030. */
  53031. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  53032. if (restoreOriginal === void 0) { restoreOriginal = false; }
  53033. if (restoreOriginal) {
  53034. if (this._target instanceof Array) {
  53035. var index = 0;
  53036. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  53037. var target = _a[_i];
  53038. if (this._originalValue[index] !== undefined) {
  53039. this._setValue(target, this._originalValue[index], -1);
  53040. }
  53041. index++;
  53042. }
  53043. }
  53044. else {
  53045. if (this._originalValue[0] !== undefined) {
  53046. this._setValue(this._target, this._originalValue[0], -1);
  53047. }
  53048. }
  53049. }
  53050. this._offsetsCache = {};
  53051. this._highLimitsCache = {};
  53052. this._currentFrame = 0;
  53053. this._blendingFactor = 0;
  53054. this._originalValue = new Array();
  53055. // Events
  53056. for (var index = 0; index < this._events.length; index++) {
  53057. this._events[index].isDone = false;
  53058. }
  53059. };
  53060. /**
  53061. * Specifies if the runtime animation is stopped
  53062. * @returns Boolean specifying if the runtime animation is stopped
  53063. */
  53064. RuntimeAnimation.prototype.isStopped = function () {
  53065. return this._stopped;
  53066. };
  53067. /**
  53068. * Disposes of the runtime animation
  53069. */
  53070. RuntimeAnimation.prototype.dispose = function () {
  53071. var index = this._animation.runtimeAnimations.indexOf(this);
  53072. if (index > -1) {
  53073. this._animation.runtimeAnimations.splice(index, 1);
  53074. }
  53075. };
  53076. /**
  53077. * Interpolates the animation from the current frame
  53078. * @param currentFrame The frame to interpolate the animation to
  53079. * @param repeatCount The number of times that the animation should loop
  53080. * @param loopMode The type of looping mode to use
  53081. * @param offsetValue Animation offset value
  53082. * @param highLimitValue The high limit value
  53083. * @returns The interpolated value
  53084. */
  53085. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  53086. this._currentFrame = currentFrame;
  53087. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  53088. this._workValue = BABYLON.Matrix.Zero();
  53089. }
  53090. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  53091. };
  53092. /**
  53093. * Apply the interpolated value to the target
  53094. * @param currentValue defines the value computed by the animation
  53095. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  53096. */
  53097. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  53098. if (weight === void 0) { weight = 1.0; }
  53099. if (this._target instanceof Array) {
  53100. var index = 0;
  53101. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  53102. var target = _a[_i];
  53103. this._setValue(target, currentValue, weight, index);
  53104. index++;
  53105. }
  53106. }
  53107. else {
  53108. this._setValue(this._target, currentValue, weight);
  53109. }
  53110. };
  53111. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  53112. if (targetIndex === void 0) { targetIndex = 0; }
  53113. // Set value
  53114. var path;
  53115. var destination;
  53116. var targetPropertyPath = this._animation.targetPropertyPath;
  53117. if (targetPropertyPath.length > 1) {
  53118. var property = target[targetPropertyPath[0]];
  53119. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  53120. property = property[targetPropertyPath[index]];
  53121. }
  53122. path = targetPropertyPath[targetPropertyPath.length - 1];
  53123. destination = property;
  53124. }
  53125. else {
  53126. path = targetPropertyPath[0];
  53127. destination = target;
  53128. }
  53129. this._targetPath = path;
  53130. this._activeTarget = destination;
  53131. this._weight = weight;
  53132. if (this._originalValue[targetIndex] === undefined) {
  53133. var originalValue = void 0;
  53134. if (destination.getRestPose && path === "_matrix") { // For bones
  53135. originalValue = destination.getRestPose();
  53136. }
  53137. else {
  53138. originalValue = destination[path];
  53139. }
  53140. if (originalValue && originalValue.clone) {
  53141. this._originalValue[targetIndex] = originalValue.clone();
  53142. }
  53143. else {
  53144. this._originalValue[targetIndex] = originalValue;
  53145. }
  53146. }
  53147. // Blending
  53148. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  53149. if (enableBlending && this._blendingFactor <= 1.0) {
  53150. if (!this._originalBlendValue) {
  53151. var originalValue = destination[path];
  53152. if (originalValue.clone) {
  53153. this._originalBlendValue = originalValue.clone();
  53154. }
  53155. else {
  53156. this._originalBlendValue = originalValue;
  53157. }
  53158. }
  53159. if (this._originalBlendValue.m) { // Matrix
  53160. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  53161. if (this._currentValue) {
  53162. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  53163. }
  53164. else {
  53165. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53166. }
  53167. }
  53168. else {
  53169. if (this._currentValue) {
  53170. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  53171. }
  53172. else {
  53173. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53174. }
  53175. }
  53176. }
  53177. else {
  53178. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53179. }
  53180. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  53181. this._blendingFactor += blendingSpeed;
  53182. }
  53183. else {
  53184. this._currentValue = currentValue;
  53185. }
  53186. if (weight !== -1.0) {
  53187. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  53188. }
  53189. else {
  53190. destination[path] = this._currentValue;
  53191. }
  53192. if (target.markAsDirty) {
  53193. target.markAsDirty(this._animation.targetProperty);
  53194. }
  53195. };
  53196. /**
  53197. * Gets the loop pmode of the runtime animation
  53198. * @returns Loop Mode
  53199. */
  53200. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  53201. if (this._target && this._target.animationPropertiesOverride) {
  53202. return this._target.animationPropertiesOverride.loopMode;
  53203. }
  53204. return this._animation.loopMode;
  53205. };
  53206. /**
  53207. * Move the current animation to a given frame
  53208. * @param frame defines the frame to move to
  53209. */
  53210. RuntimeAnimation.prototype.goToFrame = function (frame) {
  53211. var keys = this._animation.getKeys();
  53212. if (frame < keys[0].frame) {
  53213. frame = keys[0].frame;
  53214. }
  53215. else if (frame > keys[keys.length - 1].frame) {
  53216. frame = keys[keys.length - 1].frame;
  53217. }
  53218. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  53219. this.setValue(currentValue, -1);
  53220. };
  53221. /**
  53222. * @hidden Internal use only
  53223. */
  53224. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  53225. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  53226. this._ratioOffset = this._previousRatio - newRatio;
  53227. };
  53228. /**
  53229. * Execute the current animation
  53230. * @param delay defines the delay to add to the current frame
  53231. * @param from defines the lower bound of the animation range
  53232. * @param to defines the upper bound of the animation range
  53233. * @param loop defines if the current animation must loop
  53234. * @param speedRatio defines the current speed ratio
  53235. * @param weight defines the weight of the animation (default is -1 so no weight)
  53236. * @returns a boolean indicating if the animation is running
  53237. */
  53238. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  53239. if (weight === void 0) { weight = -1.0; }
  53240. var targetPropertyPath = this._animation.targetPropertyPath;
  53241. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  53242. this._stopped = true;
  53243. return false;
  53244. }
  53245. var returnValue = true;
  53246. var keys = this._animation.getKeys();
  53247. // Adding a start key at frame 0 if missing
  53248. if (keys[0].frame !== 0) {
  53249. var newKey = { frame: 0, value: keys[0].value };
  53250. keys.splice(0, 0, newKey);
  53251. }
  53252. // Adding a duplicate key when there is only one key at frame zero
  53253. else if (keys.length === 1) {
  53254. var newKey = { frame: 0.001, value: keys[0].value };
  53255. keys.push(newKey);
  53256. }
  53257. // Check limits
  53258. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  53259. from = keys[0].frame;
  53260. }
  53261. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  53262. to = keys[keys.length - 1].frame;
  53263. }
  53264. //to and from cannot be the same key
  53265. if (from === to) {
  53266. if (from > keys[0].frame) {
  53267. from--;
  53268. }
  53269. else if (to < keys[keys.length - 1].frame) {
  53270. to++;
  53271. }
  53272. }
  53273. // Compute ratio
  53274. var range = to - from;
  53275. var offsetValue;
  53276. // ratio represents the frame delta between from and to
  53277. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  53278. var highLimitValue = 0;
  53279. this._previousDelay = delay;
  53280. this._previousRatio = ratio;
  53281. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  53282. returnValue = false;
  53283. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  53284. }
  53285. else {
  53286. // Get max value if required
  53287. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  53288. var keyOffset = to.toString() + from.toString();
  53289. if (!this._offsetsCache[keyOffset]) {
  53290. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53291. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53292. switch (this._animation.dataType) {
  53293. // Float
  53294. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53295. this._offsetsCache[keyOffset] = toValue - fromValue;
  53296. break;
  53297. // Quaternion
  53298. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53299. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53300. break;
  53301. // Vector3
  53302. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53303. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53304. // Vector2
  53305. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53306. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53307. // Size
  53308. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53309. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53310. // Color3
  53311. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53312. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53313. default:
  53314. break;
  53315. }
  53316. this._highLimitsCache[keyOffset] = toValue;
  53317. }
  53318. highLimitValue = this._highLimitsCache[keyOffset];
  53319. offsetValue = this._offsetsCache[keyOffset];
  53320. }
  53321. }
  53322. if (offsetValue === undefined) {
  53323. switch (this._animation.dataType) {
  53324. // Float
  53325. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53326. offsetValue = 0;
  53327. break;
  53328. // Quaternion
  53329. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53330. offsetValue = _staticOffsetValueQuaternion;
  53331. break;
  53332. // Vector3
  53333. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53334. offsetValue = _staticOffsetValueVector3;
  53335. break;
  53336. // Vector2
  53337. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53338. offsetValue = _staticOffsetValueVector2;
  53339. break;
  53340. // Size
  53341. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53342. offsetValue = _staticOffsetValueSize;
  53343. break;
  53344. // Color3
  53345. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53346. offsetValue = _staticOffsetValueColor3;
  53347. }
  53348. }
  53349. // Compute value
  53350. var repeatCount = (ratio / range) >> 0;
  53351. var currentFrame = returnValue ? from + ratio % range : to;
  53352. // Need to normalize?
  53353. if (this._host && this._host.syncRoot) {
  53354. var syncRoot = this._host.syncRoot;
  53355. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  53356. currentFrame = from + (to - from) * hostNormalizedFrame;
  53357. }
  53358. // Reset events if looping
  53359. var events = this._events;
  53360. if (range > 0 && this.currentFrame > currentFrame ||
  53361. range < 0 && this.currentFrame < currentFrame) {
  53362. // Need to reset animation events
  53363. for (var index = 0; index < events.length; index++) {
  53364. if (!events[index].onlyOnce) {
  53365. // reset event, the animation is looping
  53366. events[index].isDone = false;
  53367. }
  53368. }
  53369. }
  53370. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  53371. // Set value
  53372. this.setValue(currentValue, weight);
  53373. // Check events
  53374. for (var index = 0; index < events.length; index++) {
  53375. // Make sure current frame has passed event frame and that event frame is within the current range
  53376. // Also, handle both forward and reverse animations
  53377. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  53378. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  53379. var event = events[index];
  53380. if (!event.isDone) {
  53381. // If event should be done only once, remove it.
  53382. if (event.onlyOnce) {
  53383. events.splice(index, 1);
  53384. index--;
  53385. }
  53386. event.isDone = true;
  53387. event.action(currentFrame);
  53388. } // Don't do anything if the event has already be done.
  53389. }
  53390. }
  53391. if (!returnValue) {
  53392. this._stopped = true;
  53393. }
  53394. return returnValue;
  53395. };
  53396. return RuntimeAnimation;
  53397. }());
  53398. BABYLON.RuntimeAnimation = RuntimeAnimation;
  53399. })(BABYLON || (BABYLON = {}));
  53400. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  53401. var BABYLON;
  53402. (function (BABYLON) {
  53403. /**
  53404. * Class used to store an actual running animation
  53405. */
  53406. var Animatable = /** @class */ (function () {
  53407. /**
  53408. * Creates a new Animatable
  53409. * @param scene defines the hosting scene
  53410. * @param target defines the target object
  53411. * @param fromFrame defines the starting frame number (default is 0)
  53412. * @param toFrame defines the ending frame number (default is 100)
  53413. * @param loopAnimation defines if the animation must loop (default is false)
  53414. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  53415. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  53416. * @param animations defines a group of animation to add to the new Animatable
  53417. */
  53418. function Animatable(scene,
  53419. /** defines the target object */
  53420. target,
  53421. /** defines the starting frame number (default is 0) */
  53422. fromFrame,
  53423. /** defines the ending frame number (default is 100) */
  53424. toFrame,
  53425. /** defines if the animation must loop (default is false) */
  53426. loopAnimation, speedRatio,
  53427. /** defines a callback to call when animation ends if it is not looping */
  53428. onAnimationEnd, animations) {
  53429. if (fromFrame === void 0) { fromFrame = 0; }
  53430. if (toFrame === void 0) { toFrame = 100; }
  53431. if (loopAnimation === void 0) { loopAnimation = false; }
  53432. if (speedRatio === void 0) { speedRatio = 1.0; }
  53433. this.target = target;
  53434. this.fromFrame = fromFrame;
  53435. this.toFrame = toFrame;
  53436. this.loopAnimation = loopAnimation;
  53437. this.onAnimationEnd = onAnimationEnd;
  53438. this._localDelayOffset = null;
  53439. this._pausedDelay = null;
  53440. this._runtimeAnimations = new Array();
  53441. this._paused = false;
  53442. this._speedRatio = 1;
  53443. this._weight = -1.0;
  53444. /**
  53445. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  53446. * This will only apply for non looping animation (default is true)
  53447. */
  53448. this.disposeOnEnd = true;
  53449. /**
  53450. * Gets a boolean indicating if the animation has started
  53451. */
  53452. this.animationStarted = false;
  53453. /**
  53454. * Observer raised when the animation ends
  53455. */
  53456. this.onAnimationEndObservable = new BABYLON.Observable();
  53457. this._scene = scene;
  53458. if (animations) {
  53459. this.appendAnimations(target, animations);
  53460. }
  53461. this._speedRatio = speedRatio;
  53462. scene._activeAnimatables.push(this);
  53463. }
  53464. Object.defineProperty(Animatable.prototype, "syncRoot", {
  53465. /**
  53466. * Gets the root Animatable used to synchronize and normalize animations
  53467. */
  53468. get: function () {
  53469. return this._syncRoot;
  53470. },
  53471. enumerable: true,
  53472. configurable: true
  53473. });
  53474. Object.defineProperty(Animatable.prototype, "masterFrame", {
  53475. /**
  53476. * Gets the current frame of the first RuntimeAnimation
  53477. * Used to synchronize Animatables
  53478. */
  53479. get: function () {
  53480. if (this._runtimeAnimations.length === 0) {
  53481. return 0;
  53482. }
  53483. return this._runtimeAnimations[0].currentFrame;
  53484. },
  53485. enumerable: true,
  53486. configurable: true
  53487. });
  53488. Object.defineProperty(Animatable.prototype, "weight", {
  53489. /**
  53490. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  53491. */
  53492. get: function () {
  53493. return this._weight;
  53494. },
  53495. set: function (value) {
  53496. if (value === -1) { // -1 is ok and means no weight
  53497. this._weight = -1;
  53498. return;
  53499. }
  53500. // Else weight must be in [0, 1] range
  53501. this._weight = Math.min(Math.max(value, 0), 1.0);
  53502. },
  53503. enumerable: true,
  53504. configurable: true
  53505. });
  53506. Object.defineProperty(Animatable.prototype, "speedRatio", {
  53507. /**
  53508. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  53509. */
  53510. get: function () {
  53511. return this._speedRatio;
  53512. },
  53513. set: function (value) {
  53514. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  53515. var animation = this._runtimeAnimations[index];
  53516. animation._prepareForSpeedRatioChange(value);
  53517. }
  53518. this._speedRatio = value;
  53519. },
  53520. enumerable: true,
  53521. configurable: true
  53522. });
  53523. // Methods
  53524. /**
  53525. * Synchronize and normalize current Animatable with a source Animatable
  53526. * This is useful when using animation weights and when animations are not of the same length
  53527. * @param root defines the root Animatable to synchronize with
  53528. * @returns the current Animatable
  53529. */
  53530. Animatable.prototype.syncWith = function (root) {
  53531. this._syncRoot = root;
  53532. if (root) {
  53533. // Make sure this animatable will animate after the root
  53534. var index = this._scene._activeAnimatables.indexOf(this);
  53535. if (index > -1) {
  53536. this._scene._activeAnimatables.splice(index, 1);
  53537. this._scene._activeAnimatables.push(this);
  53538. }
  53539. }
  53540. return this;
  53541. };
  53542. /**
  53543. * Gets the list of runtime animations
  53544. * @returns an array of RuntimeAnimation
  53545. */
  53546. Animatable.prototype.getAnimations = function () {
  53547. return this._runtimeAnimations;
  53548. };
  53549. /**
  53550. * Adds more animations to the current animatable
  53551. * @param target defines the target of the animations
  53552. * @param animations defines the new animations to add
  53553. */
  53554. Animatable.prototype.appendAnimations = function (target, animations) {
  53555. for (var index = 0; index < animations.length; index++) {
  53556. var animation = animations[index];
  53557. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  53558. }
  53559. };
  53560. /**
  53561. * Gets the source animation for a specific property
  53562. * @param property defines the propertyu to look for
  53563. * @returns null or the source animation for the given property
  53564. */
  53565. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  53566. var runtimeAnimations = this._runtimeAnimations;
  53567. for (var index = 0; index < runtimeAnimations.length; index++) {
  53568. if (runtimeAnimations[index].animation.targetProperty === property) {
  53569. return runtimeAnimations[index].animation;
  53570. }
  53571. }
  53572. return null;
  53573. };
  53574. /**
  53575. * Gets the runtime animation for a specific property
  53576. * @param property defines the propertyu to look for
  53577. * @returns null or the runtime animation for the given property
  53578. */
  53579. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  53580. var runtimeAnimations = this._runtimeAnimations;
  53581. for (var index = 0; index < runtimeAnimations.length; index++) {
  53582. if (runtimeAnimations[index].animation.targetProperty === property) {
  53583. return runtimeAnimations[index];
  53584. }
  53585. }
  53586. return null;
  53587. };
  53588. /**
  53589. * Resets the animatable to its original state
  53590. */
  53591. Animatable.prototype.reset = function () {
  53592. var runtimeAnimations = this._runtimeAnimations;
  53593. for (var index = 0; index < runtimeAnimations.length; index++) {
  53594. runtimeAnimations[index].reset(true);
  53595. }
  53596. this._localDelayOffset = null;
  53597. this._pausedDelay = null;
  53598. };
  53599. /**
  53600. * Allows the animatable to blend with current running animations
  53601. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  53602. * @param blendingSpeed defines the blending speed to use
  53603. */
  53604. Animatable.prototype.enableBlending = function (blendingSpeed) {
  53605. var runtimeAnimations = this._runtimeAnimations;
  53606. for (var index = 0; index < runtimeAnimations.length; index++) {
  53607. runtimeAnimations[index].animation.enableBlending = true;
  53608. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  53609. }
  53610. };
  53611. /**
  53612. * Disable animation blending
  53613. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  53614. */
  53615. Animatable.prototype.disableBlending = function () {
  53616. var runtimeAnimations = this._runtimeAnimations;
  53617. for (var index = 0; index < runtimeAnimations.length; index++) {
  53618. runtimeAnimations[index].animation.enableBlending = false;
  53619. }
  53620. };
  53621. /**
  53622. * Jump directly to a given frame
  53623. * @param frame defines the frame to jump to
  53624. */
  53625. Animatable.prototype.goToFrame = function (frame) {
  53626. var runtimeAnimations = this._runtimeAnimations;
  53627. if (runtimeAnimations[0]) {
  53628. var fps = runtimeAnimations[0].animation.framePerSecond;
  53629. var currentFrame = runtimeAnimations[0].currentFrame;
  53630. var adjustTime = frame - currentFrame;
  53631. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  53632. if (this._localDelayOffset === null) {
  53633. this._localDelayOffset = 0;
  53634. }
  53635. this._localDelayOffset -= delay;
  53636. }
  53637. for (var index = 0; index < runtimeAnimations.length; index++) {
  53638. runtimeAnimations[index].goToFrame(frame);
  53639. }
  53640. };
  53641. /**
  53642. * Pause the animation
  53643. */
  53644. Animatable.prototype.pause = function () {
  53645. if (this._paused) {
  53646. return;
  53647. }
  53648. this._paused = true;
  53649. };
  53650. /**
  53651. * Restart the animation
  53652. */
  53653. Animatable.prototype.restart = function () {
  53654. this._paused = false;
  53655. };
  53656. Animatable.prototype._raiseOnAnimationEnd = function () {
  53657. if (this.onAnimationEnd) {
  53658. this.onAnimationEnd();
  53659. }
  53660. this.onAnimationEndObservable.notifyObservers(this);
  53661. };
  53662. /**
  53663. * Stop and delete the current animation
  53664. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  53665. * @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)
  53666. */
  53667. Animatable.prototype.stop = function (animationName, targetMask) {
  53668. if (animationName || targetMask) {
  53669. var idx = this._scene._activeAnimatables.indexOf(this);
  53670. if (idx > -1) {
  53671. var runtimeAnimations = this._runtimeAnimations;
  53672. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  53673. var runtimeAnimation = runtimeAnimations[index];
  53674. if (animationName && runtimeAnimation.animation.name != animationName) {
  53675. continue;
  53676. }
  53677. if (targetMask && !targetMask(runtimeAnimation.target)) {
  53678. continue;
  53679. }
  53680. runtimeAnimation.dispose();
  53681. runtimeAnimations.splice(index, 1);
  53682. }
  53683. if (runtimeAnimations.length == 0) {
  53684. this._scene._activeAnimatables.splice(idx, 1);
  53685. this._raiseOnAnimationEnd();
  53686. }
  53687. }
  53688. }
  53689. else {
  53690. var index = this._scene._activeAnimatables.indexOf(this);
  53691. if (index > -1) {
  53692. this._scene._activeAnimatables.splice(index, 1);
  53693. var runtimeAnimations = this._runtimeAnimations;
  53694. for (var index = 0; index < runtimeAnimations.length; index++) {
  53695. runtimeAnimations[index].dispose();
  53696. }
  53697. this._raiseOnAnimationEnd();
  53698. }
  53699. }
  53700. };
  53701. /**
  53702. * Wait asynchronously for the animation to end
  53703. * @returns a promise which will be fullfilled when the animation ends
  53704. */
  53705. Animatable.prototype.waitAsync = function () {
  53706. var _this = this;
  53707. return new Promise(function (resolve, reject) {
  53708. _this.onAnimationEndObservable.add(function () {
  53709. resolve(_this);
  53710. }, undefined, undefined, _this, true);
  53711. });
  53712. };
  53713. /** @hidden */
  53714. Animatable.prototype._animate = function (delay) {
  53715. if (this._paused) {
  53716. this.animationStarted = false;
  53717. if (this._pausedDelay === null) {
  53718. this._pausedDelay = delay;
  53719. }
  53720. return true;
  53721. }
  53722. if (this._localDelayOffset === null) {
  53723. this._localDelayOffset = delay;
  53724. this._pausedDelay = null;
  53725. }
  53726. else if (this._pausedDelay !== null) {
  53727. this._localDelayOffset += delay - this._pausedDelay;
  53728. this._pausedDelay = null;
  53729. }
  53730. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  53731. return true;
  53732. }
  53733. // Animating
  53734. var running = false;
  53735. var runtimeAnimations = this._runtimeAnimations;
  53736. var index;
  53737. for (index = 0; index < runtimeAnimations.length; index++) {
  53738. var animation = runtimeAnimations[index];
  53739. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  53740. running = running || isRunning;
  53741. }
  53742. this.animationStarted = running;
  53743. if (!running) {
  53744. if (this.disposeOnEnd) {
  53745. // Remove from active animatables
  53746. index = this._scene._activeAnimatables.indexOf(this);
  53747. this._scene._activeAnimatables.splice(index, 1);
  53748. // Dispose all runtime animations
  53749. for (index = 0; index < runtimeAnimations.length; index++) {
  53750. runtimeAnimations[index].dispose();
  53751. }
  53752. }
  53753. this._raiseOnAnimationEnd();
  53754. if (this.disposeOnEnd) {
  53755. this.onAnimationEnd = null;
  53756. this.onAnimationEndObservable.clear();
  53757. }
  53758. }
  53759. return running;
  53760. };
  53761. return Animatable;
  53762. }());
  53763. BABYLON.Animatable = Animatable;
  53764. })(BABYLON || (BABYLON = {}));
  53765. //# sourceMappingURL=babylon.animatable.js.map
  53766. var BABYLON;
  53767. (function (BABYLON) {
  53768. /**
  53769. * Base class used for every default easing function.
  53770. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53771. */
  53772. var EasingFunction = /** @class */ (function () {
  53773. function EasingFunction() {
  53774. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  53775. }
  53776. /**
  53777. * Sets the easing mode of the current function.
  53778. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  53779. */
  53780. EasingFunction.prototype.setEasingMode = function (easingMode) {
  53781. var n = Math.min(Math.max(easingMode, 0), 2);
  53782. this._easingMode = n;
  53783. };
  53784. /**
  53785. * Gets the current easing mode.
  53786. * @returns the easing mode
  53787. */
  53788. EasingFunction.prototype.getEasingMode = function () {
  53789. return this._easingMode;
  53790. };
  53791. /**
  53792. * @hidden
  53793. */
  53794. EasingFunction.prototype.easeInCore = function (gradient) {
  53795. throw new Error('You must implement this method');
  53796. };
  53797. /**
  53798. * Given an input gradient between 0 and 1, this returns the corrseponding value
  53799. * of the easing function.
  53800. * @param gradient Defines the value between 0 and 1 we want the easing value for
  53801. * @returns the corresponding value on the curve defined by the easing function
  53802. */
  53803. EasingFunction.prototype.ease = function (gradient) {
  53804. switch (this._easingMode) {
  53805. case EasingFunction.EASINGMODE_EASEIN:
  53806. return this.easeInCore(gradient);
  53807. case EasingFunction.EASINGMODE_EASEOUT:
  53808. return (1 - this.easeInCore(1 - gradient));
  53809. }
  53810. if (gradient >= 0.5) {
  53811. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  53812. }
  53813. return (this.easeInCore(gradient * 2) * 0.5);
  53814. };
  53815. /**
  53816. * Interpolation follows the mathematical formula associated with the easing function.
  53817. */
  53818. EasingFunction.EASINGMODE_EASEIN = 0;
  53819. /**
  53820. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  53821. */
  53822. EasingFunction.EASINGMODE_EASEOUT = 1;
  53823. /**
  53824. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  53825. */
  53826. EasingFunction.EASINGMODE_EASEINOUT = 2;
  53827. return EasingFunction;
  53828. }());
  53829. BABYLON.EasingFunction = EasingFunction;
  53830. /**
  53831. * Easing function with a circle shape (see link below).
  53832. * @see https://easings.net/#easeInCirc
  53833. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53834. */
  53835. var CircleEase = /** @class */ (function (_super) {
  53836. __extends(CircleEase, _super);
  53837. function CircleEase() {
  53838. return _super !== null && _super.apply(this, arguments) || this;
  53839. }
  53840. /** @hidden */
  53841. CircleEase.prototype.easeInCore = function (gradient) {
  53842. gradient = Math.max(0, Math.min(1, gradient));
  53843. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  53844. };
  53845. return CircleEase;
  53846. }(EasingFunction));
  53847. BABYLON.CircleEase = CircleEase;
  53848. /**
  53849. * Easing function with a ease back shape (see link below).
  53850. * @see https://easings.net/#easeInBack
  53851. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53852. */
  53853. var BackEase = /** @class */ (function (_super) {
  53854. __extends(BackEase, _super);
  53855. /**
  53856. * Instantiates a back ease easing
  53857. * @see https://easings.net/#easeInBack
  53858. * @param amplitude Defines the amplitude of the function
  53859. */
  53860. function BackEase(
  53861. /** Defines the amplitude of the function */
  53862. amplitude) {
  53863. if (amplitude === void 0) { amplitude = 1; }
  53864. var _this = _super.call(this) || this;
  53865. _this.amplitude = amplitude;
  53866. return _this;
  53867. }
  53868. /** @hidden */
  53869. BackEase.prototype.easeInCore = function (gradient) {
  53870. var num = Math.max(0, this.amplitude);
  53871. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  53872. };
  53873. return BackEase;
  53874. }(EasingFunction));
  53875. BABYLON.BackEase = BackEase;
  53876. /**
  53877. * Easing function with a bouncing shape (see link below).
  53878. * @see https://easings.net/#easeInBounce
  53879. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53880. */
  53881. var BounceEase = /** @class */ (function (_super) {
  53882. __extends(BounceEase, _super);
  53883. /**
  53884. * Instantiates a bounce easing
  53885. * @see https://easings.net/#easeInBounce
  53886. * @param bounces Defines the number of bounces
  53887. * @param bounciness Defines the amplitude of the bounce
  53888. */
  53889. function BounceEase(
  53890. /** Defines the number of bounces */
  53891. bounces,
  53892. /** Defines the amplitude of the bounce */
  53893. bounciness) {
  53894. if (bounces === void 0) { bounces = 3; }
  53895. if (bounciness === void 0) { bounciness = 2; }
  53896. var _this = _super.call(this) || this;
  53897. _this.bounces = bounces;
  53898. _this.bounciness = bounciness;
  53899. return _this;
  53900. }
  53901. /** @hidden */
  53902. BounceEase.prototype.easeInCore = function (gradient) {
  53903. var y = Math.max(0.0, this.bounces);
  53904. var bounciness = this.bounciness;
  53905. if (bounciness <= 1.0) {
  53906. bounciness = 1.001;
  53907. }
  53908. var num9 = Math.pow(bounciness, y);
  53909. var num5 = 1.0 - bounciness;
  53910. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  53911. var num15 = gradient * num4;
  53912. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  53913. var num3 = Math.floor(num65);
  53914. var num13 = num3 + 1.0;
  53915. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  53916. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  53917. var num7 = (num8 + num12) * 0.5;
  53918. var num6 = gradient - num7;
  53919. var num2 = num7 - num8;
  53920. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  53921. };
  53922. return BounceEase;
  53923. }(EasingFunction));
  53924. BABYLON.BounceEase = BounceEase;
  53925. /**
  53926. * Easing function with a power of 3 shape (see link below).
  53927. * @see https://easings.net/#easeInCubic
  53928. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53929. */
  53930. var CubicEase = /** @class */ (function (_super) {
  53931. __extends(CubicEase, _super);
  53932. function CubicEase() {
  53933. return _super !== null && _super.apply(this, arguments) || this;
  53934. }
  53935. /** @hidden */
  53936. CubicEase.prototype.easeInCore = function (gradient) {
  53937. return (gradient * gradient * gradient);
  53938. };
  53939. return CubicEase;
  53940. }(EasingFunction));
  53941. BABYLON.CubicEase = CubicEase;
  53942. /**
  53943. * Easing function with an elastic shape (see link below).
  53944. * @see https://easings.net/#easeInElastic
  53945. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53946. */
  53947. var ElasticEase = /** @class */ (function (_super) {
  53948. __extends(ElasticEase, _super);
  53949. /**
  53950. * Instantiates an elastic easing function
  53951. * @see https://easings.net/#easeInElastic
  53952. * @param oscillations Defines the number of oscillations
  53953. * @param springiness Defines the amplitude of the oscillations
  53954. */
  53955. function ElasticEase(
  53956. /** Defines the number of oscillations*/
  53957. oscillations,
  53958. /** Defines the amplitude of the oscillations*/
  53959. springiness) {
  53960. if (oscillations === void 0) { oscillations = 3; }
  53961. if (springiness === void 0) { springiness = 3; }
  53962. var _this = _super.call(this) || this;
  53963. _this.oscillations = oscillations;
  53964. _this.springiness = springiness;
  53965. return _this;
  53966. }
  53967. /** @hidden */
  53968. ElasticEase.prototype.easeInCore = function (gradient) {
  53969. var num2;
  53970. var num3 = Math.max(0.0, this.oscillations);
  53971. var num = Math.max(0.0, this.springiness);
  53972. if (num == 0) {
  53973. num2 = gradient;
  53974. }
  53975. else {
  53976. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  53977. }
  53978. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  53979. };
  53980. return ElasticEase;
  53981. }(EasingFunction));
  53982. BABYLON.ElasticEase = ElasticEase;
  53983. /**
  53984. * Easing function with an exponential shape (see link below).
  53985. * @see https://easings.net/#easeInExpo
  53986. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  53987. */
  53988. var ExponentialEase = /** @class */ (function (_super) {
  53989. __extends(ExponentialEase, _super);
  53990. /**
  53991. * Instantiates an exponential easing function
  53992. * @see https://easings.net/#easeInExpo
  53993. * @param exponent Defines the exponent of the function
  53994. */
  53995. function ExponentialEase(
  53996. /** Defines the exponent of the function */
  53997. exponent) {
  53998. if (exponent === void 0) { exponent = 2; }
  53999. var _this = _super.call(this) || this;
  54000. _this.exponent = exponent;
  54001. return _this;
  54002. }
  54003. /** @hidden */
  54004. ExponentialEase.prototype.easeInCore = function (gradient) {
  54005. if (this.exponent <= 0) {
  54006. return gradient;
  54007. }
  54008. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  54009. };
  54010. return ExponentialEase;
  54011. }(EasingFunction));
  54012. BABYLON.ExponentialEase = ExponentialEase;
  54013. /**
  54014. * Easing function with a power shape (see link below).
  54015. * @see https://easings.net/#easeInQuad
  54016. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54017. */
  54018. var PowerEase = /** @class */ (function (_super) {
  54019. __extends(PowerEase, _super);
  54020. /**
  54021. * Instantiates an power base easing function
  54022. * @see https://easings.net/#easeInQuad
  54023. * @param power Defines the power of the function
  54024. */
  54025. function PowerEase(
  54026. /** Defines the power of the function */
  54027. power) {
  54028. if (power === void 0) { power = 2; }
  54029. var _this = _super.call(this) || this;
  54030. _this.power = power;
  54031. return _this;
  54032. }
  54033. /** @hidden */
  54034. PowerEase.prototype.easeInCore = function (gradient) {
  54035. var y = Math.max(0.0, this.power);
  54036. return Math.pow(gradient, y);
  54037. };
  54038. return PowerEase;
  54039. }(EasingFunction));
  54040. BABYLON.PowerEase = PowerEase;
  54041. /**
  54042. * Easing function with a power of 2 shape (see link below).
  54043. * @see https://easings.net/#easeInQuad
  54044. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54045. */
  54046. var QuadraticEase = /** @class */ (function (_super) {
  54047. __extends(QuadraticEase, _super);
  54048. function QuadraticEase() {
  54049. return _super !== null && _super.apply(this, arguments) || this;
  54050. }
  54051. /** @hidden */
  54052. QuadraticEase.prototype.easeInCore = function (gradient) {
  54053. return (gradient * gradient);
  54054. };
  54055. return QuadraticEase;
  54056. }(EasingFunction));
  54057. BABYLON.QuadraticEase = QuadraticEase;
  54058. /**
  54059. * Easing function with a power of 4 shape (see link below).
  54060. * @see https://easings.net/#easeInQuart
  54061. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54062. */
  54063. var QuarticEase = /** @class */ (function (_super) {
  54064. __extends(QuarticEase, _super);
  54065. function QuarticEase() {
  54066. return _super !== null && _super.apply(this, arguments) || this;
  54067. }
  54068. /** @hidden */
  54069. QuarticEase.prototype.easeInCore = function (gradient) {
  54070. return (gradient * gradient * gradient * gradient);
  54071. };
  54072. return QuarticEase;
  54073. }(EasingFunction));
  54074. BABYLON.QuarticEase = QuarticEase;
  54075. /**
  54076. * Easing function with a power of 5 shape (see link below).
  54077. * @see https://easings.net/#easeInQuint
  54078. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54079. */
  54080. var QuinticEase = /** @class */ (function (_super) {
  54081. __extends(QuinticEase, _super);
  54082. function QuinticEase() {
  54083. return _super !== null && _super.apply(this, arguments) || this;
  54084. }
  54085. /** @hidden */
  54086. QuinticEase.prototype.easeInCore = function (gradient) {
  54087. return (gradient * gradient * gradient * gradient * gradient);
  54088. };
  54089. return QuinticEase;
  54090. }(EasingFunction));
  54091. BABYLON.QuinticEase = QuinticEase;
  54092. /**
  54093. * Easing function with a sin shape (see link below).
  54094. * @see https://easings.net/#easeInSine
  54095. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54096. */
  54097. var SineEase = /** @class */ (function (_super) {
  54098. __extends(SineEase, _super);
  54099. function SineEase() {
  54100. return _super !== null && _super.apply(this, arguments) || this;
  54101. }
  54102. /** @hidden */
  54103. SineEase.prototype.easeInCore = function (gradient) {
  54104. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  54105. };
  54106. return SineEase;
  54107. }(EasingFunction));
  54108. BABYLON.SineEase = SineEase;
  54109. /**
  54110. * Easing function with a bezier shape (see link below).
  54111. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  54112. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54113. */
  54114. var BezierCurveEase = /** @class */ (function (_super) {
  54115. __extends(BezierCurveEase, _super);
  54116. /**
  54117. * Instantiates a bezier function
  54118. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  54119. * @param x1 Defines the x component of the start tangent in the bezier curve
  54120. * @param y1 Defines the y component of the start tangent in the bezier curve
  54121. * @param x2 Defines the x component of the end tangent in the bezier curve
  54122. * @param y2 Defines the y component of the end tangent in the bezier curve
  54123. */
  54124. function BezierCurveEase(
  54125. /** Defines the x component of the start tangent in the bezier curve */
  54126. x1,
  54127. /** Defines the y component of the start tangent in the bezier curve */
  54128. y1,
  54129. /** Defines the x component of the end tangent in the bezier curve */
  54130. x2,
  54131. /** Defines the y component of the end tangent in the bezier curve */
  54132. y2) {
  54133. if (x1 === void 0) { x1 = 0; }
  54134. if (y1 === void 0) { y1 = 0; }
  54135. if (x2 === void 0) { x2 = 1; }
  54136. if (y2 === void 0) { y2 = 1; }
  54137. var _this = _super.call(this) || this;
  54138. _this.x1 = x1;
  54139. _this.y1 = y1;
  54140. _this.x2 = x2;
  54141. _this.y2 = y2;
  54142. return _this;
  54143. }
  54144. /** @hidden */
  54145. BezierCurveEase.prototype.easeInCore = function (gradient) {
  54146. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  54147. };
  54148. return BezierCurveEase;
  54149. }(EasingFunction));
  54150. BABYLON.BezierCurveEase = BezierCurveEase;
  54151. })(BABYLON || (BABYLON = {}));
  54152. //# sourceMappingURL=babylon.easing.js.map
  54153. var BABYLON;
  54154. (function (BABYLON) {
  54155. /**
  54156. * A Condition applied to an Action
  54157. */
  54158. var Condition = /** @class */ (function () {
  54159. /**
  54160. * Creates a new Condition
  54161. * @param actionManager the manager of the action the condition is applied to
  54162. */
  54163. function Condition(actionManager) {
  54164. this._actionManager = actionManager;
  54165. }
  54166. /**
  54167. * Check if the current condition is valid
  54168. * @returns a boolean
  54169. */
  54170. Condition.prototype.isValid = function () {
  54171. return true;
  54172. };
  54173. /**
  54174. * Internal only
  54175. * @hidden
  54176. */
  54177. Condition.prototype._getProperty = function (propertyPath) {
  54178. return this._actionManager._getProperty(propertyPath);
  54179. };
  54180. /**
  54181. * Internal only
  54182. * @hidden
  54183. */
  54184. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  54185. return this._actionManager._getEffectiveTarget(target, propertyPath);
  54186. };
  54187. /**
  54188. * Serialize placeholder for child classes
  54189. * @returns the serialized object
  54190. */
  54191. Condition.prototype.serialize = function () {
  54192. };
  54193. /**
  54194. * Internal only
  54195. * @hidden
  54196. */
  54197. Condition.prototype._serialize = function (serializedCondition) {
  54198. return {
  54199. type: 2,
  54200. children: [],
  54201. name: serializedCondition.name,
  54202. properties: serializedCondition.properties
  54203. };
  54204. };
  54205. return Condition;
  54206. }());
  54207. BABYLON.Condition = Condition;
  54208. /**
  54209. * Defines specific conditional operators as extensions of Condition
  54210. */
  54211. var ValueCondition = /** @class */ (function (_super) {
  54212. __extends(ValueCondition, _super);
  54213. /**
  54214. * Creates a new ValueCondition
  54215. * @param actionManager manager for the action the condition applies to
  54216. * @param target for the action
  54217. * @param propertyPath path to specify the property of the target the conditional operator uses
  54218. * @param value the value compared by the conditional operator against the current value of the property
  54219. * @param operator the conditional operator, default ValueCondition.IsEqual
  54220. */
  54221. function ValueCondition(actionManager, target,
  54222. /** path to specify the property of the target the conditional operator uses */
  54223. propertyPath,
  54224. /** the value compared by the conditional operator against the current value of the property */
  54225. value,
  54226. /** the conditional operator, default ValueCondition.IsEqual */
  54227. operator) {
  54228. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  54229. var _this = _super.call(this, actionManager) || this;
  54230. _this.propertyPath = propertyPath;
  54231. _this.value = value;
  54232. _this.operator = operator;
  54233. _this._target = target;
  54234. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  54235. _this._property = _this._getProperty(_this.propertyPath);
  54236. return _this;
  54237. }
  54238. Object.defineProperty(ValueCondition, "IsEqual", {
  54239. /**
  54240. * returns the number for IsEqual
  54241. */
  54242. get: function () {
  54243. return ValueCondition._IsEqual;
  54244. },
  54245. enumerable: true,
  54246. configurable: true
  54247. });
  54248. Object.defineProperty(ValueCondition, "IsDifferent", {
  54249. /**
  54250. * Returns the number for IsDifferent
  54251. */
  54252. get: function () {
  54253. return ValueCondition._IsDifferent;
  54254. },
  54255. enumerable: true,
  54256. configurable: true
  54257. });
  54258. Object.defineProperty(ValueCondition, "IsGreater", {
  54259. /**
  54260. * Returns the number for IsGreater
  54261. */
  54262. get: function () {
  54263. return ValueCondition._IsGreater;
  54264. },
  54265. enumerable: true,
  54266. configurable: true
  54267. });
  54268. Object.defineProperty(ValueCondition, "IsLesser", {
  54269. /**
  54270. * Returns the number for IsLesser
  54271. */
  54272. get: function () {
  54273. return ValueCondition._IsLesser;
  54274. },
  54275. enumerable: true,
  54276. configurable: true
  54277. });
  54278. /**
  54279. * Compares the given value with the property value for the specified conditional operator
  54280. * @returns the result of the comparison
  54281. */
  54282. ValueCondition.prototype.isValid = function () {
  54283. switch (this.operator) {
  54284. case ValueCondition.IsGreater:
  54285. return this._effectiveTarget[this._property] > this.value;
  54286. case ValueCondition.IsLesser:
  54287. return this._effectiveTarget[this._property] < this.value;
  54288. case ValueCondition.IsEqual:
  54289. case ValueCondition.IsDifferent:
  54290. var check;
  54291. if (this.value.equals) {
  54292. check = this.value.equals(this._effectiveTarget[this._property]);
  54293. }
  54294. else {
  54295. check = this.value === this._effectiveTarget[this._property];
  54296. }
  54297. return this.operator === ValueCondition.IsEqual ? check : !check;
  54298. }
  54299. return false;
  54300. };
  54301. /**
  54302. * Serialize the ValueCondition into a JSON compatible object
  54303. * @returns serialization object
  54304. */
  54305. ValueCondition.prototype.serialize = function () {
  54306. return this._serialize({
  54307. name: "ValueCondition",
  54308. properties: [
  54309. BABYLON.Action._GetTargetProperty(this._target),
  54310. { name: "propertyPath", value: this.propertyPath },
  54311. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54312. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  54313. ]
  54314. });
  54315. };
  54316. /**
  54317. * Gets the name of the conditional operator for the ValueCondition
  54318. * @param operator the conditional operator
  54319. * @returns the name
  54320. */
  54321. ValueCondition.GetOperatorName = function (operator) {
  54322. switch (operator) {
  54323. case ValueCondition._IsEqual: return "IsEqual";
  54324. case ValueCondition._IsDifferent: return "IsDifferent";
  54325. case ValueCondition._IsGreater: return "IsGreater";
  54326. case ValueCondition._IsLesser: return "IsLesser";
  54327. default: return "";
  54328. }
  54329. };
  54330. /**
  54331. * Internal only
  54332. * @hidden
  54333. */
  54334. ValueCondition._IsEqual = 0;
  54335. /**
  54336. * Internal only
  54337. * @hidden
  54338. */
  54339. ValueCondition._IsDifferent = 1;
  54340. /**
  54341. * Internal only
  54342. * @hidden
  54343. */
  54344. ValueCondition._IsGreater = 2;
  54345. /**
  54346. * Internal only
  54347. * @hidden
  54348. */
  54349. ValueCondition._IsLesser = 3;
  54350. return ValueCondition;
  54351. }(Condition));
  54352. BABYLON.ValueCondition = ValueCondition;
  54353. /**
  54354. * Defines a predicate condition as an extension of Condition
  54355. */
  54356. var PredicateCondition = /** @class */ (function (_super) {
  54357. __extends(PredicateCondition, _super);
  54358. /**
  54359. * Creates a new PredicateCondition
  54360. * @param actionManager manager for the action the condition applies to
  54361. * @param predicate defines the predicate function used to validate the condition
  54362. */
  54363. function PredicateCondition(actionManager,
  54364. /** defines the predicate function used to validate the condition */
  54365. predicate) {
  54366. var _this = _super.call(this, actionManager) || this;
  54367. _this.predicate = predicate;
  54368. return _this;
  54369. }
  54370. /**
  54371. * @returns the validity of the predicate condition
  54372. */
  54373. PredicateCondition.prototype.isValid = function () {
  54374. return this.predicate();
  54375. };
  54376. return PredicateCondition;
  54377. }(Condition));
  54378. BABYLON.PredicateCondition = PredicateCondition;
  54379. /**
  54380. * Defines a state condition as an extension of Condition
  54381. */
  54382. var StateCondition = /** @class */ (function (_super) {
  54383. __extends(StateCondition, _super);
  54384. /**
  54385. * Creates a new StateCondition
  54386. * @param actionManager manager for the action the condition applies to
  54387. * @param target of the condition
  54388. * @param value to compare with target state
  54389. */
  54390. function StateCondition(actionManager, target, value) {
  54391. var _this = _super.call(this, actionManager) || this;
  54392. _this.value = value;
  54393. _this._target = target;
  54394. return _this;
  54395. }
  54396. /**
  54397. * @returns the validity of the state
  54398. */
  54399. StateCondition.prototype.isValid = function () {
  54400. return this._target.state === this.value;
  54401. };
  54402. /**
  54403. * Serialize the StateCondition into a JSON compatible object
  54404. * @returns serialization object
  54405. */
  54406. StateCondition.prototype.serialize = function () {
  54407. return this._serialize({
  54408. name: "StateCondition",
  54409. properties: [
  54410. BABYLON.Action._GetTargetProperty(this._target),
  54411. { name: "value", value: this.value }
  54412. ]
  54413. });
  54414. };
  54415. return StateCondition;
  54416. }(Condition));
  54417. BABYLON.StateCondition = StateCondition;
  54418. })(BABYLON || (BABYLON = {}));
  54419. //# sourceMappingURL=babylon.condition.js.map
  54420. var BABYLON;
  54421. (function (BABYLON) {
  54422. /**
  54423. * The action to be carried out following a trigger
  54424. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  54425. */
  54426. var Action = /** @class */ (function () {
  54427. /**
  54428. * Creates a new Action
  54429. * @param triggerOptions the trigger, with or without parameters, for the action
  54430. * @param condition an optional determinant of action
  54431. */
  54432. function Action(
  54433. /** the trigger, with or without parameters, for the action */
  54434. triggerOptions, condition) {
  54435. this.triggerOptions = triggerOptions;
  54436. /**
  54437. * An event triggered prior to action being executed.
  54438. */
  54439. this.onBeforeExecuteObservable = new BABYLON.Observable();
  54440. if (triggerOptions.parameter) {
  54441. this.trigger = triggerOptions.trigger;
  54442. this._triggerParameter = triggerOptions.parameter;
  54443. }
  54444. else if (triggerOptions.trigger) {
  54445. this.trigger = triggerOptions.trigger;
  54446. }
  54447. else {
  54448. this.trigger = triggerOptions;
  54449. }
  54450. this._nextActiveAction = this;
  54451. this._condition = condition;
  54452. }
  54453. /**
  54454. * Internal only
  54455. * @hidden
  54456. */
  54457. Action.prototype._prepare = function () {
  54458. };
  54459. /**
  54460. * Gets the trigger parameters
  54461. * @returns the trigger parameters
  54462. */
  54463. Action.prototype.getTriggerParameter = function () {
  54464. return this._triggerParameter;
  54465. };
  54466. /**
  54467. * Internal only - executes current action event
  54468. * @hidden
  54469. */
  54470. Action.prototype._executeCurrent = function (evt) {
  54471. if (this._nextActiveAction._condition) {
  54472. var condition = this._nextActiveAction._condition;
  54473. var currentRenderId = this._actionManager.getScene().getRenderId();
  54474. // We cache the current evaluation for the current frame
  54475. if (condition._evaluationId === currentRenderId) {
  54476. if (!condition._currentResult) {
  54477. return;
  54478. }
  54479. }
  54480. else {
  54481. condition._evaluationId = currentRenderId;
  54482. if (!condition.isValid()) {
  54483. condition._currentResult = false;
  54484. return;
  54485. }
  54486. condition._currentResult = true;
  54487. }
  54488. }
  54489. this.onBeforeExecuteObservable.notifyObservers(this);
  54490. this._nextActiveAction.execute(evt);
  54491. this.skipToNextActiveAction();
  54492. };
  54493. /**
  54494. * Execute placeholder for child classes
  54495. * @param evt optional action event
  54496. */
  54497. Action.prototype.execute = function (evt) {
  54498. };
  54499. /**
  54500. * Skips to next active action
  54501. */
  54502. Action.prototype.skipToNextActiveAction = function () {
  54503. if (this._nextActiveAction._child) {
  54504. if (!this._nextActiveAction._child._actionManager) {
  54505. this._nextActiveAction._child._actionManager = this._actionManager;
  54506. }
  54507. this._nextActiveAction = this._nextActiveAction._child;
  54508. }
  54509. else {
  54510. this._nextActiveAction = this;
  54511. }
  54512. };
  54513. /**
  54514. * Adds action to chain of actions, may be a DoNothingAction
  54515. * @param action defines the next action to execute
  54516. * @returns The action passed in
  54517. * @see https://www.babylonjs-playground.com/#1T30HR#0
  54518. */
  54519. Action.prototype.then = function (action) {
  54520. this._child = action;
  54521. action._actionManager = this._actionManager;
  54522. action._prepare();
  54523. return action;
  54524. };
  54525. /**
  54526. * Internal only
  54527. * @hidden
  54528. */
  54529. Action.prototype._getProperty = function (propertyPath) {
  54530. return this._actionManager._getProperty(propertyPath);
  54531. };
  54532. /**
  54533. * Internal only
  54534. * @hidden
  54535. */
  54536. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  54537. return this._actionManager._getEffectiveTarget(target, propertyPath);
  54538. };
  54539. /**
  54540. * Serialize placeholder for child classes
  54541. * @param parent of child
  54542. * @returns the serialized object
  54543. */
  54544. Action.prototype.serialize = function (parent) {
  54545. };
  54546. /**
  54547. * Internal only called by serialize
  54548. * @hidden
  54549. */
  54550. Action.prototype._serialize = function (serializedAction, parent) {
  54551. var serializationObject = {
  54552. type: 1,
  54553. children: [],
  54554. name: serializedAction.name,
  54555. properties: serializedAction.properties || []
  54556. };
  54557. // Serialize child
  54558. if (this._child) {
  54559. this._child.serialize(serializationObject);
  54560. }
  54561. // Check if "this" has a condition
  54562. if (this._condition) {
  54563. var serializedCondition = this._condition.serialize();
  54564. serializedCondition.children.push(serializationObject);
  54565. if (parent) {
  54566. parent.children.push(serializedCondition);
  54567. }
  54568. return serializedCondition;
  54569. }
  54570. if (parent) {
  54571. parent.children.push(serializationObject);
  54572. }
  54573. return serializationObject;
  54574. };
  54575. /**
  54576. * Internal only
  54577. * @hidden
  54578. */
  54579. Action._SerializeValueAsString = function (value) {
  54580. if (typeof value === "number") {
  54581. return value.toString();
  54582. }
  54583. if (typeof value === "boolean") {
  54584. return value ? "true" : "false";
  54585. }
  54586. if (value instanceof BABYLON.Vector2) {
  54587. return value.x + ", " + value.y;
  54588. }
  54589. if (value instanceof BABYLON.Vector3) {
  54590. return value.x + ", " + value.y + ", " + value.z;
  54591. }
  54592. if (value instanceof BABYLON.Color3) {
  54593. return value.r + ", " + value.g + ", " + value.b;
  54594. }
  54595. if (value instanceof BABYLON.Color4) {
  54596. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  54597. }
  54598. return value; // string
  54599. };
  54600. /**
  54601. * Internal only
  54602. * @hidden
  54603. */
  54604. Action._GetTargetProperty = function (target) {
  54605. return {
  54606. name: "target",
  54607. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  54608. : target instanceof BABYLON.Light ? "LightProperties"
  54609. : target instanceof BABYLON.Camera ? "CameraProperties"
  54610. : "SceneProperties",
  54611. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  54612. };
  54613. };
  54614. return Action;
  54615. }());
  54616. BABYLON.Action = Action;
  54617. })(BABYLON || (BABYLON = {}));
  54618. //# sourceMappingURL=babylon.action.js.map
  54619. var BABYLON;
  54620. (function (BABYLON) {
  54621. /**
  54622. * ActionEvent is the event being sent when an action is triggered.
  54623. */
  54624. var ActionEvent = /** @class */ (function () {
  54625. /**
  54626. * Creates a new ActionEvent
  54627. * @param source The mesh or sprite that triggered the action
  54628. * @param pointerX The X mouse cursor position at the time of the event
  54629. * @param pointerY The Y mouse cursor position at the time of the event
  54630. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  54631. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  54632. * @param additionalData additional data for the event
  54633. */
  54634. function ActionEvent(
  54635. /** The mesh or sprite that triggered the action */
  54636. source,
  54637. /** The X mouse cursor position at the time of the event */
  54638. pointerX,
  54639. /** The Y mouse cursor position at the time of the event */
  54640. pointerY,
  54641. /** The mesh that is currently pointed at (can be null) */
  54642. meshUnderPointer,
  54643. /** the original (browser) event that triggered the ActionEvent */
  54644. sourceEvent,
  54645. /** additional data for the event */
  54646. additionalData) {
  54647. this.source = source;
  54648. this.pointerX = pointerX;
  54649. this.pointerY = pointerY;
  54650. this.meshUnderPointer = meshUnderPointer;
  54651. this.sourceEvent = sourceEvent;
  54652. this.additionalData = additionalData;
  54653. }
  54654. /**
  54655. * Helper function to auto-create an ActionEvent from a source mesh.
  54656. * @param source The source mesh that triggered the event
  54657. * @param evt The original (browser) event
  54658. * @param additionalData additional data for the event
  54659. * @returns the new ActionEvent
  54660. */
  54661. ActionEvent.CreateNew = function (source, evt, additionalData) {
  54662. var scene = source.getScene();
  54663. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  54664. };
  54665. /**
  54666. * Helper function to auto-create an ActionEvent from a source sprite
  54667. * @param source The source sprite that triggered the event
  54668. * @param scene Scene associated with the sprite
  54669. * @param evt The original (browser) event
  54670. * @param additionalData additional data for the event
  54671. * @returns the new ActionEvent
  54672. */
  54673. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  54674. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  54675. };
  54676. /**
  54677. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  54678. * @param scene the scene where the event occurred
  54679. * @param evt The original (browser) event
  54680. * @returns the new ActionEvent
  54681. */
  54682. ActionEvent.CreateNewFromScene = function (scene, evt) {
  54683. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  54684. };
  54685. /**
  54686. * Helper function to auto-create an ActionEvent from a primitive
  54687. * @param prim defines the target primitive
  54688. * @param pointerPos defines the pointer position
  54689. * @param evt The original (browser) event
  54690. * @param additionalData additional data for the event
  54691. * @returns the new ActionEvent
  54692. */
  54693. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  54694. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  54695. };
  54696. return ActionEvent;
  54697. }());
  54698. BABYLON.ActionEvent = ActionEvent;
  54699. /**
  54700. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  54701. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  54702. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54703. */
  54704. var ActionManager = /** @class */ (function () {
  54705. /**
  54706. * Creates a new action manager
  54707. * @param scene defines the hosting scene
  54708. */
  54709. function ActionManager(scene) {
  54710. // Members
  54711. /** Gets the list of actions */
  54712. this.actions = new Array();
  54713. /** Gets the cursor to use when hovering items */
  54714. this.hoverCursor = '';
  54715. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54716. scene.actionManagers.push(this);
  54717. }
  54718. // Methods
  54719. /**
  54720. * Releases all associated resources
  54721. */
  54722. ActionManager.prototype.dispose = function () {
  54723. var index = this._scene.actionManagers.indexOf(this);
  54724. for (var i = 0; i < this.actions.length; i++) {
  54725. var action = this.actions[i];
  54726. ActionManager.Triggers[action.trigger]--;
  54727. if (ActionManager.Triggers[action.trigger] === 0) {
  54728. delete ActionManager.Triggers[action.trigger];
  54729. }
  54730. }
  54731. if (index > -1) {
  54732. this._scene.actionManagers.splice(index, 1);
  54733. }
  54734. };
  54735. /**
  54736. * Gets hosting scene
  54737. * @returns the hosting scene
  54738. */
  54739. ActionManager.prototype.getScene = function () {
  54740. return this._scene;
  54741. };
  54742. /**
  54743. * Does this action manager handles actions of any of the given triggers
  54744. * @param triggers defines the triggers to be tested
  54745. * @return a boolean indicating whether one (or more) of the triggers is handled
  54746. */
  54747. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  54748. for (var index = 0; index < this.actions.length; index++) {
  54749. var action = this.actions[index];
  54750. if (triggers.indexOf(action.trigger) > -1) {
  54751. return true;
  54752. }
  54753. }
  54754. return false;
  54755. };
  54756. /**
  54757. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  54758. * speed.
  54759. * @param triggerA defines the trigger to be tested
  54760. * @param triggerB defines the trigger to be tested
  54761. * @return a boolean indicating whether one (or more) of the triggers is handled
  54762. */
  54763. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  54764. for (var index = 0; index < this.actions.length; index++) {
  54765. var action = this.actions[index];
  54766. if (triggerA == action.trigger || triggerB == action.trigger) {
  54767. return true;
  54768. }
  54769. }
  54770. return false;
  54771. };
  54772. /**
  54773. * Does this action manager handles actions of a given trigger
  54774. * @param trigger defines the trigger to be tested
  54775. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  54776. * @return whether the trigger is handled
  54777. */
  54778. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  54779. for (var index = 0; index < this.actions.length; index++) {
  54780. var action = this.actions[index];
  54781. if (action.trigger === trigger) {
  54782. if (parameterPredicate) {
  54783. if (parameterPredicate(action.getTriggerParameter())) {
  54784. return true;
  54785. }
  54786. }
  54787. else {
  54788. return true;
  54789. }
  54790. }
  54791. }
  54792. return false;
  54793. };
  54794. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  54795. /**
  54796. * Does this action manager has pointer triggers
  54797. */
  54798. get: function () {
  54799. for (var index = 0; index < this.actions.length; index++) {
  54800. var action = this.actions[index];
  54801. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  54802. return true;
  54803. }
  54804. }
  54805. return false;
  54806. },
  54807. enumerable: true,
  54808. configurable: true
  54809. });
  54810. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  54811. /**
  54812. * Does this action manager has pick triggers
  54813. */
  54814. get: function () {
  54815. for (var index = 0; index < this.actions.length; index++) {
  54816. var action = this.actions[index];
  54817. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  54818. return true;
  54819. }
  54820. }
  54821. return false;
  54822. },
  54823. enumerable: true,
  54824. configurable: true
  54825. });
  54826. Object.defineProperty(ActionManager, "HasTriggers", {
  54827. /**
  54828. * Does exist one action manager with at least one trigger
  54829. **/
  54830. get: function () {
  54831. for (var t in ActionManager.Triggers) {
  54832. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54833. return true;
  54834. }
  54835. }
  54836. return false;
  54837. },
  54838. enumerable: true,
  54839. configurable: true
  54840. });
  54841. Object.defineProperty(ActionManager, "HasPickTriggers", {
  54842. /**
  54843. * Does exist one action manager with at least one pick trigger
  54844. **/
  54845. get: function () {
  54846. for (var t in ActionManager.Triggers) {
  54847. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54848. var t_int = parseInt(t);
  54849. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  54850. return true;
  54851. }
  54852. }
  54853. }
  54854. return false;
  54855. },
  54856. enumerable: true,
  54857. configurable: true
  54858. });
  54859. /**
  54860. * Does exist one action manager that handles actions of a given trigger
  54861. * @param trigger defines the trigger to be tested
  54862. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  54863. **/
  54864. ActionManager.HasSpecificTrigger = function (trigger) {
  54865. for (var t in ActionManager.Triggers) {
  54866. if (ActionManager.Triggers.hasOwnProperty(t)) {
  54867. var t_int = parseInt(t);
  54868. if (t_int === trigger) {
  54869. return true;
  54870. }
  54871. }
  54872. }
  54873. return false;
  54874. };
  54875. /**
  54876. * Registers an action to this action manager
  54877. * @param action defines the action to be registered
  54878. * @return the action amended (prepared) after registration
  54879. */
  54880. ActionManager.prototype.registerAction = function (action) {
  54881. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  54882. if (this.getScene().actionManager !== this) {
  54883. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  54884. return null;
  54885. }
  54886. }
  54887. this.actions.push(action);
  54888. if (ActionManager.Triggers[action.trigger]) {
  54889. ActionManager.Triggers[action.trigger]++;
  54890. }
  54891. else {
  54892. ActionManager.Triggers[action.trigger] = 1;
  54893. }
  54894. action._actionManager = this;
  54895. action._prepare();
  54896. return action;
  54897. };
  54898. /**
  54899. * Unregisters an action to this action manager
  54900. * @param action defines the action to be unregistered
  54901. * @return a boolean indicating whether the action has been unregistered
  54902. */
  54903. ActionManager.prototype.unregisterAction = function (action) {
  54904. var index = this.actions.indexOf(action);
  54905. if (index !== -1) {
  54906. this.actions.splice(index, 1);
  54907. ActionManager.Triggers[action.trigger] -= 1;
  54908. if (ActionManager.Triggers[action.trigger] === 0) {
  54909. delete ActionManager.Triggers[action.trigger];
  54910. }
  54911. delete action._actionManager;
  54912. return true;
  54913. }
  54914. return false;
  54915. };
  54916. /**
  54917. * Process a specific trigger
  54918. * @param trigger defines the trigger to process
  54919. * @param evt defines the event details to be processed
  54920. */
  54921. ActionManager.prototype.processTrigger = function (trigger, evt) {
  54922. for (var index = 0; index < this.actions.length; index++) {
  54923. var action = this.actions[index];
  54924. if (action.trigger === trigger) {
  54925. if (evt) {
  54926. if (trigger === ActionManager.OnKeyUpTrigger
  54927. || trigger === ActionManager.OnKeyDownTrigger) {
  54928. var parameter = action.getTriggerParameter();
  54929. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  54930. if (!parameter.toLowerCase) {
  54931. continue;
  54932. }
  54933. var lowerCase = parameter.toLowerCase();
  54934. if (lowerCase !== evt.sourceEvent.key) {
  54935. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  54936. var actualkey = String.fromCharCode(unicode).toLowerCase();
  54937. if (actualkey !== lowerCase) {
  54938. continue;
  54939. }
  54940. }
  54941. }
  54942. }
  54943. }
  54944. action._executeCurrent(evt);
  54945. }
  54946. }
  54947. };
  54948. /** @hidden */
  54949. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  54950. var properties = propertyPath.split(".");
  54951. for (var index = 0; index < properties.length - 1; index++) {
  54952. target = target[properties[index]];
  54953. }
  54954. return target;
  54955. };
  54956. /** @hidden */
  54957. ActionManager.prototype._getProperty = function (propertyPath) {
  54958. var properties = propertyPath.split(".");
  54959. return properties[properties.length - 1];
  54960. };
  54961. /**
  54962. * Serialize this manager to a JSON object
  54963. * @param name defines the property name to store this manager
  54964. * @returns a JSON representation of this manager
  54965. */
  54966. ActionManager.prototype.serialize = function (name) {
  54967. var root = {
  54968. children: new Array(),
  54969. name: name,
  54970. type: 3,
  54971. properties: new Array() // Empty for root but required
  54972. };
  54973. for (var i = 0; i < this.actions.length; i++) {
  54974. var triggerObject = {
  54975. type: 0,
  54976. children: new Array(),
  54977. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  54978. properties: new Array()
  54979. };
  54980. var triggerOptions = this.actions[i].triggerOptions;
  54981. if (triggerOptions && typeof triggerOptions !== "number") {
  54982. if (triggerOptions.parameter instanceof BABYLON.Node) {
  54983. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  54984. }
  54985. else {
  54986. var parameter = {};
  54987. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  54988. if (triggerOptions.parameter.mesh) {
  54989. parameter._meshId = triggerOptions.parameter.mesh.id;
  54990. }
  54991. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  54992. }
  54993. }
  54994. // Serialize child action, recursively
  54995. this.actions[i].serialize(triggerObject);
  54996. // Add serialized trigger
  54997. root.children.push(triggerObject);
  54998. }
  54999. return root;
  55000. };
  55001. /**
  55002. * Creates a new ActionManager from a JSON data
  55003. * @param parsedActions defines the JSON data to read from
  55004. * @param object defines the hosting mesh
  55005. * @param scene defines the hosting scene
  55006. */
  55007. ActionManager.Parse = function (parsedActions, object, scene) {
  55008. var actionManager = new ActionManager(scene);
  55009. if (object === null)
  55010. scene.actionManager = actionManager;
  55011. else
  55012. object.actionManager = actionManager;
  55013. // instanciate a new object
  55014. var instanciate = function (name, params) {
  55015. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  55016. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  55017. newInstance.constructor.apply(newInstance, params);
  55018. return newInstance;
  55019. };
  55020. var parseParameter = function (name, value, target, propertyPath) {
  55021. if (propertyPath === null) {
  55022. // String, boolean or float
  55023. var floatValue = parseFloat(value);
  55024. if (value === "true" || value === "false")
  55025. return value === "true";
  55026. else
  55027. return isNaN(floatValue) ? value : floatValue;
  55028. }
  55029. var effectiveTarget = propertyPath.split(".");
  55030. var values = value.split(",");
  55031. // Get effective Target
  55032. for (var i = 0; i < effectiveTarget.length; i++) {
  55033. target = target[effectiveTarget[i]];
  55034. }
  55035. // Return appropriate value with its type
  55036. if (typeof (target) === "boolean")
  55037. return values[0] === "true";
  55038. if (typeof (target) === "string")
  55039. return values[0];
  55040. // Parameters with multiple values such as Vector3 etc.
  55041. var split = new Array();
  55042. for (var i = 0; i < values.length; i++)
  55043. split.push(parseFloat(values[i]));
  55044. if (target instanceof BABYLON.Vector3)
  55045. return BABYLON.Vector3.FromArray(split);
  55046. if (target instanceof BABYLON.Vector4)
  55047. return BABYLON.Vector4.FromArray(split);
  55048. if (target instanceof BABYLON.Color3)
  55049. return BABYLON.Color3.FromArray(split);
  55050. if (target instanceof BABYLON.Color4)
  55051. return BABYLON.Color4.FromArray(split);
  55052. return parseFloat(values[0]);
  55053. };
  55054. // traverse graph per trigger
  55055. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  55056. if (combineArray === void 0) { combineArray = null; }
  55057. if (parsedAction.detached)
  55058. return;
  55059. var parameters = new Array();
  55060. var target = null;
  55061. var propertyPath = null;
  55062. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  55063. // Parameters
  55064. if (parsedAction.type === 2)
  55065. parameters.push(actionManager);
  55066. else
  55067. parameters.push(trigger);
  55068. if (combine) {
  55069. var actions = new Array();
  55070. for (var j = 0; j < parsedAction.combine.length; j++) {
  55071. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  55072. }
  55073. parameters.push(actions);
  55074. }
  55075. else {
  55076. for (var i = 0; i < parsedAction.properties.length; i++) {
  55077. var value = parsedAction.properties[i].value;
  55078. var name = parsedAction.properties[i].name;
  55079. var targetType = parsedAction.properties[i].targetType;
  55080. if (name === "target")
  55081. if (targetType !== null && targetType === "SceneProperties")
  55082. value = target = scene;
  55083. else
  55084. value = target = scene.getNodeByName(value);
  55085. else if (name === "parent")
  55086. value = scene.getNodeByName(value);
  55087. else if (name === "sound") {
  55088. // Can not externalize to component, so only checks for the presence off the API.
  55089. if (scene.getSoundByName) {
  55090. value = scene.getSoundByName(value);
  55091. }
  55092. }
  55093. else if (name !== "propertyPath") {
  55094. if (parsedAction.type === 2 && name === "operator")
  55095. value = BABYLON.ValueCondition[value];
  55096. else
  55097. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  55098. }
  55099. else {
  55100. propertyPath = value;
  55101. }
  55102. parameters.push(value);
  55103. }
  55104. }
  55105. if (combineArray === null) {
  55106. parameters.push(condition);
  55107. }
  55108. else {
  55109. parameters.push(null);
  55110. }
  55111. // If interpolate value action
  55112. if (parsedAction.name === "InterpolateValueAction") {
  55113. var param = parameters[parameters.length - 2];
  55114. parameters[parameters.length - 1] = param;
  55115. parameters[parameters.length - 2] = condition;
  55116. }
  55117. // Action or condition(s) and not CombineAction
  55118. var newAction = instanciate(parsedAction.name, parameters);
  55119. if (newAction instanceof BABYLON.Condition && condition !== null) {
  55120. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  55121. if (action)
  55122. action.then(nothing);
  55123. else
  55124. actionManager.registerAction(nothing);
  55125. action = nothing;
  55126. }
  55127. if (combineArray === null) {
  55128. if (newAction instanceof BABYLON.Condition) {
  55129. condition = newAction;
  55130. newAction = action;
  55131. }
  55132. else {
  55133. condition = null;
  55134. if (action)
  55135. action.then(newAction);
  55136. else
  55137. actionManager.registerAction(newAction);
  55138. }
  55139. }
  55140. else {
  55141. combineArray.push(newAction);
  55142. }
  55143. for (var i = 0; i < parsedAction.children.length; i++)
  55144. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  55145. };
  55146. // triggers
  55147. for (var i = 0; i < parsedActions.children.length; i++) {
  55148. var triggerParams;
  55149. var trigger = parsedActions.children[i];
  55150. if (trigger.properties.length > 0) {
  55151. var param = trigger.properties[0].value;
  55152. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  55153. if (value._meshId) {
  55154. value.mesh = scene.getMeshByID(value._meshId);
  55155. }
  55156. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  55157. }
  55158. else
  55159. triggerParams = ActionManager[trigger.name];
  55160. for (var j = 0; j < trigger.children.length; j++) {
  55161. if (!trigger.detached)
  55162. traverse(trigger.children[j], triggerParams, null, null);
  55163. }
  55164. }
  55165. };
  55166. /**
  55167. * Get a trigger name by index
  55168. * @param trigger defines the trigger index
  55169. * @returns a trigger name
  55170. */
  55171. ActionManager.GetTriggerName = function (trigger) {
  55172. switch (trigger) {
  55173. case 0: return "NothingTrigger";
  55174. case 1: return "OnPickTrigger";
  55175. case 2: return "OnLeftPickTrigger";
  55176. case 3: return "OnRightPickTrigger";
  55177. case 4: return "OnCenterPickTrigger";
  55178. case 5: return "OnPickDownTrigger";
  55179. case 6: return "OnPickUpTrigger";
  55180. case 7: return "OnLongPressTrigger";
  55181. case 8: return "OnPointerOverTrigger";
  55182. case 9: return "OnPointerOutTrigger";
  55183. case 10: return "OnEveryFrameTrigger";
  55184. case 11: return "OnIntersectionEnterTrigger";
  55185. case 12: return "OnIntersectionExitTrigger";
  55186. case 13: return "OnKeyDownTrigger";
  55187. case 14: return "OnKeyUpTrigger";
  55188. case 15: return "OnPickOutTrigger";
  55189. default: return "";
  55190. }
  55191. };
  55192. /**
  55193. * Nothing
  55194. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55195. */
  55196. ActionManager.NothingTrigger = 0;
  55197. /**
  55198. * On pick
  55199. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55200. */
  55201. ActionManager.OnPickTrigger = 1;
  55202. /**
  55203. * On left pick
  55204. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55205. */
  55206. ActionManager.OnLeftPickTrigger = 2;
  55207. /**
  55208. * On right pick
  55209. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55210. */
  55211. ActionManager.OnRightPickTrigger = 3;
  55212. /**
  55213. * On center pick
  55214. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55215. */
  55216. ActionManager.OnCenterPickTrigger = 4;
  55217. /**
  55218. * On pick down
  55219. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55220. */
  55221. ActionManager.OnPickDownTrigger = 5;
  55222. /**
  55223. * On double pick
  55224. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55225. */
  55226. ActionManager.OnDoublePickTrigger = 6;
  55227. /**
  55228. * On pick up
  55229. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55230. */
  55231. ActionManager.OnPickUpTrigger = 7;
  55232. /**
  55233. * On pick out.
  55234. * This trigger will only be raised if you also declared a OnPickDown
  55235. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55236. */
  55237. ActionManager.OnPickOutTrigger = 16;
  55238. /**
  55239. * On long press
  55240. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55241. */
  55242. ActionManager.OnLongPressTrigger = 8;
  55243. /**
  55244. * On pointer over
  55245. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55246. */
  55247. ActionManager.OnPointerOverTrigger = 9;
  55248. /**
  55249. * On pointer out
  55250. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55251. */
  55252. ActionManager.OnPointerOutTrigger = 10;
  55253. /**
  55254. * On every frame
  55255. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55256. */
  55257. ActionManager.OnEveryFrameTrigger = 11;
  55258. /**
  55259. * On intersection enter
  55260. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55261. */
  55262. ActionManager.OnIntersectionEnterTrigger = 12;
  55263. /**
  55264. * On intersection exit
  55265. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55266. */
  55267. ActionManager.OnIntersectionExitTrigger = 13;
  55268. /**
  55269. * On key down
  55270. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55271. */
  55272. ActionManager.OnKeyDownTrigger = 14;
  55273. /**
  55274. * On key up
  55275. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55276. */
  55277. ActionManager.OnKeyUpTrigger = 15;
  55278. /** Gets the list of active triggers */
  55279. ActionManager.Triggers = {};
  55280. return ActionManager;
  55281. }());
  55282. BABYLON.ActionManager = ActionManager;
  55283. })(BABYLON || (BABYLON = {}));
  55284. //# sourceMappingURL=babylon.actionManager.js.map
  55285. var BABYLON;
  55286. (function (BABYLON) {
  55287. /**
  55288. * This defines an action responsible to change the value of a property
  55289. * by interpolating between its current value and the newly set one once triggered.
  55290. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55291. */
  55292. var InterpolateValueAction = /** @class */ (function (_super) {
  55293. __extends(InterpolateValueAction, _super);
  55294. /**
  55295. * Instantiate the action
  55296. * @param triggerOptions defines the trigger options
  55297. * @param target defines the object containing the value to interpolate
  55298. * @param propertyPath defines the path to the property in the target object
  55299. * @param value defines the target value at the end of the interpolation
  55300. * @param duration deines the time it will take for the property to interpolate to the value.
  55301. * @param condition defines the trigger related conditions
  55302. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  55303. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  55304. */
  55305. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  55306. if (duration === void 0) { duration = 1000; }
  55307. var _this = _super.call(this, triggerOptions, condition) || this;
  55308. /**
  55309. * Defines the time it will take for the property to interpolate to the value.
  55310. */
  55311. _this.duration = 1000;
  55312. /**
  55313. * Observable triggered once the interpolation animation has been done.
  55314. */
  55315. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  55316. _this.propertyPath = propertyPath;
  55317. _this.value = value;
  55318. _this.duration = duration;
  55319. _this.stopOtherAnimations = stopOtherAnimations;
  55320. _this.onInterpolationDone = onInterpolationDone;
  55321. _this._target = _this._effectiveTarget = target;
  55322. return _this;
  55323. }
  55324. /** @hidden */
  55325. InterpolateValueAction.prototype._prepare = function () {
  55326. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55327. this._property = this._getProperty(this.propertyPath);
  55328. };
  55329. /**
  55330. * Execute the action starts the value interpolation.
  55331. */
  55332. InterpolateValueAction.prototype.execute = function () {
  55333. var _this = this;
  55334. var scene = this._actionManager.getScene();
  55335. var keys = [
  55336. {
  55337. frame: 0,
  55338. value: this._effectiveTarget[this._property]
  55339. }, {
  55340. frame: 100,
  55341. value: this.value
  55342. }
  55343. ];
  55344. var dataType;
  55345. if (typeof this.value === "number") {
  55346. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  55347. }
  55348. else if (this.value instanceof BABYLON.Color3) {
  55349. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  55350. }
  55351. else if (this.value instanceof BABYLON.Vector3) {
  55352. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  55353. }
  55354. else if (this.value instanceof BABYLON.Matrix) {
  55355. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  55356. }
  55357. else if (this.value instanceof BABYLON.Quaternion) {
  55358. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  55359. }
  55360. else {
  55361. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  55362. return;
  55363. }
  55364. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  55365. animation.setKeys(keys);
  55366. if (this.stopOtherAnimations) {
  55367. scene.stopAnimation(this._effectiveTarget);
  55368. }
  55369. var wrapper = function () {
  55370. _this.onInterpolationDoneObservable.notifyObservers(_this);
  55371. if (_this.onInterpolationDone) {
  55372. _this.onInterpolationDone();
  55373. }
  55374. };
  55375. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  55376. };
  55377. /**
  55378. * Serializes the actions and its related information.
  55379. * @param parent defines the object to serialize in
  55380. * @returns the serialized object
  55381. */
  55382. InterpolateValueAction.prototype.serialize = function (parent) {
  55383. return _super.prototype._serialize.call(this, {
  55384. name: "InterpolateValueAction",
  55385. properties: [
  55386. BABYLON.Action._GetTargetProperty(this._target),
  55387. { name: "propertyPath", value: this.propertyPath },
  55388. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  55389. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  55390. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  55391. ]
  55392. }, parent);
  55393. };
  55394. return InterpolateValueAction;
  55395. }(BABYLON.Action));
  55396. BABYLON.InterpolateValueAction = InterpolateValueAction;
  55397. })(BABYLON || (BABYLON = {}));
  55398. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  55399. var BABYLON;
  55400. (function (BABYLON) {
  55401. /**
  55402. * This defines an action responsible to toggle a boolean once triggered.
  55403. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55404. */
  55405. var SwitchBooleanAction = /** @class */ (function (_super) {
  55406. __extends(SwitchBooleanAction, _super);
  55407. /**
  55408. * Instantiate the action
  55409. * @param triggerOptions defines the trigger options
  55410. * @param target defines the object containing the boolean
  55411. * @param propertyPath defines the path to the boolean property in the target object
  55412. * @param condition defines the trigger related conditions
  55413. */
  55414. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  55415. var _this = _super.call(this, triggerOptions, condition) || this;
  55416. _this.propertyPath = propertyPath;
  55417. _this._target = _this._effectiveTarget = target;
  55418. return _this;
  55419. }
  55420. /** @hidden */
  55421. SwitchBooleanAction.prototype._prepare = function () {
  55422. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55423. this._property = this._getProperty(this.propertyPath);
  55424. };
  55425. /**
  55426. * Execute the action toggle the boolean value.
  55427. */
  55428. SwitchBooleanAction.prototype.execute = function () {
  55429. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  55430. };
  55431. /**
  55432. * Serializes the actions and its related information.
  55433. * @param parent defines the object to serialize in
  55434. * @returns the serialized object
  55435. */
  55436. SwitchBooleanAction.prototype.serialize = function (parent) {
  55437. return _super.prototype._serialize.call(this, {
  55438. name: "SwitchBooleanAction",
  55439. properties: [
  55440. BABYLON.Action._GetTargetProperty(this._target),
  55441. { name: "propertyPath", value: this.propertyPath }
  55442. ]
  55443. }, parent);
  55444. };
  55445. return SwitchBooleanAction;
  55446. }(BABYLON.Action));
  55447. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  55448. /**
  55449. * This defines an action responsible to set a the state field of the target
  55450. * to a desired value once triggered.
  55451. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55452. */
  55453. var SetStateAction = /** @class */ (function (_super) {
  55454. __extends(SetStateAction, _super);
  55455. /**
  55456. * Instantiate the action
  55457. * @param triggerOptions defines the trigger options
  55458. * @param target defines the object containing the state property
  55459. * @param value defines the value to store in the state field
  55460. * @param condition defines the trigger related conditions
  55461. */
  55462. function SetStateAction(triggerOptions, target, value, condition) {
  55463. var _this = _super.call(this, triggerOptions, condition) || this;
  55464. _this.value = value;
  55465. _this._target = target;
  55466. return _this;
  55467. }
  55468. /**
  55469. * Execute the action and store the value on the target state property.
  55470. */
  55471. SetStateAction.prototype.execute = function () {
  55472. this._target.state = this.value;
  55473. };
  55474. /**
  55475. * Serializes the actions and its related information.
  55476. * @param parent defines the object to serialize in
  55477. * @returns the serialized object
  55478. */
  55479. SetStateAction.prototype.serialize = function (parent) {
  55480. return _super.prototype._serialize.call(this, {
  55481. name: "SetStateAction",
  55482. properties: [
  55483. BABYLON.Action._GetTargetProperty(this._target),
  55484. { name: "value", value: this.value }
  55485. ]
  55486. }, parent);
  55487. };
  55488. return SetStateAction;
  55489. }(BABYLON.Action));
  55490. BABYLON.SetStateAction = SetStateAction;
  55491. /**
  55492. * This defines an action responsible to set a property of the target
  55493. * to a desired value once triggered.
  55494. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55495. */
  55496. var SetValueAction = /** @class */ (function (_super) {
  55497. __extends(SetValueAction, _super);
  55498. /**
  55499. * Instantiate the action
  55500. * @param triggerOptions defines the trigger options
  55501. * @param target defines the object containing the property
  55502. * @param propertyPath defines the path of the property to set in the target
  55503. * @param value defines the value to set in the property
  55504. * @param condition defines the trigger related conditions
  55505. */
  55506. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  55507. var _this = _super.call(this, triggerOptions, condition) || this;
  55508. _this.propertyPath = propertyPath;
  55509. _this.value = value;
  55510. _this._target = _this._effectiveTarget = target;
  55511. return _this;
  55512. }
  55513. /** @hidden */
  55514. SetValueAction.prototype._prepare = function () {
  55515. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55516. this._property = this._getProperty(this.propertyPath);
  55517. };
  55518. /**
  55519. * Execute the action and set the targetted property to the desired value.
  55520. */
  55521. SetValueAction.prototype.execute = function () {
  55522. this._effectiveTarget[this._property] = this.value;
  55523. if (this._target.markAsDirty) {
  55524. this._target.markAsDirty(this._property);
  55525. }
  55526. };
  55527. /**
  55528. * Serializes the actions and its related information.
  55529. * @param parent defines the object to serialize in
  55530. * @returns the serialized object
  55531. */
  55532. SetValueAction.prototype.serialize = function (parent) {
  55533. return _super.prototype._serialize.call(this, {
  55534. name: "SetValueAction",
  55535. properties: [
  55536. BABYLON.Action._GetTargetProperty(this._target),
  55537. { name: "propertyPath", value: this.propertyPath },
  55538. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  55539. ]
  55540. }, parent);
  55541. };
  55542. return SetValueAction;
  55543. }(BABYLON.Action));
  55544. BABYLON.SetValueAction = SetValueAction;
  55545. /**
  55546. * This defines an action responsible to increment the target value
  55547. * to a desired value once triggered.
  55548. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55549. */
  55550. var IncrementValueAction = /** @class */ (function (_super) {
  55551. __extends(IncrementValueAction, _super);
  55552. /**
  55553. * Instantiate the action
  55554. * @param triggerOptions defines the trigger options
  55555. * @param target defines the object containing the property
  55556. * @param propertyPath defines the path of the property to increment in the target
  55557. * @param value defines the value value we should increment the property by
  55558. * @param condition defines the trigger related conditions
  55559. */
  55560. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  55561. var _this = _super.call(this, triggerOptions, condition) || this;
  55562. _this.propertyPath = propertyPath;
  55563. _this.value = value;
  55564. _this._target = _this._effectiveTarget = target;
  55565. return _this;
  55566. }
  55567. /** @hidden */
  55568. IncrementValueAction.prototype._prepare = function () {
  55569. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55570. this._property = this._getProperty(this.propertyPath);
  55571. if (typeof this._effectiveTarget[this._property] !== "number") {
  55572. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  55573. }
  55574. };
  55575. /**
  55576. * Execute the action and increment the target of the value amount.
  55577. */
  55578. IncrementValueAction.prototype.execute = function () {
  55579. this._effectiveTarget[this._property] += this.value;
  55580. if (this._target.markAsDirty) {
  55581. this._target.markAsDirty(this._property);
  55582. }
  55583. };
  55584. /**
  55585. * Serializes the actions and its related information.
  55586. * @param parent defines the object to serialize in
  55587. * @returns the serialized object
  55588. */
  55589. IncrementValueAction.prototype.serialize = function (parent) {
  55590. return _super.prototype._serialize.call(this, {
  55591. name: "IncrementValueAction",
  55592. properties: [
  55593. BABYLON.Action._GetTargetProperty(this._target),
  55594. { name: "propertyPath", value: this.propertyPath },
  55595. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  55596. ]
  55597. }, parent);
  55598. };
  55599. return IncrementValueAction;
  55600. }(BABYLON.Action));
  55601. BABYLON.IncrementValueAction = IncrementValueAction;
  55602. /**
  55603. * This defines an action responsible to start an animation once triggered.
  55604. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55605. */
  55606. var PlayAnimationAction = /** @class */ (function (_super) {
  55607. __extends(PlayAnimationAction, _super);
  55608. /**
  55609. * Instantiate the action
  55610. * @param triggerOptions defines the trigger options
  55611. * @param target defines the target animation or animation name
  55612. * @param from defines from where the animation should start (animation frame)
  55613. * @param end defines where the animation should stop (animation frame)
  55614. * @param loop defines if the animation should loop or stop after the first play
  55615. * @param condition defines the trigger related conditions
  55616. */
  55617. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  55618. var _this = _super.call(this, triggerOptions, condition) || this;
  55619. _this.from = from;
  55620. _this.to = to;
  55621. _this.loop = loop;
  55622. _this._target = target;
  55623. return _this;
  55624. }
  55625. /** @hidden */
  55626. PlayAnimationAction.prototype._prepare = function () {
  55627. };
  55628. /**
  55629. * Execute the action and play the animation.
  55630. */
  55631. PlayAnimationAction.prototype.execute = function () {
  55632. var scene = this._actionManager.getScene();
  55633. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  55634. };
  55635. /**
  55636. * Serializes the actions and its related information.
  55637. * @param parent defines the object to serialize in
  55638. * @returns the serialized object
  55639. */
  55640. PlayAnimationAction.prototype.serialize = function (parent) {
  55641. return _super.prototype._serialize.call(this, {
  55642. name: "PlayAnimationAction",
  55643. properties: [
  55644. BABYLON.Action._GetTargetProperty(this._target),
  55645. { name: "from", value: String(this.from) },
  55646. { name: "to", value: String(this.to) },
  55647. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  55648. ]
  55649. }, parent);
  55650. };
  55651. return PlayAnimationAction;
  55652. }(BABYLON.Action));
  55653. BABYLON.PlayAnimationAction = PlayAnimationAction;
  55654. /**
  55655. * This defines an action responsible to stop an animation once triggered.
  55656. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55657. */
  55658. var StopAnimationAction = /** @class */ (function (_super) {
  55659. __extends(StopAnimationAction, _super);
  55660. /**
  55661. * Instantiate the action
  55662. * @param triggerOptions defines the trigger options
  55663. * @param target defines the target animation or animation name
  55664. * @param condition defines the trigger related conditions
  55665. */
  55666. function StopAnimationAction(triggerOptions, target, condition) {
  55667. var _this = _super.call(this, triggerOptions, condition) || this;
  55668. _this._target = target;
  55669. return _this;
  55670. }
  55671. /** @hidden */
  55672. StopAnimationAction.prototype._prepare = function () {
  55673. };
  55674. /**
  55675. * Execute the action and stop the animation.
  55676. */
  55677. StopAnimationAction.prototype.execute = function () {
  55678. var scene = this._actionManager.getScene();
  55679. scene.stopAnimation(this._target);
  55680. };
  55681. /**
  55682. * Serializes the actions and its related information.
  55683. * @param parent defines the object to serialize in
  55684. * @returns the serialized object
  55685. */
  55686. StopAnimationAction.prototype.serialize = function (parent) {
  55687. return _super.prototype._serialize.call(this, {
  55688. name: "StopAnimationAction",
  55689. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  55690. }, parent);
  55691. };
  55692. return StopAnimationAction;
  55693. }(BABYLON.Action));
  55694. BABYLON.StopAnimationAction = StopAnimationAction;
  55695. /**
  55696. * This defines an action responsible that does nothing once triggered.
  55697. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55698. */
  55699. var DoNothingAction = /** @class */ (function (_super) {
  55700. __extends(DoNothingAction, _super);
  55701. /**
  55702. * Instantiate the action
  55703. * @param triggerOptions defines the trigger options
  55704. * @param condition defines the trigger related conditions
  55705. */
  55706. function DoNothingAction(triggerOptions, condition) {
  55707. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  55708. return _super.call(this, triggerOptions, condition) || this;
  55709. }
  55710. /**
  55711. * Execute the action and do nothing.
  55712. */
  55713. DoNothingAction.prototype.execute = function () {
  55714. };
  55715. /**
  55716. * Serializes the actions and its related information.
  55717. * @param parent defines the object to serialize in
  55718. * @returns the serialized object
  55719. */
  55720. DoNothingAction.prototype.serialize = function (parent) {
  55721. return _super.prototype._serialize.call(this, {
  55722. name: "DoNothingAction",
  55723. properties: []
  55724. }, parent);
  55725. };
  55726. return DoNothingAction;
  55727. }(BABYLON.Action));
  55728. BABYLON.DoNothingAction = DoNothingAction;
  55729. /**
  55730. * This defines an action responsible to trigger several actions once triggered.
  55731. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55732. */
  55733. var CombineAction = /** @class */ (function (_super) {
  55734. __extends(CombineAction, _super);
  55735. /**
  55736. * Instantiate the action
  55737. * @param triggerOptions defines the trigger options
  55738. * @param children defines the list of aggregated animations to run
  55739. * @param condition defines the trigger related conditions
  55740. */
  55741. function CombineAction(triggerOptions, children, condition) {
  55742. var _this = _super.call(this, triggerOptions, condition) || this;
  55743. _this.children = children;
  55744. return _this;
  55745. }
  55746. /** @hidden */
  55747. CombineAction.prototype._prepare = function () {
  55748. for (var index = 0; index < this.children.length; index++) {
  55749. this.children[index]._actionManager = this._actionManager;
  55750. this.children[index]._prepare();
  55751. }
  55752. };
  55753. /**
  55754. * Execute the action and executes all the aggregated actions.
  55755. */
  55756. CombineAction.prototype.execute = function (evt) {
  55757. for (var index = 0; index < this.children.length; index++) {
  55758. this.children[index].execute(evt);
  55759. }
  55760. };
  55761. /**
  55762. * Serializes the actions and its related information.
  55763. * @param parent defines the object to serialize in
  55764. * @returns the serialized object
  55765. */
  55766. CombineAction.prototype.serialize = function (parent) {
  55767. var serializationObject = _super.prototype._serialize.call(this, {
  55768. name: "CombineAction",
  55769. properties: [],
  55770. combine: []
  55771. }, parent);
  55772. for (var i = 0; i < this.children.length; i++) {
  55773. serializationObject.combine.push(this.children[i].serialize(null));
  55774. }
  55775. return serializationObject;
  55776. };
  55777. return CombineAction;
  55778. }(BABYLON.Action));
  55779. BABYLON.CombineAction = CombineAction;
  55780. /**
  55781. * This defines an action responsible to run code (external event) once triggered.
  55782. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55783. */
  55784. var ExecuteCodeAction = /** @class */ (function (_super) {
  55785. __extends(ExecuteCodeAction, _super);
  55786. /**
  55787. * Instantiate the action
  55788. * @param triggerOptions defines the trigger options
  55789. * @param func defines the callback function to run
  55790. * @param condition defines the trigger related conditions
  55791. */
  55792. function ExecuteCodeAction(triggerOptions, func, condition) {
  55793. var _this = _super.call(this, triggerOptions, condition) || this;
  55794. _this.func = func;
  55795. return _this;
  55796. }
  55797. /**
  55798. * Execute the action and run the attached code.
  55799. */
  55800. ExecuteCodeAction.prototype.execute = function (evt) {
  55801. this.func(evt);
  55802. };
  55803. return ExecuteCodeAction;
  55804. }(BABYLON.Action));
  55805. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  55806. /**
  55807. * This defines an action responsible to set the parent property of the target once triggered.
  55808. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55809. */
  55810. var SetParentAction = /** @class */ (function (_super) {
  55811. __extends(SetParentAction, _super);
  55812. /**
  55813. * Instantiate the action
  55814. * @param triggerOptions defines the trigger options
  55815. * @param target defines the target containing the parent property
  55816. * @param parent defines from where the animation should start (animation frame)
  55817. * @param condition defines the trigger related conditions
  55818. */
  55819. function SetParentAction(triggerOptions, target, parent, condition) {
  55820. var _this = _super.call(this, triggerOptions, condition) || this;
  55821. _this._target = target;
  55822. _this._parent = parent;
  55823. return _this;
  55824. }
  55825. /** @hidden */
  55826. SetParentAction.prototype._prepare = function () {
  55827. };
  55828. /**
  55829. * Execute the action and set the parent property.
  55830. */
  55831. SetParentAction.prototype.execute = function () {
  55832. if (this._target.parent === this._parent) {
  55833. return;
  55834. }
  55835. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  55836. invertParentWorldMatrix.invert();
  55837. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  55838. this._target.parent = this._parent;
  55839. };
  55840. /**
  55841. * Serializes the actions and its related information.
  55842. * @param parent defines the object to serialize in
  55843. * @returns the serialized object
  55844. */
  55845. SetParentAction.prototype.serialize = function (parent) {
  55846. return _super.prototype._serialize.call(this, {
  55847. name: "SetParentAction",
  55848. properties: [
  55849. BABYLON.Action._GetTargetProperty(this._target),
  55850. BABYLON.Action._GetTargetProperty(this._parent),
  55851. ]
  55852. }, parent);
  55853. };
  55854. return SetParentAction;
  55855. }(BABYLON.Action));
  55856. BABYLON.SetParentAction = SetParentAction;
  55857. })(BABYLON || (BABYLON = {}));
  55858. //# sourceMappingURL=babylon.directActions.js.map
  55859. var BABYLON;
  55860. (function (BABYLON) {
  55861. var SpriteManager = /** @class */ (function () {
  55862. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  55863. if (epsilon === void 0) { epsilon = 0.01; }
  55864. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55865. this.name = name;
  55866. this.sprites = new Array();
  55867. this.renderingGroupId = 0;
  55868. this.layerMask = 0x0FFFFFFF;
  55869. this.fogEnabled = true;
  55870. this.isPickable = false;
  55871. /**
  55872. * An event triggered when the manager is disposed.
  55873. */
  55874. this.onDisposeObservable = new BABYLON.Observable();
  55875. this._vertexBuffers = {};
  55876. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  55877. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  55878. }
  55879. this._capacity = capacity;
  55880. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  55881. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55882. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55883. if (cellSize.width && cellSize.height) {
  55884. this.cellWidth = cellSize.width;
  55885. this.cellHeight = cellSize.height;
  55886. }
  55887. else if (cellSize !== undefined) {
  55888. this.cellWidth = cellSize;
  55889. this.cellHeight = cellSize;
  55890. }
  55891. else {
  55892. return;
  55893. }
  55894. this._epsilon = epsilon;
  55895. this._scene = scene;
  55896. this._scene.spriteManagers.push(this);
  55897. var indices = [];
  55898. var index = 0;
  55899. for (var count = 0; count < capacity; count++) {
  55900. indices.push(index);
  55901. indices.push(index + 1);
  55902. indices.push(index + 2);
  55903. indices.push(index);
  55904. indices.push(index + 2);
  55905. indices.push(index + 3);
  55906. index += 4;
  55907. }
  55908. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  55909. // VBO
  55910. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  55911. this._vertexData = new Float32Array(capacity * 16 * 4);
  55912. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  55913. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  55914. var options = this._buffer.createVertexBuffer("options", 4, 4);
  55915. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  55916. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  55917. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55918. this._vertexBuffers["options"] = options;
  55919. this._vertexBuffers["cellInfo"] = cellInfo;
  55920. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55921. // Effects
  55922. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  55923. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  55924. }
  55925. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  55926. set: function (callback) {
  55927. if (this._onDisposeObserver) {
  55928. this.onDisposeObservable.remove(this._onDisposeObserver);
  55929. }
  55930. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55931. },
  55932. enumerable: true,
  55933. configurable: true
  55934. });
  55935. Object.defineProperty(SpriteManager.prototype, "texture", {
  55936. get: function () {
  55937. return this._spriteTexture;
  55938. },
  55939. set: function (value) {
  55940. this._spriteTexture = value;
  55941. },
  55942. enumerable: true,
  55943. configurable: true
  55944. });
  55945. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  55946. var arrayOffset = index * 16;
  55947. if (offsetX === 0)
  55948. offsetX = this._epsilon;
  55949. else if (offsetX === 1)
  55950. offsetX = 1 - this._epsilon;
  55951. if (offsetY === 0)
  55952. offsetY = this._epsilon;
  55953. else if (offsetY === 1)
  55954. offsetY = 1 - this._epsilon;
  55955. this._vertexData[arrayOffset] = sprite.position.x;
  55956. this._vertexData[arrayOffset + 1] = sprite.position.y;
  55957. this._vertexData[arrayOffset + 2] = sprite.position.z;
  55958. this._vertexData[arrayOffset + 3] = sprite.angle;
  55959. this._vertexData[arrayOffset + 4] = sprite.width;
  55960. this._vertexData[arrayOffset + 5] = sprite.height;
  55961. this._vertexData[arrayOffset + 6] = offsetX;
  55962. this._vertexData[arrayOffset + 7] = offsetY;
  55963. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  55964. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  55965. var offset = (sprite.cellIndex / rowSize) >> 0;
  55966. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  55967. this._vertexData[arrayOffset + 11] = offset;
  55968. // Color
  55969. this._vertexData[arrayOffset + 12] = sprite.color.r;
  55970. this._vertexData[arrayOffset + 13] = sprite.color.g;
  55971. this._vertexData[arrayOffset + 14] = sprite.color.b;
  55972. this._vertexData[arrayOffset + 15] = sprite.color.a;
  55973. };
  55974. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  55975. var count = Math.min(this._capacity, this.sprites.length);
  55976. var min = BABYLON.Vector3.Zero();
  55977. var max = BABYLON.Vector3.Zero();
  55978. var distance = Number.MAX_VALUE;
  55979. var currentSprite = null;
  55980. var cameraSpacePosition = BABYLON.Vector3.Zero();
  55981. var cameraView = camera.getViewMatrix();
  55982. for (var index = 0; index < count; index++) {
  55983. var sprite = this.sprites[index];
  55984. if (!sprite) {
  55985. continue;
  55986. }
  55987. if (predicate) {
  55988. if (!predicate(sprite)) {
  55989. continue;
  55990. }
  55991. }
  55992. else if (!sprite.isPickable) {
  55993. continue;
  55994. }
  55995. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  55996. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  55997. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  55998. if (ray.intersectsBoxMinMax(min, max)) {
  55999. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  56000. if (distance > currentDistance) {
  56001. distance = currentDistance;
  56002. currentSprite = sprite;
  56003. if (fastCheck) {
  56004. break;
  56005. }
  56006. }
  56007. }
  56008. }
  56009. if (currentSprite) {
  56010. var result = new BABYLON.PickingInfo();
  56011. result.hit = true;
  56012. result.pickedSprite = currentSprite;
  56013. result.distance = distance;
  56014. return result;
  56015. }
  56016. return null;
  56017. };
  56018. SpriteManager.prototype.render = function () {
  56019. // Check
  56020. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  56021. return;
  56022. var engine = this._scene.getEngine();
  56023. var baseSize = this._spriteTexture.getBaseSize();
  56024. // Sprites
  56025. var deltaTime = engine.getDeltaTime();
  56026. var max = Math.min(this._capacity, this.sprites.length);
  56027. var rowSize = baseSize.width / this.cellWidth;
  56028. var offset = 0;
  56029. for (var index = 0; index < max; index++) {
  56030. var sprite = this.sprites[index];
  56031. if (!sprite || !sprite.isVisible) {
  56032. continue;
  56033. }
  56034. sprite._animate(deltaTime);
  56035. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  56036. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  56037. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  56038. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  56039. }
  56040. this._buffer.update(this._vertexData);
  56041. // Render
  56042. var effect = this._effectBase;
  56043. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56044. effect = this._effectFog;
  56045. }
  56046. engine.enableEffect(effect);
  56047. var viewMatrix = this._scene.getViewMatrix();
  56048. effect.setTexture("diffuseSampler", this._spriteTexture);
  56049. effect.setMatrix("view", viewMatrix);
  56050. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56051. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  56052. // Fog
  56053. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56054. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  56055. effect.setColor3("vFogColor", this._scene.fogColor);
  56056. }
  56057. // VBOs
  56058. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56059. // Draw order
  56060. engine.setDepthFunctionToLessOrEqual();
  56061. effect.setBool("alphaTest", true);
  56062. engine.setColorWrite(false);
  56063. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  56064. engine.setColorWrite(true);
  56065. effect.setBool("alphaTest", false);
  56066. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56067. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  56068. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56069. };
  56070. SpriteManager.prototype.dispose = function () {
  56071. if (this._buffer) {
  56072. this._buffer.dispose();
  56073. this._buffer = null;
  56074. }
  56075. if (this._indexBuffer) {
  56076. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56077. this._indexBuffer = null;
  56078. }
  56079. if (this._spriteTexture) {
  56080. this._spriteTexture.dispose();
  56081. this._spriteTexture = null;
  56082. }
  56083. // Remove from scene
  56084. var index = this._scene.spriteManagers.indexOf(this);
  56085. this._scene.spriteManagers.splice(index, 1);
  56086. // Callback
  56087. this.onDisposeObservable.notifyObservers(this);
  56088. this.onDisposeObservable.clear();
  56089. };
  56090. return SpriteManager;
  56091. }());
  56092. BABYLON.SpriteManager = SpriteManager;
  56093. })(BABYLON || (BABYLON = {}));
  56094. //# sourceMappingURL=babylon.spriteManager.js.map
  56095. var BABYLON;
  56096. (function (BABYLON) {
  56097. var Sprite = /** @class */ (function () {
  56098. function Sprite(name, manager) {
  56099. this.name = name;
  56100. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56101. this.width = 1.0;
  56102. this.height = 1.0;
  56103. this.angle = 0;
  56104. this.cellIndex = 0;
  56105. this.invertU = 0;
  56106. this.invertV = 0;
  56107. this.animations = new Array();
  56108. this.isPickable = false;
  56109. this._animationStarted = false;
  56110. this._loopAnimation = false;
  56111. this._fromIndex = 0;
  56112. this._toIndex = 0;
  56113. this._delay = 0;
  56114. this._direction = 1;
  56115. this._time = 0;
  56116. /**
  56117. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  56118. */
  56119. this.isVisible = true;
  56120. this._manager = manager;
  56121. this._manager.sprites.push(this);
  56122. this.position = BABYLON.Vector3.Zero();
  56123. }
  56124. Object.defineProperty(Sprite.prototype, "size", {
  56125. get: function () {
  56126. return this.width;
  56127. },
  56128. set: function (value) {
  56129. this.width = value;
  56130. this.height = value;
  56131. },
  56132. enumerable: true,
  56133. configurable: true
  56134. });
  56135. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  56136. this._fromIndex = from;
  56137. this._toIndex = to;
  56138. this._loopAnimation = loop;
  56139. this._delay = delay;
  56140. this._animationStarted = true;
  56141. this._direction = from < to ? 1 : -1;
  56142. this.cellIndex = from;
  56143. this._time = 0;
  56144. this._onAnimationEnd = onAnimationEnd;
  56145. };
  56146. Sprite.prototype.stopAnimation = function () {
  56147. this._animationStarted = false;
  56148. };
  56149. /** @hidden */
  56150. Sprite.prototype._animate = function (deltaTime) {
  56151. if (!this._animationStarted)
  56152. return;
  56153. this._time += deltaTime;
  56154. if (this._time > this._delay) {
  56155. this._time = this._time % this._delay;
  56156. this.cellIndex += this._direction;
  56157. if (this.cellIndex > this._toIndex) {
  56158. if (this._loopAnimation) {
  56159. this.cellIndex = this._fromIndex;
  56160. }
  56161. else {
  56162. this.cellIndex = this._toIndex;
  56163. this._animationStarted = false;
  56164. if (this._onAnimationEnd) {
  56165. this._onAnimationEnd();
  56166. }
  56167. if (this.disposeWhenFinishedAnimating) {
  56168. this.dispose();
  56169. }
  56170. }
  56171. }
  56172. }
  56173. };
  56174. Sprite.prototype.dispose = function () {
  56175. for (var i = 0; i < this._manager.sprites.length; i++) {
  56176. if (this._manager.sprites[i] == this) {
  56177. this._manager.sprites.splice(i, 1);
  56178. }
  56179. }
  56180. };
  56181. return Sprite;
  56182. }());
  56183. BABYLON.Sprite = Sprite;
  56184. })(BABYLON || (BABYLON = {}));
  56185. //# sourceMappingURL=babylon.sprite.js.map
  56186. var BABYLON;
  56187. (function (BABYLON) {
  56188. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  56189. if (!BABYLON.PickingInfo) {
  56190. return null;
  56191. }
  56192. var pickingInfo = null;
  56193. if (!camera) {
  56194. if (!this.activeCamera) {
  56195. return null;
  56196. }
  56197. camera = this.activeCamera;
  56198. }
  56199. if (this.spriteManagers.length > 0) {
  56200. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  56201. var spriteManager = this.spriteManagers[spriteIndex];
  56202. if (!spriteManager.isPickable) {
  56203. continue;
  56204. }
  56205. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  56206. if (!result || !result.hit)
  56207. continue;
  56208. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  56209. continue;
  56210. pickingInfo = result;
  56211. if (fastCheck) {
  56212. break;
  56213. }
  56214. }
  56215. }
  56216. return pickingInfo || new BABYLON.PickingInfo();
  56217. };
  56218. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  56219. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  56220. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56221. };
  56222. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  56223. if (!this._tempSpritePickingRay) {
  56224. return null;
  56225. }
  56226. if (!camera) {
  56227. if (!this.activeCamera) {
  56228. return null;
  56229. }
  56230. camera = this.activeCamera;
  56231. }
  56232. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  56233. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56234. };
  56235. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  56236. if (this._pointerOverSprite === sprite) {
  56237. return;
  56238. }
  56239. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56240. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56241. }
  56242. this._pointerOverSprite = sprite;
  56243. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56244. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56245. }
  56246. };
  56247. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  56248. return this._pointerOverSprite;
  56249. };
  56250. /**
  56251. * Defines the sprite scene component responsible to manage sprites
  56252. * in a given scene.
  56253. */
  56254. var SpriteSceneComponent = /** @class */ (function () {
  56255. /**
  56256. * Creates a new instance of the component for the given scene
  56257. * @param scene Defines the scene to register the component in
  56258. */
  56259. function SpriteSceneComponent(scene) {
  56260. /**
  56261. * The component name helpfull to identify the component in the list of scene components.
  56262. */
  56263. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  56264. this.scene = scene;
  56265. this.scene.spriteManagers = new Array();
  56266. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  56267. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  56268. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  56269. this._spritePredicate = function (sprite) {
  56270. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  56271. };
  56272. }
  56273. /**
  56274. * Registers the component in a given scene
  56275. */
  56276. SpriteSceneComponent.prototype.register = function () {
  56277. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  56278. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  56279. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  56280. };
  56281. /**
  56282. * Rebuilds the elements related to this component in case of
  56283. * context lost for instance.
  56284. */
  56285. SpriteSceneComponent.prototype.rebuild = function () {
  56286. /** Nothing to do for sprites */
  56287. };
  56288. /**
  56289. * Disposes the component and the associated ressources.
  56290. */
  56291. SpriteSceneComponent.prototype.dispose = function () {
  56292. this.scene.onBeforeSpritesRenderingObservable.clear();
  56293. this.scene.onAfterSpritesRenderingObservable.clear();
  56294. var spriteManagers = this.scene.spriteManagers;
  56295. while (spriteManagers.length) {
  56296. spriteManagers[0].dispose();
  56297. }
  56298. };
  56299. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  56300. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  56301. if (result) {
  56302. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  56303. }
  56304. return result;
  56305. };
  56306. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  56307. var scene = this.scene;
  56308. if (isMeshPicked) {
  56309. scene.setPointerOverSprite(null);
  56310. }
  56311. else {
  56312. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  56313. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  56314. scene.setPointerOverSprite(pickResult.pickedSprite);
  56315. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  56316. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  56317. }
  56318. else {
  56319. canvas.style.cursor = scene.hoverCursor;
  56320. }
  56321. }
  56322. else {
  56323. scene.setPointerOverSprite(null);
  56324. }
  56325. }
  56326. return pickResult;
  56327. };
  56328. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  56329. var scene = this.scene;
  56330. scene._pickedDownSprite = null;
  56331. if (scene.spriteManagers.length > 0) {
  56332. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  56333. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  56334. if (pickResult.pickedSprite.actionManager) {
  56335. scene._pickedDownSprite = pickResult.pickedSprite;
  56336. switch (evt.button) {
  56337. case 0:
  56338. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56339. break;
  56340. case 1:
  56341. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56342. break;
  56343. case 2:
  56344. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56345. break;
  56346. }
  56347. if (pickResult.pickedSprite.actionManager) {
  56348. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56349. }
  56350. }
  56351. }
  56352. }
  56353. return pickResult;
  56354. };
  56355. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  56356. var scene = this.scene;
  56357. if (scene.spriteManagers.length > 0) {
  56358. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  56359. if (spritePickResult) {
  56360. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  56361. if (spritePickResult.pickedSprite.actionManager) {
  56362. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  56363. if (spritePickResult.pickedSprite.actionManager) {
  56364. if (!this.scene._isPointerSwiping()) {
  56365. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  56366. }
  56367. }
  56368. }
  56369. }
  56370. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  56371. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  56372. }
  56373. }
  56374. }
  56375. return pickResult;
  56376. };
  56377. return SpriteSceneComponent;
  56378. }());
  56379. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  56380. })(BABYLON || (BABYLON = {}));
  56381. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  56382. var BABYLON;
  56383. (function (BABYLON) {
  56384. /**
  56385. * @hidden
  56386. */
  56387. var IntersectionInfo = /** @class */ (function () {
  56388. function IntersectionInfo(bu, bv, distance) {
  56389. this.bu = bu;
  56390. this.bv = bv;
  56391. this.distance = distance;
  56392. this.faceId = 0;
  56393. this.subMeshId = 0;
  56394. }
  56395. return IntersectionInfo;
  56396. }());
  56397. BABYLON.IntersectionInfo = IntersectionInfo;
  56398. /**
  56399. * Information about the result of picking within a scene
  56400. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  56401. */
  56402. var PickingInfo = /** @class */ (function () {
  56403. function PickingInfo() {
  56404. /**
  56405. * If the pick collided with an object
  56406. */
  56407. this.hit = false;
  56408. /**
  56409. * Distance away where the pick collided
  56410. */
  56411. this.distance = 0;
  56412. /**
  56413. * The location of pick collision
  56414. */
  56415. this.pickedPoint = null;
  56416. /**
  56417. * The mesh corresponding the the pick collision
  56418. */
  56419. this.pickedMesh = null;
  56420. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  56421. this.bu = 0;
  56422. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  56423. this.bv = 0;
  56424. /** The id of the face on the mesh that was picked */
  56425. this.faceId = -1;
  56426. /** Id of the the submesh that was picked */
  56427. this.subMeshId = 0;
  56428. /** If a sprite was picked, this will be the sprite the pick collided with */
  56429. this.pickedSprite = null;
  56430. /**
  56431. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  56432. */
  56433. this.originMesh = null;
  56434. /**
  56435. * The ray that was used to perform the picking.
  56436. */
  56437. this.ray = null;
  56438. }
  56439. /**
  56440. * Gets the normal correspodning to the face the pick collided with
  56441. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  56442. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  56443. * @returns The normal correspodning to the face the pick collided with
  56444. */
  56445. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  56446. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  56447. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  56448. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  56449. return null;
  56450. }
  56451. var indices = this.pickedMesh.getIndices();
  56452. if (!indices) {
  56453. return null;
  56454. }
  56455. var result;
  56456. if (useVerticesNormals) {
  56457. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56458. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  56459. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  56460. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  56461. normal0 = normal0.scale(this.bu);
  56462. normal1 = normal1.scale(this.bv);
  56463. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  56464. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  56465. }
  56466. else {
  56467. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56468. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  56469. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  56470. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  56471. var p1p2 = vertex1.subtract(vertex2);
  56472. var p3p2 = vertex3.subtract(vertex2);
  56473. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  56474. }
  56475. if (useWorldCoordinates) {
  56476. var wm = this.pickedMesh.getWorldMatrix();
  56477. if (this.pickedMesh.nonUniformScaling) {
  56478. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  56479. wm = BABYLON.Tmp.Matrix[0];
  56480. wm.setTranslationFromFloats(0, 0, 0);
  56481. wm.invert();
  56482. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  56483. wm = BABYLON.Tmp.Matrix[1];
  56484. }
  56485. result = BABYLON.Vector3.TransformNormal(result, wm);
  56486. }
  56487. result.normalize();
  56488. return result;
  56489. };
  56490. /**
  56491. * Gets the texture coordinates of where the pick occured
  56492. * @returns the vector containing the coordnates of the texture
  56493. */
  56494. PickingInfo.prototype.getTextureCoordinates = function () {
  56495. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56496. return null;
  56497. }
  56498. var indices = this.pickedMesh.getIndices();
  56499. if (!indices) {
  56500. return null;
  56501. }
  56502. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56503. if (!uvs) {
  56504. return null;
  56505. }
  56506. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  56507. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  56508. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  56509. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  56510. uv1 = uv1.scale(this.bu);
  56511. uv2 = uv2.scale(this.bv);
  56512. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  56513. };
  56514. return PickingInfo;
  56515. }());
  56516. BABYLON.PickingInfo = PickingInfo;
  56517. })(BABYLON || (BABYLON = {}));
  56518. //# sourceMappingURL=babylon.pickingInfo.js.map
  56519. var BABYLON;
  56520. (function (BABYLON) {
  56521. var Ray = /** @class */ (function () {
  56522. function Ray(origin, direction, length) {
  56523. if (length === void 0) { length = Number.MAX_VALUE; }
  56524. this.origin = origin;
  56525. this.direction = direction;
  56526. this.length = length;
  56527. }
  56528. // Methods
  56529. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  56530. var d = 0.0;
  56531. var maxValue = Number.MAX_VALUE;
  56532. var inv;
  56533. var min;
  56534. var max;
  56535. var temp;
  56536. if (Math.abs(this.direction.x) < 0.0000001) {
  56537. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  56538. return false;
  56539. }
  56540. }
  56541. else {
  56542. inv = 1.0 / this.direction.x;
  56543. min = (minimum.x - this.origin.x) * inv;
  56544. max = (maximum.x - this.origin.x) * inv;
  56545. if (max === -Infinity) {
  56546. max = Infinity;
  56547. }
  56548. if (min > max) {
  56549. temp = min;
  56550. min = max;
  56551. max = temp;
  56552. }
  56553. d = Math.max(min, d);
  56554. maxValue = Math.min(max, maxValue);
  56555. if (d > maxValue) {
  56556. return false;
  56557. }
  56558. }
  56559. if (Math.abs(this.direction.y) < 0.0000001) {
  56560. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  56561. return false;
  56562. }
  56563. }
  56564. else {
  56565. inv = 1.0 / this.direction.y;
  56566. min = (minimum.y - this.origin.y) * inv;
  56567. max = (maximum.y - this.origin.y) * inv;
  56568. if (max === -Infinity) {
  56569. max = Infinity;
  56570. }
  56571. if (min > max) {
  56572. temp = min;
  56573. min = max;
  56574. max = temp;
  56575. }
  56576. d = Math.max(min, d);
  56577. maxValue = Math.min(max, maxValue);
  56578. if (d > maxValue) {
  56579. return false;
  56580. }
  56581. }
  56582. if (Math.abs(this.direction.z) < 0.0000001) {
  56583. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  56584. return false;
  56585. }
  56586. }
  56587. else {
  56588. inv = 1.0 / this.direction.z;
  56589. min = (minimum.z - this.origin.z) * inv;
  56590. max = (maximum.z - this.origin.z) * inv;
  56591. if (max === -Infinity) {
  56592. max = Infinity;
  56593. }
  56594. if (min > max) {
  56595. temp = min;
  56596. min = max;
  56597. max = temp;
  56598. }
  56599. d = Math.max(min, d);
  56600. maxValue = Math.min(max, maxValue);
  56601. if (d > maxValue) {
  56602. return false;
  56603. }
  56604. }
  56605. return true;
  56606. };
  56607. Ray.prototype.intersectsBox = function (box) {
  56608. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  56609. };
  56610. Ray.prototype.intersectsSphere = function (sphere) {
  56611. var x = sphere.center.x - this.origin.x;
  56612. var y = sphere.center.y - this.origin.y;
  56613. var z = sphere.center.z - this.origin.z;
  56614. var pyth = (x * x) + (y * y) + (z * z);
  56615. var rr = sphere.radius * sphere.radius;
  56616. if (pyth <= rr) {
  56617. return true;
  56618. }
  56619. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  56620. if (dot < 0.0) {
  56621. return false;
  56622. }
  56623. var temp = pyth - (dot * dot);
  56624. return temp <= rr;
  56625. };
  56626. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  56627. if (!this._edge1) {
  56628. this._edge1 = BABYLON.Vector3.Zero();
  56629. this._edge2 = BABYLON.Vector3.Zero();
  56630. this._pvec = BABYLON.Vector3.Zero();
  56631. this._tvec = BABYLON.Vector3.Zero();
  56632. this._qvec = BABYLON.Vector3.Zero();
  56633. }
  56634. vertex1.subtractToRef(vertex0, this._edge1);
  56635. vertex2.subtractToRef(vertex0, this._edge2);
  56636. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  56637. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  56638. if (det === 0) {
  56639. return null;
  56640. }
  56641. var invdet = 1 / det;
  56642. this.origin.subtractToRef(vertex0, this._tvec);
  56643. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  56644. if (bu < 0 || bu > 1.0) {
  56645. return null;
  56646. }
  56647. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  56648. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  56649. if (bv < 0 || bu + bv > 1.0) {
  56650. return null;
  56651. }
  56652. //check if the distance is longer than the predefined length.
  56653. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  56654. if (distance > this.length) {
  56655. return null;
  56656. }
  56657. return new BABYLON.IntersectionInfo(bu, bv, distance);
  56658. };
  56659. Ray.prototype.intersectsPlane = function (plane) {
  56660. var distance;
  56661. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  56662. if (Math.abs(result1) < 9.99999997475243E-07) {
  56663. return null;
  56664. }
  56665. else {
  56666. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  56667. distance = (-plane.d - result2) / result1;
  56668. if (distance < 0.0) {
  56669. if (distance < -9.99999997475243E-07) {
  56670. return null;
  56671. }
  56672. else {
  56673. return 0;
  56674. }
  56675. }
  56676. return distance;
  56677. }
  56678. };
  56679. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  56680. var tm = BABYLON.Tmp.Matrix[0];
  56681. mesh.getWorldMatrix().invertToRef(tm);
  56682. if (this._tmpRay) {
  56683. Ray.TransformToRef(this, tm, this._tmpRay);
  56684. }
  56685. else {
  56686. this._tmpRay = Ray.Transform(this, tm);
  56687. }
  56688. return mesh.intersects(this._tmpRay, fastCheck);
  56689. };
  56690. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  56691. if (results) {
  56692. results.length = 0;
  56693. }
  56694. else {
  56695. results = [];
  56696. }
  56697. for (var i = 0; i < meshes.length; i++) {
  56698. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  56699. if (pickInfo.hit) {
  56700. results.push(pickInfo);
  56701. }
  56702. }
  56703. results.sort(this._comparePickingInfo);
  56704. return results;
  56705. };
  56706. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  56707. if (pickingInfoA.distance < pickingInfoB.distance) {
  56708. return -1;
  56709. }
  56710. else if (pickingInfoA.distance > pickingInfoB.distance) {
  56711. return 1;
  56712. }
  56713. else {
  56714. return 0;
  56715. }
  56716. };
  56717. /**
  56718. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  56719. * @param sega the first point of the segment to test the intersection against
  56720. * @param segb the second point of the segment to test the intersection against
  56721. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  56722. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  56723. */
  56724. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  56725. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  56726. var u = segb.subtract(sega);
  56727. var v = rsegb.subtract(this.origin);
  56728. var w = sega.subtract(this.origin);
  56729. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  56730. var b = BABYLON.Vector3.Dot(u, v);
  56731. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  56732. var d = BABYLON.Vector3.Dot(u, w);
  56733. var e = BABYLON.Vector3.Dot(v, w);
  56734. var D = a * c - b * b; // always >= 0
  56735. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  56736. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  56737. // compute the line parameters of the two closest points
  56738. if (D < Ray.smallnum) { // the lines are almost parallel
  56739. sN = 0.0; // force using point P0 on segment S1
  56740. sD = 1.0; // to prevent possible division by 0.0 later
  56741. tN = e;
  56742. tD = c;
  56743. }
  56744. else { // get the closest points on the infinite lines
  56745. sN = (b * e - c * d);
  56746. tN = (a * e - b * d);
  56747. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  56748. sN = 0.0;
  56749. tN = e;
  56750. tD = c;
  56751. }
  56752. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  56753. sN = sD;
  56754. tN = e + b;
  56755. tD = c;
  56756. }
  56757. }
  56758. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  56759. tN = 0.0;
  56760. // recompute sc for this edge
  56761. if (-d < 0.0) {
  56762. sN = 0.0;
  56763. }
  56764. else if (-d > a)
  56765. sN = sD;
  56766. else {
  56767. sN = -d;
  56768. sD = a;
  56769. }
  56770. }
  56771. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  56772. tN = tD;
  56773. // recompute sc for this edge
  56774. if ((-d + b) < 0.0) {
  56775. sN = 0;
  56776. }
  56777. else if ((-d + b) > a) {
  56778. sN = sD;
  56779. }
  56780. else {
  56781. sN = (-d + b);
  56782. sD = a;
  56783. }
  56784. }
  56785. // finally do the division to get sc and tc
  56786. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  56787. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  56788. // get the difference of the two closest points
  56789. var qtc = v.multiplyByFloats(tc, tc, tc);
  56790. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  56791. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  56792. if (isIntersected) {
  56793. return qtc.length();
  56794. }
  56795. return -1;
  56796. };
  56797. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  56798. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  56799. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  56800. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  56801. this.direction.normalize();
  56802. return this;
  56803. };
  56804. // Statics
  56805. Ray.Zero = function () {
  56806. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  56807. };
  56808. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  56809. var result = Ray.Zero();
  56810. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  56811. };
  56812. /**
  56813. * 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
  56814. * transformed to the given world matrix.
  56815. * @param origin The origin point
  56816. * @param end The end point
  56817. * @param world a matrix to transform the ray to. Default is the identity matrix.
  56818. */
  56819. Ray.CreateNewFromTo = function (origin, end, world) {
  56820. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  56821. var direction = end.subtract(origin);
  56822. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  56823. direction.normalize();
  56824. return Ray.Transform(new Ray(origin, direction, length), world);
  56825. };
  56826. Ray.Transform = function (ray, matrix) {
  56827. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  56828. Ray.TransformToRef(ray, matrix, result);
  56829. return result;
  56830. };
  56831. Ray.TransformToRef = function (ray, matrix, result) {
  56832. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  56833. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  56834. result.length = ray.length;
  56835. var dir = result.direction;
  56836. var len = dir.length();
  56837. if (!(len === 0 || len === 1)) {
  56838. var num = 1.0 / len;
  56839. dir.x *= num;
  56840. dir.y *= num;
  56841. dir.z *= num;
  56842. result.length *= len;
  56843. }
  56844. };
  56845. Ray.smallnum = 0.00000001;
  56846. Ray.rayl = 10e8;
  56847. return Ray;
  56848. }());
  56849. BABYLON.Ray = Ray;
  56850. })(BABYLON || (BABYLON = {}));
  56851. //# sourceMappingURL=babylon.ray.js.map
  56852. var BABYLON;
  56853. (function (BABYLON) {
  56854. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  56855. if (boxMin.x > sphereCenter.x + sphereRadius)
  56856. return false;
  56857. if (sphereCenter.x - sphereRadius > boxMax.x)
  56858. return false;
  56859. if (boxMin.y > sphereCenter.y + sphereRadius)
  56860. return false;
  56861. if (sphereCenter.y - sphereRadius > boxMax.y)
  56862. return false;
  56863. if (boxMin.z > sphereCenter.z + sphereRadius)
  56864. return false;
  56865. if (sphereCenter.z - sphereRadius > boxMax.z)
  56866. return false;
  56867. return true;
  56868. };
  56869. var getLowestRoot = (function () {
  56870. var result = { root: 0, found: false };
  56871. return function (a, b, c, maxR) {
  56872. result.root = 0;
  56873. result.found = false;
  56874. var determinant = b * b - 4.0 * a * c;
  56875. if (determinant < 0)
  56876. return result;
  56877. var sqrtD = Math.sqrt(determinant);
  56878. var r1 = (-b - sqrtD) / (2.0 * a);
  56879. var r2 = (-b + sqrtD) / (2.0 * a);
  56880. if (r1 > r2) {
  56881. var temp = r2;
  56882. r2 = r1;
  56883. r1 = temp;
  56884. }
  56885. if (r1 > 0 && r1 < maxR) {
  56886. result.root = r1;
  56887. result.found = true;
  56888. return result;
  56889. }
  56890. if (r2 > 0 && r2 < maxR) {
  56891. result.root = r2;
  56892. result.found = true;
  56893. return result;
  56894. }
  56895. return result;
  56896. };
  56897. })();
  56898. /** @hidden */
  56899. var Collider = /** @class */ (function () {
  56900. function Collider() {
  56901. this._collisionPoint = BABYLON.Vector3.Zero();
  56902. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  56903. this._tempVector = BABYLON.Vector3.Zero();
  56904. this._tempVector2 = BABYLON.Vector3.Zero();
  56905. this._tempVector3 = BABYLON.Vector3.Zero();
  56906. this._tempVector4 = BABYLON.Vector3.Zero();
  56907. this._edge = BABYLON.Vector3.Zero();
  56908. this._baseToVertex = BABYLON.Vector3.Zero();
  56909. this._destinationPoint = BABYLON.Vector3.Zero();
  56910. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  56911. this._displacementVector = BABYLON.Vector3.Zero();
  56912. /** @hidden */
  56913. this._radius = BABYLON.Vector3.One();
  56914. /** @hidden */
  56915. this._retry = 0;
  56916. /** @hidden */
  56917. this._basePointWorld = BABYLON.Vector3.Zero();
  56918. this._velocityWorld = BABYLON.Vector3.Zero();
  56919. this._normalizedVelocity = BABYLON.Vector3.Zero();
  56920. this._collisionMask = -1;
  56921. }
  56922. Object.defineProperty(Collider.prototype, "collisionMask", {
  56923. get: function () {
  56924. return this._collisionMask;
  56925. },
  56926. set: function (mask) {
  56927. this._collisionMask = !isNaN(mask) ? mask : -1;
  56928. },
  56929. enumerable: true,
  56930. configurable: true
  56931. });
  56932. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  56933. /**
  56934. * Gets the plane normal used to compute the sliding response (in local space)
  56935. */
  56936. get: function () {
  56937. return this._slidePlaneNormal;
  56938. },
  56939. enumerable: true,
  56940. configurable: true
  56941. });
  56942. // Methods
  56943. /** @hidden */
  56944. Collider.prototype._initialize = function (source, dir, e) {
  56945. this._velocity = dir;
  56946. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  56947. this._basePoint = source;
  56948. source.multiplyToRef(this._radius, this._basePointWorld);
  56949. dir.multiplyToRef(this._radius, this._velocityWorld);
  56950. this._velocityWorldLength = this._velocityWorld.length();
  56951. this._epsilon = e;
  56952. this.collisionFound = false;
  56953. };
  56954. /** @hidden */
  56955. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  56956. pa.subtractToRef(point, this._tempVector);
  56957. pb.subtractToRef(point, this._tempVector2);
  56958. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  56959. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56960. if (d < 0)
  56961. return false;
  56962. pc.subtractToRef(point, this._tempVector3);
  56963. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  56964. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56965. if (d < 0)
  56966. return false;
  56967. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  56968. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  56969. return d >= 0;
  56970. };
  56971. /** @hidden */
  56972. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  56973. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  56974. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  56975. if (distance > this._velocityWorldLength + max + sphereRadius) {
  56976. return false;
  56977. }
  56978. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  56979. return false;
  56980. return true;
  56981. };
  56982. /** @hidden */
  56983. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  56984. var t0;
  56985. var embeddedInPlane = false;
  56986. //defensive programming, actually not needed.
  56987. if (!trianglePlaneArray) {
  56988. trianglePlaneArray = [];
  56989. }
  56990. if (!trianglePlaneArray[faceIndex]) {
  56991. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  56992. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  56993. }
  56994. var trianglePlane = trianglePlaneArray[faceIndex];
  56995. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  56996. return;
  56997. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  56998. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  56999. if (normalDotVelocity == 0) {
  57000. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  57001. return;
  57002. embeddedInPlane = true;
  57003. t0 = 0;
  57004. }
  57005. else {
  57006. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  57007. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  57008. if (t0 > t1) {
  57009. var temp = t1;
  57010. t1 = t0;
  57011. t0 = temp;
  57012. }
  57013. if (t0 > 1.0 || t1 < 0.0)
  57014. return;
  57015. if (t0 < 0)
  57016. t0 = 0;
  57017. if (t0 > 1.0)
  57018. t0 = 1.0;
  57019. }
  57020. this._collisionPoint.copyFromFloats(0, 0, 0);
  57021. var found = false;
  57022. var t = 1.0;
  57023. if (!embeddedInPlane) {
  57024. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  57025. this._velocity.scaleToRef(t0, this._tempVector);
  57026. this._planeIntersectionPoint.addInPlace(this._tempVector);
  57027. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  57028. found = true;
  57029. t = t0;
  57030. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  57031. }
  57032. }
  57033. if (!found) {
  57034. var velocitySquaredLength = this._velocity.lengthSquared();
  57035. var a = velocitySquaredLength;
  57036. this._basePoint.subtractToRef(p1, this._tempVector);
  57037. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57038. var c = this._tempVector.lengthSquared() - 1.0;
  57039. var lowestRoot = getLowestRoot(a, b, c, t);
  57040. if (lowestRoot.found) {
  57041. t = lowestRoot.root;
  57042. found = true;
  57043. this._collisionPoint.copyFrom(p1);
  57044. }
  57045. this._basePoint.subtractToRef(p2, this._tempVector);
  57046. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57047. c = this._tempVector.lengthSquared() - 1.0;
  57048. lowestRoot = getLowestRoot(a, b, c, t);
  57049. if (lowestRoot.found) {
  57050. t = lowestRoot.root;
  57051. found = true;
  57052. this._collisionPoint.copyFrom(p2);
  57053. }
  57054. this._basePoint.subtractToRef(p3, this._tempVector);
  57055. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57056. c = this._tempVector.lengthSquared() - 1.0;
  57057. lowestRoot = getLowestRoot(a, b, c, t);
  57058. if (lowestRoot.found) {
  57059. t = lowestRoot.root;
  57060. found = true;
  57061. this._collisionPoint.copyFrom(p3);
  57062. }
  57063. p2.subtractToRef(p1, this._edge);
  57064. p1.subtractToRef(this._basePoint, this._baseToVertex);
  57065. var edgeSquaredLength = this._edge.lengthSquared();
  57066. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57067. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57068. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57069. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57070. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57071. lowestRoot = getLowestRoot(a, b, c, t);
  57072. if (lowestRoot.found) {
  57073. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57074. if (f >= 0.0 && f <= 1.0) {
  57075. t = lowestRoot.root;
  57076. found = true;
  57077. this._edge.scaleInPlace(f);
  57078. p1.addToRef(this._edge, this._collisionPoint);
  57079. }
  57080. }
  57081. p3.subtractToRef(p2, this._edge);
  57082. p2.subtractToRef(this._basePoint, this._baseToVertex);
  57083. edgeSquaredLength = this._edge.lengthSquared();
  57084. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57085. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57086. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57087. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57088. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57089. lowestRoot = getLowestRoot(a, b, c, t);
  57090. if (lowestRoot.found) {
  57091. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57092. if (f >= 0.0 && f <= 1.0) {
  57093. t = lowestRoot.root;
  57094. found = true;
  57095. this._edge.scaleInPlace(f);
  57096. p2.addToRef(this._edge, this._collisionPoint);
  57097. }
  57098. }
  57099. p1.subtractToRef(p3, this._edge);
  57100. p3.subtractToRef(this._basePoint, this._baseToVertex);
  57101. edgeSquaredLength = this._edge.lengthSquared();
  57102. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57103. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57104. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57105. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57106. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57107. lowestRoot = getLowestRoot(a, b, c, t);
  57108. if (lowestRoot.found) {
  57109. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57110. if (f >= 0.0 && f <= 1.0) {
  57111. t = lowestRoot.root;
  57112. found = true;
  57113. this._edge.scaleInPlace(f);
  57114. p3.addToRef(this._edge, this._collisionPoint);
  57115. }
  57116. }
  57117. }
  57118. if (found) {
  57119. var distToCollision = t * this._velocity.length();
  57120. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  57121. if (!this.intersectionPoint) {
  57122. this.intersectionPoint = this._collisionPoint.clone();
  57123. }
  57124. else {
  57125. this.intersectionPoint.copyFrom(this._collisionPoint);
  57126. }
  57127. this._nearestDistance = distToCollision;
  57128. this.collisionFound = true;
  57129. }
  57130. }
  57131. };
  57132. /** @hidden */
  57133. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  57134. for (var i = indexStart; i < indexEnd; i += 3) {
  57135. var p1 = pts[indices[i] - decal];
  57136. var p2 = pts[indices[i + 1] - decal];
  57137. var p3 = pts[indices[i + 2] - decal];
  57138. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  57139. }
  57140. };
  57141. /** @hidden */
  57142. Collider.prototype._getResponse = function (pos, vel) {
  57143. pos.addToRef(vel, this._destinationPoint);
  57144. vel.scaleInPlace((this._nearestDistance / vel.length()));
  57145. this._basePoint.addToRef(vel, pos);
  57146. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  57147. this._slidePlaneNormal.normalize();
  57148. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  57149. pos.addInPlace(this._displacementVector);
  57150. this.intersectionPoint.addInPlace(this._displacementVector);
  57151. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  57152. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  57153. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  57154. };
  57155. return Collider;
  57156. }());
  57157. BABYLON.Collider = Collider;
  57158. })(BABYLON || (BABYLON = {}));
  57159. //# sourceMappingURL=babylon.collider.js.map
  57160. var BABYLON;
  57161. (function (BABYLON) {
  57162. //WebWorker code will be inserted to this variable.
  57163. /** @hidden */
  57164. BABYLON.CollisionWorker = "";
  57165. /** Defines supported task for worker process */
  57166. var WorkerTaskType;
  57167. (function (WorkerTaskType) {
  57168. /** Initialization */
  57169. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  57170. /** Update of geometry */
  57171. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  57172. /** Evaluate collision */
  57173. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  57174. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  57175. /** Defines kind of replies returned by worker */
  57176. var WorkerReplyType;
  57177. (function (WorkerReplyType) {
  57178. /** Success */
  57179. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  57180. /** Unkown error */
  57181. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  57182. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  57183. /** @hidden */
  57184. var CollisionCoordinatorWorker = /** @class */ (function () {
  57185. function CollisionCoordinatorWorker() {
  57186. var _this = this;
  57187. this._scaledPosition = BABYLON.Vector3.Zero();
  57188. this._scaledVelocity = BABYLON.Vector3.Zero();
  57189. this.onMeshUpdated = function (transformNode) {
  57190. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  57191. };
  57192. this.onGeometryUpdated = function (geometry) {
  57193. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  57194. };
  57195. this._afterRender = function () {
  57196. if (!_this._init)
  57197. return;
  57198. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  57199. return;
  57200. }
  57201. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  57202. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  57203. if (_this._runningUpdated > 4) {
  57204. return;
  57205. }
  57206. ++_this._runningUpdated;
  57207. var payload = {
  57208. updatedMeshes: _this._addUpdateMeshesList,
  57209. updatedGeometries: _this._addUpdateGeometriesList,
  57210. removedGeometries: _this._toRemoveGeometryArray,
  57211. removedMeshes: _this._toRemoveMeshesArray
  57212. };
  57213. var message = {
  57214. payload: payload,
  57215. taskType: WorkerTaskType.UPDATE
  57216. };
  57217. var serializable = [];
  57218. for (var id in payload.updatedGeometries) {
  57219. if (payload.updatedGeometries.hasOwnProperty(id)) {
  57220. //prepare transferables
  57221. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  57222. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  57223. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  57224. }
  57225. }
  57226. _this._worker.postMessage(message, serializable);
  57227. _this._addUpdateMeshesList = {};
  57228. _this._addUpdateGeometriesList = {};
  57229. _this._toRemoveGeometryArray = [];
  57230. _this._toRemoveMeshesArray = [];
  57231. };
  57232. this._onMessageFromWorker = function (e) {
  57233. var returnData = e.data;
  57234. if (returnData.error != WorkerReplyType.SUCCESS) {
  57235. //TODO what errors can be returned from the worker?
  57236. BABYLON.Tools.Warn("error returned from worker!");
  57237. return;
  57238. }
  57239. switch (returnData.taskType) {
  57240. case WorkerTaskType.INIT:
  57241. _this._init = true;
  57242. //Update the worked with ALL of the scene's current state
  57243. _this._scene.meshes.forEach(function (mesh) {
  57244. _this.onMeshAdded(mesh);
  57245. });
  57246. _this._scene.getGeometries().forEach(function (geometry) {
  57247. _this.onGeometryAdded(geometry);
  57248. });
  57249. break;
  57250. case WorkerTaskType.UPDATE:
  57251. _this._runningUpdated--;
  57252. break;
  57253. case WorkerTaskType.COLLIDE:
  57254. var returnPayload = returnData.payload;
  57255. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  57256. return;
  57257. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  57258. if (callback) {
  57259. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  57260. if (mesh) {
  57261. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  57262. }
  57263. }
  57264. //cleanup
  57265. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  57266. break;
  57267. }
  57268. };
  57269. this._collisionsCallbackArray = [];
  57270. this._init = false;
  57271. this._runningUpdated = 0;
  57272. this._addUpdateMeshesList = {};
  57273. this._addUpdateGeometriesList = {};
  57274. this._toRemoveGeometryArray = [];
  57275. this._toRemoveMeshesArray = [];
  57276. }
  57277. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  57278. if (!this._init)
  57279. return;
  57280. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  57281. return;
  57282. position.divideToRef(collider._radius, this._scaledPosition);
  57283. displacement.divideToRef(collider._radius, this._scaledVelocity);
  57284. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  57285. var payload = {
  57286. collider: {
  57287. position: this._scaledPosition.asArray(),
  57288. velocity: this._scaledVelocity.asArray(),
  57289. radius: collider._radius.asArray()
  57290. },
  57291. collisionId: collisionIndex,
  57292. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  57293. maximumRetry: maximumRetry
  57294. };
  57295. var message = {
  57296. payload: payload,
  57297. taskType: WorkerTaskType.COLLIDE
  57298. };
  57299. this._worker.postMessage(message);
  57300. };
  57301. CollisionCoordinatorWorker.prototype.init = function (scene) {
  57302. this._scene = scene;
  57303. this._scene.registerAfterRender(this._afterRender);
  57304. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  57305. this._worker = new Worker(workerUrl);
  57306. this._worker.onmessage = this._onMessageFromWorker;
  57307. var message = {
  57308. payload: {},
  57309. taskType: WorkerTaskType.INIT
  57310. };
  57311. this._worker.postMessage(message);
  57312. };
  57313. CollisionCoordinatorWorker.prototype.destroy = function () {
  57314. this._scene.unregisterAfterRender(this._afterRender);
  57315. this._worker.terminate();
  57316. };
  57317. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  57318. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  57319. this.onMeshUpdated(mesh);
  57320. };
  57321. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  57322. this._toRemoveMeshesArray.push(mesh.uniqueId);
  57323. };
  57324. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  57325. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  57326. geometry.onGeometryUpdated = this.onGeometryUpdated;
  57327. this.onGeometryUpdated(geometry);
  57328. };
  57329. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  57330. this._toRemoveGeometryArray.push(geometry.id);
  57331. };
  57332. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  57333. var submeshes = [];
  57334. if (mesh.subMeshes) {
  57335. submeshes = mesh.subMeshes.map(function (sm, idx) {
  57336. var boundingInfo = sm.getBoundingInfo();
  57337. return {
  57338. position: idx,
  57339. verticesStart: sm.verticesStart,
  57340. verticesCount: sm.verticesCount,
  57341. indexStart: sm.indexStart,
  57342. indexCount: sm.indexCount,
  57343. hasMaterial: !!sm.getMaterial(),
  57344. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  57345. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  57346. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  57347. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  57348. };
  57349. });
  57350. }
  57351. var geometryId = null;
  57352. if (mesh instanceof BABYLON.Mesh) {
  57353. var geometry = mesh.geometry;
  57354. geometryId = geometry ? geometry.id : null;
  57355. }
  57356. else if (mesh instanceof BABYLON.InstancedMesh) {
  57357. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  57358. geometryId = geometry ? geometry.id : null;
  57359. }
  57360. var boundingInfo = mesh.getBoundingInfo();
  57361. return {
  57362. uniqueId: mesh.uniqueId,
  57363. id: mesh.id,
  57364. name: mesh.name,
  57365. geometryId: geometryId,
  57366. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  57367. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  57368. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  57369. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  57370. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  57371. subMeshes: submeshes,
  57372. checkCollisions: mesh.checkCollisions
  57373. };
  57374. };
  57375. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  57376. return {
  57377. id: geometry.id,
  57378. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  57379. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  57380. indices: new Uint32Array(geometry.getIndices() || []),
  57381. };
  57382. };
  57383. return CollisionCoordinatorWorker;
  57384. }());
  57385. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  57386. /** @hidden */
  57387. var CollisionCoordinatorLegacy = /** @class */ (function () {
  57388. function CollisionCoordinatorLegacy() {
  57389. this._scaledPosition = BABYLON.Vector3.Zero();
  57390. this._scaledVelocity = BABYLON.Vector3.Zero();
  57391. this._finalPosition = BABYLON.Vector3.Zero();
  57392. }
  57393. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  57394. position.divideToRef(collider._radius, this._scaledPosition);
  57395. displacement.divideToRef(collider._radius, this._scaledVelocity);
  57396. collider.collidedMesh = null;
  57397. collider._retry = 0;
  57398. collider._initialVelocity = this._scaledVelocity;
  57399. collider._initialPosition = this._scaledPosition;
  57400. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  57401. this._finalPosition.multiplyInPlace(collider._radius);
  57402. //run the callback
  57403. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  57404. };
  57405. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  57406. this._scene = scene;
  57407. };
  57408. CollisionCoordinatorLegacy.prototype.destroy = function () {
  57409. //Legacy need no destruction method.
  57410. };
  57411. //No update in legacy mode
  57412. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  57413. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  57414. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  57415. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  57416. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  57417. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  57418. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  57419. if (excludedMesh === void 0) { excludedMesh = null; }
  57420. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  57421. if (collider._retry >= maximumRetry) {
  57422. finalPosition.copyFrom(position);
  57423. return;
  57424. }
  57425. // Check if this is a mesh else camera or -1
  57426. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  57427. collider._initialize(position, velocity, closeDistance);
  57428. // Check all meshes
  57429. for (var index = 0; index < this._scene.meshes.length; index++) {
  57430. var mesh = this._scene.meshes[index];
  57431. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  57432. mesh._checkCollision(collider);
  57433. }
  57434. }
  57435. if (!collider.collisionFound) {
  57436. position.addToRef(velocity, finalPosition);
  57437. return;
  57438. }
  57439. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  57440. collider._getResponse(position, velocity);
  57441. }
  57442. if (velocity.length() <= closeDistance) {
  57443. finalPosition.copyFrom(position);
  57444. return;
  57445. }
  57446. collider._retry++;
  57447. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  57448. };
  57449. return CollisionCoordinatorLegacy;
  57450. }());
  57451. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  57452. })(BABYLON || (BABYLON = {}));
  57453. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  57454. var BABYLON;
  57455. (function (BABYLON) {
  57456. /**
  57457. * A particle represents one of the element emitted by a particle system.
  57458. * This is mainly define by its coordinates, direction, velocity and age.
  57459. */
  57460. var Particle = /** @class */ (function () {
  57461. /**
  57462. * Creates a new instance Particle
  57463. * @param particleSystem the particle system the particle belongs to
  57464. */
  57465. function Particle(
  57466. /**
  57467. * The particle system the particle belongs to.
  57468. */
  57469. particleSystem) {
  57470. this.particleSystem = particleSystem;
  57471. /**
  57472. * The world position of the particle in the scene.
  57473. */
  57474. this.position = BABYLON.Vector3.Zero();
  57475. /**
  57476. * The world direction of the particle in the scene.
  57477. */
  57478. this.direction = BABYLON.Vector3.Zero();
  57479. /**
  57480. * The color of the particle.
  57481. */
  57482. this.color = new BABYLON.Color4(0, 0, 0, 0);
  57483. /**
  57484. * The color change of the particle per step.
  57485. */
  57486. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  57487. /**
  57488. * Defines how long will the life of the particle be.
  57489. */
  57490. this.lifeTime = 1.0;
  57491. /**
  57492. * The current age of the particle.
  57493. */
  57494. this.age = 0;
  57495. /**
  57496. * The current size of the particle.
  57497. */
  57498. this.size = 0;
  57499. /**
  57500. * The current scale of the particle.
  57501. */
  57502. this.scale = new BABYLON.Vector2(1, 1);
  57503. /**
  57504. * The current angle of the particle.
  57505. */
  57506. this.angle = 0;
  57507. /**
  57508. * Defines how fast is the angle changing.
  57509. */
  57510. this.angularSpeed = 0;
  57511. /**
  57512. * Defines the cell index used by the particle to be rendered from a sprite.
  57513. */
  57514. this.cellIndex = 0;
  57515. /** @hidden */
  57516. this._attachedSubEmitters = null;
  57517. /** @hidden */
  57518. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  57519. /** @hidden */
  57520. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  57521. /** @hidden */
  57522. this._currentSize1 = 0;
  57523. /** @hidden */
  57524. this._currentSize2 = 0;
  57525. /** @hidden */
  57526. this._currentAngularSpeed1 = 0;
  57527. /** @hidden */
  57528. this._currentAngularSpeed2 = 0;
  57529. /** @hidden */
  57530. this._currentVelocity1 = 0;
  57531. /** @hidden */
  57532. this._currentVelocity2 = 0;
  57533. /** @hidden */
  57534. this._currentLimitVelocity1 = 0;
  57535. /** @hidden */
  57536. this._currentLimitVelocity2 = 0;
  57537. /** @hidden */
  57538. this._currentDrag1 = 0;
  57539. /** @hidden */
  57540. this._currentDrag2 = 0;
  57541. this.id = Particle._Count++;
  57542. if (!this.particleSystem.isAnimationSheetEnabled) {
  57543. return;
  57544. }
  57545. this.updateCellInfoFromSystem();
  57546. }
  57547. Particle.prototype.updateCellInfoFromSystem = function () {
  57548. this.cellIndex = this.particleSystem.startSpriteCellID;
  57549. };
  57550. /**
  57551. * Defines how the sprite cell index is updated for the particle
  57552. */
  57553. Particle.prototype.updateCellIndex = function () {
  57554. var offsetAge = this.age;
  57555. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  57556. if (this.particleSystem.spriteRandomStartCell) {
  57557. if (this._randomCellOffset === undefined) {
  57558. this._randomCellOffset = Math.random() * this.lifeTime;
  57559. }
  57560. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  57561. changeSpeed = 1;
  57562. offsetAge = this._randomCellOffset;
  57563. }
  57564. else {
  57565. offsetAge += this._randomCellOffset;
  57566. }
  57567. }
  57568. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  57569. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  57570. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  57571. };
  57572. /** @hidden */
  57573. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  57574. if (subEmitter.particleSystem.emitter.position) {
  57575. var emitterMesh = subEmitter.particleSystem.emitter;
  57576. emitterMesh.position.copyFrom(this.position);
  57577. if (subEmitter.inheritDirection) {
  57578. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  57579. // Look at using Y as forward
  57580. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  57581. }
  57582. }
  57583. else {
  57584. var emitterPosition = subEmitter.particleSystem.emitter;
  57585. emitterPosition.copyFrom(this.position);
  57586. }
  57587. // Set inheritedVelocityOffset to be used when new particles are created
  57588. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  57589. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  57590. };
  57591. /** @hidden */
  57592. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  57593. var _this = this;
  57594. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  57595. this._attachedSubEmitters.forEach(function (subEmitter) {
  57596. _this._inheritParticleInfoToSubEmitter(subEmitter);
  57597. });
  57598. }
  57599. };
  57600. /** @hidden */
  57601. Particle.prototype._reset = function () {
  57602. this.age = 0;
  57603. this._currentColorGradient = null;
  57604. this._currentSizeGradient = null;
  57605. this._currentAngularSpeedGradient = null;
  57606. this._currentVelocityGradient = null;
  57607. this._currentLimitVelocityGradient = null;
  57608. this._currentDragGradient = null;
  57609. this.cellIndex = this.particleSystem.startSpriteCellID;
  57610. this._randomCellOffset = undefined;
  57611. };
  57612. /**
  57613. * Copy the properties of particle to another one.
  57614. * @param other the particle to copy the information to.
  57615. */
  57616. Particle.prototype.copyTo = function (other) {
  57617. other.position.copyFrom(this.position);
  57618. if (this._initialDirection) {
  57619. if (other._initialDirection) {
  57620. other._initialDirection.copyFrom(this._initialDirection);
  57621. }
  57622. else {
  57623. other._initialDirection = this._initialDirection.clone();
  57624. }
  57625. }
  57626. else {
  57627. other._initialDirection = null;
  57628. }
  57629. other.direction.copyFrom(this.direction);
  57630. other.color.copyFrom(this.color);
  57631. other.colorStep.copyFrom(this.colorStep);
  57632. other.lifeTime = this.lifeTime;
  57633. other.age = this.age;
  57634. other._randomCellOffset = this._randomCellOffset;
  57635. other.size = this.size;
  57636. other.scale.copyFrom(this.scale);
  57637. other.angle = this.angle;
  57638. other.angularSpeed = this.angularSpeed;
  57639. other.particleSystem = this.particleSystem;
  57640. other.cellIndex = this.cellIndex;
  57641. other.id = this.id;
  57642. other._attachedSubEmitters = this._attachedSubEmitters;
  57643. if (this._currentColorGradient) {
  57644. other._currentColorGradient = this._currentColorGradient;
  57645. other._currentColor1.copyFrom(this._currentColor1);
  57646. other._currentColor2.copyFrom(this._currentColor2);
  57647. }
  57648. if (this._currentSizeGradient) {
  57649. other._currentSizeGradient = this._currentSizeGradient;
  57650. other._currentSize1 = this._currentSize1;
  57651. other._currentSize2 = this._currentSize2;
  57652. }
  57653. if (this._currentAngularSpeedGradient) {
  57654. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  57655. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  57656. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  57657. }
  57658. if (this._currentVelocityGradient) {
  57659. other._currentVelocityGradient = this._currentVelocityGradient;
  57660. other._currentVelocity1 = this._currentVelocity1;
  57661. other._currentVelocity2 = this._currentVelocity2;
  57662. }
  57663. if (this._currentLimitVelocityGradient) {
  57664. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  57665. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  57666. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  57667. }
  57668. if (this._currentDragGradient) {
  57669. other._currentDragGradient = this._currentDragGradient;
  57670. other._currentDrag1 = this._currentDrag1;
  57671. other._currentDrag2 = this._currentDrag2;
  57672. }
  57673. if (this.particleSystem.isAnimationSheetEnabled) {
  57674. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  57675. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  57676. }
  57677. if (this.particleSystem.useRampGradients) {
  57678. other.remapData.copyFrom(this.remapData);
  57679. }
  57680. if (this._randomNoiseCoordinates1) {
  57681. if (other._randomNoiseCoordinates1) {
  57682. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  57683. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  57684. }
  57685. else {
  57686. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  57687. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  57688. }
  57689. }
  57690. };
  57691. Particle._Count = 0;
  57692. return Particle;
  57693. }());
  57694. BABYLON.Particle = Particle;
  57695. })(BABYLON || (BABYLON = {}));
  57696. //# sourceMappingURL=babylon.particle.js.map
  57697. var BABYLON;
  57698. (function (BABYLON) {
  57699. /**
  57700. * This represents the base class for particle system in Babylon.
  57701. * 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.
  57702. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  57703. * @example https://doc.babylonjs.com/babylon101/particles
  57704. */
  57705. var BaseParticleSystem = /** @class */ (function () {
  57706. /**
  57707. * Instantiates a particle system.
  57708. * 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.
  57709. * @param name The name of the particle system
  57710. */
  57711. function BaseParticleSystem(name) {
  57712. /**
  57713. * List of animations used by the particle system.
  57714. */
  57715. this.animations = [];
  57716. /**
  57717. * The rendering group used by the Particle system to chose when to render.
  57718. */
  57719. this.renderingGroupId = 0;
  57720. /**
  57721. * The emitter represents the Mesh or position we are attaching the particle system to.
  57722. */
  57723. this.emitter = null;
  57724. /**
  57725. * The maximum number of particles to emit per frame
  57726. */
  57727. this.emitRate = 10;
  57728. /**
  57729. * If you want to launch only a few particles at once, that can be done, as well.
  57730. */
  57731. this.manualEmitCount = -1;
  57732. /**
  57733. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57734. */
  57735. this.updateSpeed = 0.01;
  57736. /**
  57737. * The amount of time the particle system is running (depends of the overall update speed).
  57738. */
  57739. this.targetStopDuration = 0;
  57740. /**
  57741. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  57742. */
  57743. this.disposeOnStop = false;
  57744. /**
  57745. * Minimum power of emitting particles.
  57746. */
  57747. this.minEmitPower = 1;
  57748. /**
  57749. * Maximum power of emitting particles.
  57750. */
  57751. this.maxEmitPower = 1;
  57752. /**
  57753. * Minimum life time of emitting particles.
  57754. */
  57755. this.minLifeTime = 1;
  57756. /**
  57757. * Maximum life time of emitting particles.
  57758. */
  57759. this.maxLifeTime = 1;
  57760. /**
  57761. * Minimum Size of emitting particles.
  57762. */
  57763. this.minSize = 1;
  57764. /**
  57765. * Maximum Size of emitting particles.
  57766. */
  57767. this.maxSize = 1;
  57768. /**
  57769. * Minimum scale of emitting particles on X axis.
  57770. */
  57771. this.minScaleX = 1;
  57772. /**
  57773. * Maximum scale of emitting particles on X axis.
  57774. */
  57775. this.maxScaleX = 1;
  57776. /**
  57777. * Minimum scale of emitting particles on Y axis.
  57778. */
  57779. this.minScaleY = 1;
  57780. /**
  57781. * Maximum scale of emitting particles on Y axis.
  57782. */
  57783. this.maxScaleY = 1;
  57784. /**
  57785. * Gets or sets the minimal initial rotation in radians.
  57786. */
  57787. this.minInitialRotation = 0;
  57788. /**
  57789. * Gets or sets the maximal initial rotation in radians.
  57790. */
  57791. this.maxInitialRotation = 0;
  57792. /**
  57793. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57794. */
  57795. this.minAngularSpeed = 0;
  57796. /**
  57797. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57798. */
  57799. this.maxAngularSpeed = 0;
  57800. /**
  57801. * The layer mask we are rendering the particles through.
  57802. */
  57803. this.layerMask = 0x0FFFFFFF;
  57804. /**
  57805. * This can help using your own shader to render the particle system.
  57806. * The according effect will be created
  57807. */
  57808. this.customShader = null;
  57809. /**
  57810. * By default particle system starts as soon as they are created. This prevents the
  57811. * automatic start to happen and let you decide when to start emitting particles.
  57812. */
  57813. this.preventAutoStart = false;
  57814. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  57815. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  57816. /**
  57817. * Callback triggered when the particle animation is ending.
  57818. */
  57819. this.onAnimationEnd = null;
  57820. /**
  57821. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57822. */
  57823. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57824. /**
  57825. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57826. * to override the particles.
  57827. */
  57828. this.forceDepthWrite = false;
  57829. /** 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 */
  57830. this.preWarmCycles = 0;
  57831. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  57832. this.preWarmStepOffset = 1;
  57833. /**
  57834. * 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)
  57835. */
  57836. this.spriteCellChangeSpeed = 1;
  57837. /**
  57838. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  57839. */
  57840. this.startSpriteCellID = 0;
  57841. /**
  57842. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  57843. */
  57844. this.endSpriteCellID = 0;
  57845. /**
  57846. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  57847. */
  57848. this.spriteCellWidth = 0;
  57849. /**
  57850. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  57851. */
  57852. this.spriteCellHeight = 0;
  57853. /**
  57854. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  57855. */
  57856. this.spriteRandomStartCell = false;
  57857. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  57858. this.translationPivot = new BABYLON.Vector2(0, 0);
  57859. /**
  57860. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  57861. */
  57862. this.beginAnimationOnStart = false;
  57863. /**
  57864. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  57865. */
  57866. this.beginAnimationFrom = 0;
  57867. /**
  57868. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  57869. */
  57870. this.beginAnimationTo = 60;
  57871. /**
  57872. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  57873. */
  57874. this.beginAnimationLoop = false;
  57875. /**
  57876. * You can use gravity if you want to give an orientation to your particles.
  57877. */
  57878. this.gravity = BABYLON.Vector3.Zero();
  57879. this._colorGradients = null;
  57880. this._sizeGradients = null;
  57881. this._lifeTimeGradients = null;
  57882. this._angularSpeedGradients = null;
  57883. this._velocityGradients = null;
  57884. this._limitVelocityGradients = null;
  57885. this._dragGradients = null;
  57886. this._emitRateGradients = null;
  57887. this._startSizeGradients = null;
  57888. this._rampGradients = null;
  57889. this._colorRemapGradients = null;
  57890. this._alphaRemapGradients = null;
  57891. /**
  57892. * Defines the delay in milliseconds before starting the system (0 by default)
  57893. */
  57894. this.startDelay = 0;
  57895. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  57896. this.limitVelocityDamping = 0.4;
  57897. /**
  57898. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  57899. */
  57900. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57901. /**
  57902. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  57903. */
  57904. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57905. /**
  57906. * Color the particle will have at the end of its lifetime
  57907. */
  57908. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  57909. /**
  57910. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  57911. */
  57912. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57913. /** @hidden */
  57914. this._isSubEmitter = false;
  57915. /**
  57916. * Gets or sets the billboard mode to use when isBillboardBased = true.
  57917. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  57918. */
  57919. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  57920. this._isBillboardBased = true;
  57921. /**
  57922. * Local cache of defines for image processing.
  57923. */
  57924. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  57925. this.id = name;
  57926. this.name = name;
  57927. }
  57928. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  57929. /**
  57930. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  57931. */
  57932. get: function () {
  57933. return this._isAnimationSheetEnabled;
  57934. },
  57935. set: function (value) {
  57936. if (this._isAnimationSheetEnabled == value) {
  57937. return;
  57938. }
  57939. this._isAnimationSheetEnabled = value;
  57940. this._reset();
  57941. },
  57942. enumerable: true,
  57943. configurable: true
  57944. });
  57945. /**
  57946. * Get hosting scene
  57947. * @returns the scene
  57948. */
  57949. BaseParticleSystem.prototype.getScene = function () {
  57950. return this._scene;
  57951. };
  57952. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  57953. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  57954. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  57955. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  57956. };
  57957. /**
  57958. * Gets the current list of drag gradients.
  57959. * You must use addDragGradient and removeDragGradient to udpate this list
  57960. * @returns the list of drag gradients
  57961. */
  57962. BaseParticleSystem.prototype.getDragGradients = function () {
  57963. return this._dragGradients;
  57964. };
  57965. /**
  57966. * Gets the current list of limit velocity gradients.
  57967. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  57968. * @returns the list of limit velocity gradients
  57969. */
  57970. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  57971. return this._limitVelocityGradients;
  57972. };
  57973. /**
  57974. * Gets the current list of color gradients.
  57975. * You must use addColorGradient and removeColorGradient to udpate this list
  57976. * @returns the list of color gradients
  57977. */
  57978. BaseParticleSystem.prototype.getColorGradients = function () {
  57979. return this._colorGradients;
  57980. };
  57981. /**
  57982. * Gets the current list of size gradients.
  57983. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57984. * @returns the list of size gradients
  57985. */
  57986. BaseParticleSystem.prototype.getSizeGradients = function () {
  57987. return this._sizeGradients;
  57988. };
  57989. /**
  57990. * Gets the current list of color remap gradients.
  57991. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  57992. * @returns the list of color remap gradients
  57993. */
  57994. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  57995. return this._colorRemapGradients;
  57996. };
  57997. /**
  57998. * Gets the current list of alpha remap gradients.
  57999. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  58000. * @returns the list of alpha remap gradients
  58001. */
  58002. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  58003. return this._alphaRemapGradients;
  58004. };
  58005. /**
  58006. * Gets the current list of life time gradients.
  58007. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  58008. * @returns the list of life time gradients
  58009. */
  58010. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  58011. return this._lifeTimeGradients;
  58012. };
  58013. /**
  58014. * Gets the current list of angular speed gradients.
  58015. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  58016. * @returns the list of angular speed gradients
  58017. */
  58018. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  58019. return this._angularSpeedGradients;
  58020. };
  58021. /**
  58022. * Gets the current list of velocity gradients.
  58023. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  58024. * @returns the list of velocity gradients
  58025. */
  58026. BaseParticleSystem.prototype.getVelocityGradients = function () {
  58027. return this._velocityGradients;
  58028. };
  58029. /**
  58030. * Gets the current list of start size gradients.
  58031. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  58032. * @returns the list of start size gradients
  58033. */
  58034. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  58035. return this._startSizeGradients;
  58036. };
  58037. /**
  58038. * Gets the current list of emit rate gradients.
  58039. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  58040. * @returns the list of emit rate gradients
  58041. */
  58042. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  58043. return this._emitRateGradients;
  58044. };
  58045. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  58046. /**
  58047. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58048. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58049. */
  58050. get: function () {
  58051. if (this.particleEmitterType.direction1) {
  58052. return this.particleEmitterType.direction1;
  58053. }
  58054. return BABYLON.Vector3.Zero();
  58055. },
  58056. set: function (value) {
  58057. if (this.particleEmitterType.direction1) {
  58058. this.particleEmitterType.direction1 = value;
  58059. }
  58060. },
  58061. enumerable: true,
  58062. configurable: true
  58063. });
  58064. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  58065. /**
  58066. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58067. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58068. */
  58069. get: function () {
  58070. if (this.particleEmitterType.direction2) {
  58071. return this.particleEmitterType.direction2;
  58072. }
  58073. return BABYLON.Vector3.Zero();
  58074. },
  58075. set: function (value) {
  58076. if (this.particleEmitterType.direction2) {
  58077. this.particleEmitterType.direction2 = value;
  58078. }
  58079. },
  58080. enumerable: true,
  58081. configurable: true
  58082. });
  58083. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  58084. /**
  58085. * 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.
  58086. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58087. */
  58088. get: function () {
  58089. if (this.particleEmitterType.minEmitBox) {
  58090. return this.particleEmitterType.minEmitBox;
  58091. }
  58092. return BABYLON.Vector3.Zero();
  58093. },
  58094. set: function (value) {
  58095. if (this.particleEmitterType.minEmitBox) {
  58096. this.particleEmitterType.minEmitBox = value;
  58097. }
  58098. },
  58099. enumerable: true,
  58100. configurable: true
  58101. });
  58102. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  58103. /**
  58104. * 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.
  58105. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58106. */
  58107. get: function () {
  58108. if (this.particleEmitterType.maxEmitBox) {
  58109. return this.particleEmitterType.maxEmitBox;
  58110. }
  58111. return BABYLON.Vector3.Zero();
  58112. },
  58113. set: function (value) {
  58114. if (this.particleEmitterType.maxEmitBox) {
  58115. this.particleEmitterType.maxEmitBox = value;
  58116. }
  58117. },
  58118. enumerable: true,
  58119. configurable: true
  58120. });
  58121. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  58122. /**
  58123. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  58124. */
  58125. get: function () {
  58126. return this._isBillboardBased;
  58127. },
  58128. set: function (value) {
  58129. if (this._isBillboardBased === value) {
  58130. return;
  58131. }
  58132. this._isBillboardBased = value;
  58133. this._reset();
  58134. },
  58135. enumerable: true,
  58136. configurable: true
  58137. });
  58138. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  58139. /**
  58140. * Gets the image processing configuration used either in this material.
  58141. */
  58142. get: function () {
  58143. return this._imageProcessingConfiguration;
  58144. },
  58145. /**
  58146. * Sets the Default image processing configuration used either in the this material.
  58147. *
  58148. * If sets to null, the scene one is in use.
  58149. */
  58150. set: function (value) {
  58151. this._attachImageProcessingConfiguration(value);
  58152. },
  58153. enumerable: true,
  58154. configurable: true
  58155. });
  58156. /**
  58157. * Attaches a new image processing configuration to the Standard Material.
  58158. * @param configuration
  58159. */
  58160. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  58161. if (configuration === this._imageProcessingConfiguration) {
  58162. return;
  58163. }
  58164. // Pick the scene configuration if needed.
  58165. if (!configuration) {
  58166. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  58167. }
  58168. else {
  58169. this._imageProcessingConfiguration = configuration;
  58170. }
  58171. };
  58172. /** @hidden */
  58173. BaseParticleSystem.prototype._reset = function () {
  58174. };
  58175. /** @hidden */
  58176. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  58177. if (!gradients) {
  58178. return this;
  58179. }
  58180. var index = 0;
  58181. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  58182. var valueGradient = gradients_1[_i];
  58183. if (valueGradient.gradient === gradient) {
  58184. gradients.splice(index, 1);
  58185. break;
  58186. }
  58187. index++;
  58188. }
  58189. if (texture) {
  58190. texture.dispose();
  58191. }
  58192. return this;
  58193. };
  58194. /**
  58195. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  58196. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  58197. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  58198. * @returns the emitter
  58199. */
  58200. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  58201. var particleEmitter = new BABYLON.PointParticleEmitter();
  58202. particleEmitter.direction1 = direction1;
  58203. particleEmitter.direction2 = direction2;
  58204. this.particleEmitterType = particleEmitter;
  58205. return particleEmitter;
  58206. };
  58207. /**
  58208. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  58209. * @param radius The radius of the hemisphere to emit from
  58210. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  58211. * @returns the emitter
  58212. */
  58213. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  58214. if (radius === void 0) { radius = 1; }
  58215. if (radiusRange === void 0) { radiusRange = 1; }
  58216. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  58217. this.particleEmitterType = particleEmitter;
  58218. return particleEmitter;
  58219. };
  58220. /**
  58221. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  58222. * @param radius The radius of the sphere to emit from
  58223. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  58224. * @returns the emitter
  58225. */
  58226. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  58227. if (radius === void 0) { radius = 1; }
  58228. if (radiusRange === void 0) { radiusRange = 1; }
  58229. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  58230. this.particleEmitterType = particleEmitter;
  58231. return particleEmitter;
  58232. };
  58233. /**
  58234. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  58235. * @param radius The radius of the sphere to emit from
  58236. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  58237. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  58238. * @returns the emitter
  58239. */
  58240. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  58241. if (radius === void 0) { radius = 1; }
  58242. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  58243. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  58244. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  58245. this.particleEmitterType = particleEmitter;
  58246. return particleEmitter;
  58247. };
  58248. /**
  58249. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  58250. * @param radius The radius of the emission cylinder
  58251. * @param height The height of the emission cylinder
  58252. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  58253. * @param directionRandomizer How much to randomize the particle direction [0-1]
  58254. * @returns the emitter
  58255. */
  58256. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  58257. if (radius === void 0) { radius = 1; }
  58258. if (height === void 0) { height = 1; }
  58259. if (radiusRange === void 0) { radiusRange = 1; }
  58260. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58261. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  58262. this.particleEmitterType = particleEmitter;
  58263. return particleEmitter;
  58264. };
  58265. /**
  58266. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  58267. * @param radius The radius of the cylinder to emit from
  58268. * @param height The height of the emission cylinder
  58269. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58270. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  58271. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  58272. * @returns the emitter
  58273. */
  58274. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  58275. if (radius === void 0) { radius = 1; }
  58276. if (height === void 0) { height = 1; }
  58277. if (radiusRange === void 0) { radiusRange = 1; }
  58278. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  58279. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  58280. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  58281. this.particleEmitterType = particleEmitter;
  58282. return particleEmitter;
  58283. };
  58284. /**
  58285. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  58286. * @param radius The radius of the cone to emit from
  58287. * @param angle The base angle of the cone
  58288. * @returns the emitter
  58289. */
  58290. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  58291. if (radius === void 0) { radius = 1; }
  58292. if (angle === void 0) { angle = Math.PI / 4; }
  58293. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  58294. this.particleEmitterType = particleEmitter;
  58295. return particleEmitter;
  58296. };
  58297. /**
  58298. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  58299. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  58300. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  58301. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  58302. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  58303. * @returns the emitter
  58304. */
  58305. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  58306. var particleEmitter = new BABYLON.BoxParticleEmitter();
  58307. this.particleEmitterType = particleEmitter;
  58308. this.direction1 = direction1;
  58309. this.direction2 = direction2;
  58310. this.minEmitBox = minEmitBox;
  58311. this.maxEmitBox = maxEmitBox;
  58312. return particleEmitter;
  58313. };
  58314. /**
  58315. * Source color is added to the destination color without alpha affecting the result
  58316. */
  58317. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  58318. /**
  58319. * Blend current color and particle color using particle’s alpha
  58320. */
  58321. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  58322. /**
  58323. * Add current color and particle color multiplied by particle’s alpha
  58324. */
  58325. BaseParticleSystem.BLENDMODE_ADD = 2;
  58326. /**
  58327. * Multiply current color with particle color
  58328. */
  58329. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  58330. /**
  58331. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  58332. */
  58333. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  58334. return BaseParticleSystem;
  58335. }());
  58336. BABYLON.BaseParticleSystem = BaseParticleSystem;
  58337. })(BABYLON || (BABYLON = {}));
  58338. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  58339. var BABYLON;
  58340. (function (BABYLON) {
  58341. /**
  58342. * This represents a particle system in Babylon.
  58343. * 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.
  58344. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  58345. * @example https://doc.babylonjs.com/babylon101/particles
  58346. */
  58347. var ParticleSystem = /** @class */ (function (_super) {
  58348. __extends(ParticleSystem, _super);
  58349. /**
  58350. * Instantiates a particle system.
  58351. * 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.
  58352. * @param name The name of the particle system
  58353. * @param capacity The max number of particles alive at the same time
  58354. * @param scene The scene the particle system belongs to
  58355. * @param customEffect a custom effect used to change the way particles are rendered by default
  58356. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  58357. * @param epsilon Offset used to render the particles
  58358. */
  58359. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  58360. if (customEffect === void 0) { customEffect = null; }
  58361. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58362. if (epsilon === void 0) { epsilon = 0.01; }
  58363. var _this = _super.call(this, name) || this;
  58364. /**
  58365. * @hidden
  58366. */
  58367. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  58368. /**
  58369. * An event triggered when the system is disposed
  58370. */
  58371. _this.onDisposeObservable = new BABYLON.Observable();
  58372. _this._particles = new Array();
  58373. _this._stockParticles = new Array();
  58374. _this._newPartsExcess = 0;
  58375. _this._vertexBuffers = {};
  58376. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  58377. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  58378. _this._scaledDirection = BABYLON.Vector3.Zero();
  58379. _this._scaledGravity = BABYLON.Vector3.Zero();
  58380. _this._currentRenderId = -1;
  58381. _this._useInstancing = false;
  58382. _this._started = false;
  58383. _this._stopped = false;
  58384. _this._actualFrame = 0;
  58385. /** @hidden */
  58386. _this._currentEmitRate1 = 0;
  58387. /** @hidden */
  58388. _this._currentEmitRate2 = 0;
  58389. /** @hidden */
  58390. _this._currentStartSize1 = 0;
  58391. /** @hidden */
  58392. _this._currentStartSize2 = 0;
  58393. _this._rawTextureWidth = 256;
  58394. _this._useRampGradients = false;
  58395. /**
  58396. * @hidden
  58397. * If the particle systems emitter should be disposed when the particle system is disposed
  58398. */
  58399. _this._disposeEmitterOnDispose = false;
  58400. // start of sub system methods
  58401. /**
  58402. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  58403. * Its lifetime will start back at 0.
  58404. */
  58405. _this.recycleParticle = function (particle) {
  58406. // move particle from activeParticle list to stock particles
  58407. var lastParticle = _this._particles.pop();
  58408. if (lastParticle !== particle) {
  58409. lastParticle.copyTo(particle);
  58410. }
  58411. _this._stockParticles.push(lastParticle);
  58412. };
  58413. _this._createParticle = function () {
  58414. var particle;
  58415. if (_this._stockParticles.length !== 0) {
  58416. particle = _this._stockParticles.pop();
  58417. particle._reset();
  58418. }
  58419. else {
  58420. particle = new BABYLON.Particle(_this);
  58421. }
  58422. // Attach emitters
  58423. if (_this._subEmitters && _this._subEmitters.length > 0) {
  58424. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  58425. particle._attachedSubEmitters = [];
  58426. subEmitters.forEach(function (subEmitter) {
  58427. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  58428. var newEmitter = subEmitter.clone();
  58429. particle._attachedSubEmitters.push(newEmitter);
  58430. newEmitter.particleSystem.start();
  58431. }
  58432. });
  58433. }
  58434. return particle;
  58435. };
  58436. _this._emitFromParticle = function (particle) {
  58437. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  58438. return;
  58439. }
  58440. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  58441. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  58442. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  58443. var subSystem = subEmitter.clone();
  58444. particle._inheritParticleInfoToSubEmitter(subSystem);
  58445. subSystem.particleSystem._rootParticleSystem = _this;
  58446. _this.activeSubSystems.push(subSystem.particleSystem);
  58447. subSystem.particleSystem.start();
  58448. }
  58449. });
  58450. };
  58451. _this._capacity = capacity;
  58452. _this._epsilon = epsilon;
  58453. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  58454. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58455. // Setup the default processing configuration to the scene.
  58456. _this._attachImageProcessingConfiguration(null);
  58457. _this._customEffect = customEffect;
  58458. _this._scene.particleSystems.push(_this);
  58459. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  58460. _this._createIndexBuffer();
  58461. _this._createVertexBuffers();
  58462. // Default emitter type
  58463. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  58464. // Update
  58465. _this.updateFunction = function (particles) {
  58466. var noiseTextureSize = null;
  58467. var noiseTextureData = null;
  58468. if (_this.noiseTexture) { // We need to get texture data back to CPU
  58469. noiseTextureSize = _this.noiseTexture.getSize();
  58470. noiseTextureData = (_this.noiseTexture.getContent());
  58471. }
  58472. var _loop_1 = function () {
  58473. particle = particles[index];
  58474. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  58475. var previousAge = particle.age;
  58476. particle.age += scaledUpdateSpeed;
  58477. // Evaluate step to death
  58478. if (particle.age > particle.lifeTime) {
  58479. var diff = particle.age - previousAge;
  58480. var oldDiff = particle.lifeTime - previousAge;
  58481. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  58482. particle.age = particle.lifeTime;
  58483. }
  58484. var ratio = particle.age / particle.lifeTime;
  58485. // Color
  58486. if (_this._colorGradients && _this._colorGradients.length > 0) {
  58487. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  58488. if (currentGradient !== particle._currentColorGradient) {
  58489. particle._currentColor1.copyFrom(particle._currentColor2);
  58490. nextGradient.getColorToRef(particle._currentColor2);
  58491. particle._currentColorGradient = currentGradient;
  58492. }
  58493. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  58494. });
  58495. }
  58496. else {
  58497. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  58498. particle.color.addInPlace(_this._scaledColorStep);
  58499. if (particle.color.a < 0) {
  58500. particle.color.a = 0;
  58501. }
  58502. }
  58503. // Angular speed
  58504. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  58505. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  58506. if (currentGradient !== particle._currentAngularSpeedGradient) {
  58507. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  58508. particle._currentAngularSpeed2 = nextGradient.getFactor();
  58509. particle._currentAngularSpeedGradient = currentGradient;
  58510. }
  58511. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  58512. });
  58513. }
  58514. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  58515. // Direction
  58516. var directionScale = scaledUpdateSpeed;
  58517. /// Velocity
  58518. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  58519. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  58520. if (currentGradient !== particle._currentVelocityGradient) {
  58521. particle._currentVelocity1 = particle._currentVelocity2;
  58522. particle._currentVelocity2 = nextGradient.getFactor();
  58523. particle._currentVelocityGradient = currentGradient;
  58524. }
  58525. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  58526. });
  58527. }
  58528. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  58529. /// Limit velocity
  58530. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  58531. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  58532. if (currentGradient !== particle._currentLimitVelocityGradient) {
  58533. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  58534. particle._currentLimitVelocity2 = nextGradient.getFactor();
  58535. particle._currentLimitVelocityGradient = currentGradient;
  58536. }
  58537. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  58538. var currentVelocity = particle.direction.length();
  58539. if (currentVelocity > limitVelocity) {
  58540. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  58541. }
  58542. });
  58543. }
  58544. /// Drag
  58545. if (_this._dragGradients && _this._dragGradients.length > 0) {
  58546. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  58547. if (currentGradient !== particle._currentDragGradient) {
  58548. particle._currentDrag1 = particle._currentDrag2;
  58549. particle._currentDrag2 = nextGradient.getFactor();
  58550. particle._currentDragGradient = currentGradient;
  58551. }
  58552. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  58553. _this._scaledDirection.scaleInPlace(1.0 - drag);
  58554. });
  58555. }
  58556. particle.position.addInPlace(_this._scaledDirection);
  58557. // Noise
  58558. if (noiseTextureData && noiseTextureSize) {
  58559. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  58560. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  58561. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  58562. var force = BABYLON.Tmp.Vector3[0];
  58563. var scaledForce = BABYLON.Tmp.Vector3[1];
  58564. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  58565. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  58566. particle.direction.addInPlace(scaledForce);
  58567. }
  58568. // Gravity
  58569. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  58570. particle.direction.addInPlace(_this._scaledGravity);
  58571. // Size
  58572. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  58573. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  58574. if (currentGradient !== particle._currentSizeGradient) {
  58575. particle._currentSize1 = particle._currentSize2;
  58576. particle._currentSize2 = nextGradient.getFactor();
  58577. particle._currentSizeGradient = currentGradient;
  58578. }
  58579. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  58580. });
  58581. }
  58582. // Remap data
  58583. if (_this._useRampGradients) {
  58584. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  58585. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  58586. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  58587. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  58588. particle.remapData.x = min;
  58589. particle.remapData.y = max - min;
  58590. });
  58591. }
  58592. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  58593. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  58594. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  58595. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  58596. particle.remapData.z = min;
  58597. particle.remapData.w = max - min;
  58598. });
  58599. }
  58600. }
  58601. if (_this._isAnimationSheetEnabled) {
  58602. particle.updateCellIndex();
  58603. }
  58604. // Update the position of the attached sub-emitters to match their attached particle
  58605. particle._inheritParticleInfoToSubEmitters();
  58606. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  58607. _this._emitFromParticle(particle);
  58608. if (particle._attachedSubEmitters) {
  58609. particle._attachedSubEmitters.forEach(function (subEmitter) {
  58610. subEmitter.particleSystem.disposeOnStop = true;
  58611. subEmitter.particleSystem.stop();
  58612. });
  58613. particle._attachedSubEmitters = null;
  58614. }
  58615. _this.recycleParticle(particle);
  58616. index--;
  58617. return "continue";
  58618. }
  58619. };
  58620. var particle;
  58621. for (var index = 0; index < particles.length; index++) {
  58622. _loop_1();
  58623. }
  58624. };
  58625. return _this;
  58626. }
  58627. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  58628. /**
  58629. * Sets a callback that will be triggered when the system is disposed
  58630. */
  58631. set: function (callback) {
  58632. if (this._onDisposeObserver) {
  58633. this.onDisposeObservable.remove(this._onDisposeObserver);
  58634. }
  58635. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  58636. },
  58637. enumerable: true,
  58638. configurable: true
  58639. });
  58640. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  58641. /** Gets or sets a boolean indicating that ramp gradients must be used
  58642. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  58643. */
  58644. get: function () {
  58645. return this._useRampGradients;
  58646. },
  58647. set: function (value) {
  58648. if (this._useRampGradients === value) {
  58649. return;
  58650. }
  58651. this._useRampGradients = value;
  58652. this._resetEffect();
  58653. },
  58654. enumerable: true,
  58655. configurable: true
  58656. });
  58657. Object.defineProperty(ParticleSystem.prototype, "particles", {
  58658. //end of Sub-emitter
  58659. /**
  58660. * Gets the current list of active particles
  58661. */
  58662. get: function () {
  58663. return this._particles;
  58664. },
  58665. enumerable: true,
  58666. configurable: true
  58667. });
  58668. /**
  58669. * Returns the string "ParticleSystem"
  58670. * @returns a string containing the class name
  58671. */
  58672. ParticleSystem.prototype.getClassName = function () {
  58673. return "ParticleSystem";
  58674. };
  58675. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  58676. var newGradient = new BABYLON.FactorGradient();
  58677. newGradient.gradient = gradient;
  58678. newGradient.factor1 = factor;
  58679. newGradient.factor2 = factor2;
  58680. factorGradients.push(newGradient);
  58681. factorGradients.sort(function (a, b) {
  58682. if (a.gradient < b.gradient) {
  58683. return -1;
  58684. }
  58685. else if (a.gradient > b.gradient) {
  58686. return 1;
  58687. }
  58688. return 0;
  58689. });
  58690. };
  58691. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  58692. if (!factorGradients) {
  58693. return;
  58694. }
  58695. var index = 0;
  58696. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  58697. var factorGradient = factorGradients_1[_i];
  58698. if (factorGradient.gradient === gradient) {
  58699. factorGradients.splice(index, 1);
  58700. break;
  58701. }
  58702. index++;
  58703. }
  58704. };
  58705. /**
  58706. * Adds a new life time gradient
  58707. * @param gradient defines the gradient to use (between 0 and 1)
  58708. * @param factor defines the life time factor to affect to the specified gradient
  58709. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58710. * @returns the current particle system
  58711. */
  58712. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  58713. if (!this._lifeTimeGradients) {
  58714. this._lifeTimeGradients = [];
  58715. }
  58716. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  58717. return this;
  58718. };
  58719. /**
  58720. * Remove a specific life time gradient
  58721. * @param gradient defines the gradient to remove
  58722. * @returns the current particle system
  58723. */
  58724. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  58725. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  58726. return this;
  58727. };
  58728. /**
  58729. * Adds a new size gradient
  58730. * @param gradient defines the gradient to use (between 0 and 1)
  58731. * @param factor defines the size factor to affect to the specified gradient
  58732. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58733. * @returns the current particle system
  58734. */
  58735. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  58736. if (!this._sizeGradients) {
  58737. this._sizeGradients = [];
  58738. }
  58739. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  58740. return this;
  58741. };
  58742. /**
  58743. * Remove a specific size gradient
  58744. * @param gradient defines the gradient to remove
  58745. * @returns the current particle system
  58746. */
  58747. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  58748. this._removeFactorGradient(this._sizeGradients, gradient);
  58749. return this;
  58750. };
  58751. /**
  58752. * Adds a new color remap gradient
  58753. * @param gradient defines the gradient to use (between 0 and 1)
  58754. * @param min defines the color remap minimal range
  58755. * @param max defines the color remap maximal range
  58756. * @returns the current particle system
  58757. */
  58758. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  58759. if (!this._colorRemapGradients) {
  58760. this._colorRemapGradients = [];
  58761. }
  58762. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  58763. return this;
  58764. };
  58765. /**
  58766. * Remove a specific color remap gradient
  58767. * @param gradient defines the gradient to remove
  58768. * @returns the current particle system
  58769. */
  58770. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  58771. this._removeFactorGradient(this._colorRemapGradients, gradient);
  58772. return this;
  58773. };
  58774. /**
  58775. * Adds a new alpha remap gradient
  58776. * @param gradient defines the gradient to use (between 0 and 1)
  58777. * @param min defines the alpha remap minimal range
  58778. * @param max defines the alpha remap maximal range
  58779. * @returns the current particle system
  58780. */
  58781. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  58782. if (!this._alphaRemapGradients) {
  58783. this._alphaRemapGradients = [];
  58784. }
  58785. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  58786. return this;
  58787. };
  58788. /**
  58789. * Remove a specific alpha remap gradient
  58790. * @param gradient defines the gradient to remove
  58791. * @returns the current particle system
  58792. */
  58793. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  58794. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  58795. return this;
  58796. };
  58797. /**
  58798. * Adds a new angular speed gradient
  58799. * @param gradient defines the gradient to use (between 0 and 1)
  58800. * @param factor defines the angular speed to affect to the specified gradient
  58801. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58802. * @returns the current particle system
  58803. */
  58804. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  58805. if (!this._angularSpeedGradients) {
  58806. this._angularSpeedGradients = [];
  58807. }
  58808. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  58809. return this;
  58810. };
  58811. /**
  58812. * Remove a specific angular speed gradient
  58813. * @param gradient defines the gradient to remove
  58814. * @returns the current particle system
  58815. */
  58816. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  58817. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  58818. return this;
  58819. };
  58820. /**
  58821. * Adds a new velocity gradient
  58822. * @param gradient defines the gradient to use (between 0 and 1)
  58823. * @param factor defines the velocity to affect to the specified gradient
  58824. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58825. * @returns the current particle system
  58826. */
  58827. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  58828. if (!this._velocityGradients) {
  58829. this._velocityGradients = [];
  58830. }
  58831. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  58832. return this;
  58833. };
  58834. /**
  58835. * Remove a specific velocity gradient
  58836. * @param gradient defines the gradient to remove
  58837. * @returns the current particle system
  58838. */
  58839. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  58840. this._removeFactorGradient(this._velocityGradients, gradient);
  58841. return this;
  58842. };
  58843. /**
  58844. * Adds a new limit velocity gradient
  58845. * @param gradient defines the gradient to use (between 0 and 1)
  58846. * @param factor defines the limit velocity value to affect to the specified gradient
  58847. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58848. * @returns the current particle system
  58849. */
  58850. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  58851. if (!this._limitVelocityGradients) {
  58852. this._limitVelocityGradients = [];
  58853. }
  58854. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  58855. return this;
  58856. };
  58857. /**
  58858. * Remove a specific limit velocity gradient
  58859. * @param gradient defines the gradient to remove
  58860. * @returns the current particle system
  58861. */
  58862. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  58863. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  58864. return this;
  58865. };
  58866. /**
  58867. * Adds a new drag gradient
  58868. * @param gradient defines the gradient to use (between 0 and 1)
  58869. * @param factor defines the drag value to affect to the specified gradient
  58870. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58871. * @returns the current particle system
  58872. */
  58873. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  58874. if (!this._dragGradients) {
  58875. this._dragGradients = [];
  58876. }
  58877. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  58878. return this;
  58879. };
  58880. /**
  58881. * Remove a specific drag gradient
  58882. * @param gradient defines the gradient to remove
  58883. * @returns the current particle system
  58884. */
  58885. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  58886. this._removeFactorGradient(this._dragGradients, gradient);
  58887. return this;
  58888. };
  58889. /**
  58890. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  58891. * @param gradient defines the gradient to use (between 0 and 1)
  58892. * @param factor defines the emit rate value to affect to the specified gradient
  58893. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58894. * @returns the current particle system
  58895. */
  58896. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  58897. if (!this._emitRateGradients) {
  58898. this._emitRateGradients = [];
  58899. }
  58900. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  58901. if (!this._currentEmitRateGradient) {
  58902. this._currentEmitRateGradient = this._emitRateGradients[0];
  58903. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  58904. this._currentEmitRate2 = this._currentEmitRate1;
  58905. }
  58906. if (this._emitRateGradients.length === 2) {
  58907. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  58908. }
  58909. return this;
  58910. };
  58911. /**
  58912. * Remove a specific emit rate gradient
  58913. * @param gradient defines the gradient to remove
  58914. * @returns the current particle system
  58915. */
  58916. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  58917. this._removeFactorGradient(this._emitRateGradients, gradient);
  58918. return this;
  58919. };
  58920. /**
  58921. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  58922. * @param gradient defines the gradient to use (between 0 and 1)
  58923. * @param factor defines the start size value to affect to the specified gradient
  58924. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  58925. * @returns the current particle system
  58926. */
  58927. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  58928. if (!this._startSizeGradients) {
  58929. this._startSizeGradients = [];
  58930. }
  58931. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  58932. if (!this._currentStartSizeGradient) {
  58933. this._currentStartSizeGradient = this._startSizeGradients[0];
  58934. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  58935. this._currentStartSize2 = this._currentStartSize1;
  58936. }
  58937. if (this._startSizeGradients.length === 2) {
  58938. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  58939. }
  58940. return this;
  58941. };
  58942. /**
  58943. * Remove a specific start size gradient
  58944. * @param gradient defines the gradient to remove
  58945. * @returns the current particle system
  58946. */
  58947. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  58948. this._removeFactorGradient(this._emitRateGradients, gradient);
  58949. return this;
  58950. };
  58951. ParticleSystem.prototype._createRampGradientTexture = function () {
  58952. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  58953. return;
  58954. }
  58955. var data = new Uint8Array(this._rawTextureWidth * 4);
  58956. var tmpColor = BABYLON.Tmp.Color3[0];
  58957. for (var x = 0; x < this._rawTextureWidth; x++) {
  58958. var ratio = x / this._rawTextureWidth;
  58959. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  58960. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  58961. data[x * 4] = tmpColor.r * 255;
  58962. data[x * 4 + 1] = tmpColor.g * 255;
  58963. data[x * 4 + 2] = tmpColor.b * 255;
  58964. data[x * 4 + 3] = 255;
  58965. });
  58966. }
  58967. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58968. };
  58969. /**
  58970. * Gets the current list of ramp gradients.
  58971. * You must use addRampGradient and removeRampGradient to udpate this list
  58972. * @returns the list of ramp gradients
  58973. */
  58974. ParticleSystem.prototype.getRampGradients = function () {
  58975. return this._rampGradients;
  58976. };
  58977. /**
  58978. * Adds a new ramp gradient used to remap particle colors
  58979. * @param gradient defines the gradient to use (between 0 and 1)
  58980. * @param color defines the color to affect to the specified gradient
  58981. * @returns the current particle system
  58982. */
  58983. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  58984. if (!this._rampGradients) {
  58985. this._rampGradients = [];
  58986. }
  58987. var rampGradient = new BABYLON.Color3Gradient();
  58988. rampGradient.gradient = gradient;
  58989. rampGradient.color = color;
  58990. this._rampGradients.push(rampGradient);
  58991. this._rampGradients.sort(function (a, b) {
  58992. if (a.gradient < b.gradient) {
  58993. return -1;
  58994. }
  58995. else if (a.gradient > b.gradient) {
  58996. return 1;
  58997. }
  58998. return 0;
  58999. });
  59000. if (this._rampGradientsTexture) {
  59001. this._rampGradientsTexture.dispose();
  59002. this._rampGradientsTexture = null;
  59003. }
  59004. this._createRampGradientTexture();
  59005. return this;
  59006. };
  59007. /**
  59008. * Remove a specific ramp gradient
  59009. * @param gradient defines the gradient to remove
  59010. * @returns the current particle system
  59011. */
  59012. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  59013. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  59014. this._rampGradientsTexture = null;
  59015. if (this._rampGradients && this._rampGradients.length > 0) {
  59016. this._createRampGradientTexture();
  59017. }
  59018. return this;
  59019. };
  59020. /**
  59021. * Adds a new color gradient
  59022. * @param gradient defines the gradient to use (between 0 and 1)
  59023. * @param color1 defines the color to affect to the specified gradient
  59024. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  59025. * @returns this particle system
  59026. */
  59027. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  59028. if (!this._colorGradients) {
  59029. this._colorGradients = [];
  59030. }
  59031. var colorGradient = new BABYLON.ColorGradient();
  59032. colorGradient.gradient = gradient;
  59033. colorGradient.color1 = color1;
  59034. colorGradient.color2 = color2;
  59035. this._colorGradients.push(colorGradient);
  59036. this._colorGradients.sort(function (a, b) {
  59037. if (a.gradient < b.gradient) {
  59038. return -1;
  59039. }
  59040. else if (a.gradient > b.gradient) {
  59041. return 1;
  59042. }
  59043. return 0;
  59044. });
  59045. return this;
  59046. };
  59047. /**
  59048. * Remove a specific color gradient
  59049. * @param gradient defines the gradient to remove
  59050. * @returns this particle system
  59051. */
  59052. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  59053. if (!this._colorGradients) {
  59054. return this;
  59055. }
  59056. var index = 0;
  59057. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  59058. var colorGradient = _a[_i];
  59059. if (colorGradient.gradient === gradient) {
  59060. this._colorGradients.splice(index, 1);
  59061. break;
  59062. }
  59063. index++;
  59064. }
  59065. return this;
  59066. };
  59067. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  59068. u = Math.abs(u) * 0.5 + 0.5;
  59069. v = Math.abs(v) * 0.5 + 0.5;
  59070. var wrappedU = ((u * width) % width) | 0;
  59071. var wrappedV = ((v * height) % height) | 0;
  59072. var position = (wrappedU + wrappedV * width) * 4;
  59073. return pixels[position] / 255;
  59074. };
  59075. ParticleSystem.prototype._reset = function () {
  59076. this._resetEffect();
  59077. };
  59078. ParticleSystem.prototype._resetEffect = function () {
  59079. if (this._vertexBuffer) {
  59080. this._vertexBuffer.dispose();
  59081. this._vertexBuffer = null;
  59082. }
  59083. if (this._spriteBuffer) {
  59084. this._spriteBuffer.dispose();
  59085. this._spriteBuffer = null;
  59086. }
  59087. this._createVertexBuffers();
  59088. };
  59089. ParticleSystem.prototype._createVertexBuffers = function () {
  59090. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  59091. if (this._isAnimationSheetEnabled) {
  59092. this._vertexBufferSize += 1;
  59093. }
  59094. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59095. this._vertexBufferSize += 3;
  59096. }
  59097. if (this._useRampGradients) {
  59098. this._vertexBufferSize += 4;
  59099. }
  59100. var engine = this._scene.getEngine();
  59101. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  59102. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  59103. var dataOffset = 0;
  59104. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  59105. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  59106. dataOffset += 3;
  59107. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  59108. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  59109. dataOffset += 4;
  59110. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  59111. this._vertexBuffers["angle"] = options;
  59112. dataOffset += 1;
  59113. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  59114. this._vertexBuffers["size"] = size;
  59115. dataOffset += 2;
  59116. if (this._isAnimationSheetEnabled) {
  59117. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  59118. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  59119. dataOffset += 1;
  59120. }
  59121. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59122. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  59123. this._vertexBuffers["direction"] = directionBuffer;
  59124. dataOffset += 3;
  59125. }
  59126. if (this._useRampGradients) {
  59127. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  59128. this._vertexBuffers["remapData"] = rampDataBuffer;
  59129. dataOffset += 4;
  59130. }
  59131. var offsets;
  59132. if (this._useInstancing) {
  59133. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  59134. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  59135. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  59136. }
  59137. else {
  59138. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  59139. dataOffset += 2;
  59140. }
  59141. this._vertexBuffers["offset"] = offsets;
  59142. };
  59143. ParticleSystem.prototype._createIndexBuffer = function () {
  59144. if (this._useInstancing) {
  59145. return;
  59146. }
  59147. var indices = [];
  59148. var index = 0;
  59149. for (var count = 0; count < this._capacity; count++) {
  59150. indices.push(index);
  59151. indices.push(index + 1);
  59152. indices.push(index + 2);
  59153. indices.push(index);
  59154. indices.push(index + 2);
  59155. indices.push(index + 3);
  59156. index += 4;
  59157. }
  59158. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  59159. };
  59160. /**
  59161. * Gets the maximum number of particles active at the same time.
  59162. * @returns The max number of active particles.
  59163. */
  59164. ParticleSystem.prototype.getCapacity = function () {
  59165. return this._capacity;
  59166. };
  59167. /**
  59168. * Gets whether there are still active particles in the system.
  59169. * @returns True if it is alive, otherwise false.
  59170. */
  59171. ParticleSystem.prototype.isAlive = function () {
  59172. return this._alive;
  59173. };
  59174. /**
  59175. * Gets if the system has been started. (Note: this will still be true after stop is called)
  59176. * @returns True if it has been started, otherwise false.
  59177. */
  59178. ParticleSystem.prototype.isStarted = function () {
  59179. return this._started;
  59180. };
  59181. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  59182. var _this = this;
  59183. this._subEmitters = new Array();
  59184. if (this.subEmitters) {
  59185. this.subEmitters.forEach(function (subEmitter) {
  59186. if (subEmitter instanceof ParticleSystem) {
  59187. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  59188. }
  59189. else if (subEmitter instanceof BABYLON.SubEmitter) {
  59190. _this._subEmitters.push([subEmitter]);
  59191. }
  59192. else if (subEmitter instanceof Array) {
  59193. _this._subEmitters.push(subEmitter);
  59194. }
  59195. });
  59196. }
  59197. };
  59198. /**
  59199. * Starts the particle system and begins to emit
  59200. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  59201. */
  59202. ParticleSystem.prototype.start = function (delay) {
  59203. var _this = this;
  59204. if (delay === void 0) { delay = this.startDelay; }
  59205. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  59206. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  59207. }
  59208. if (delay) {
  59209. setTimeout(function () {
  59210. _this.start(0);
  59211. }, delay);
  59212. return;
  59213. }
  59214. // Convert the subEmitters field to the constant type field _subEmitters
  59215. this._prepareSubEmitterInternalArray();
  59216. this._started = true;
  59217. this._stopped = false;
  59218. this._actualFrame = 0;
  59219. if (this._subEmitters && this._subEmitters.length != 0) {
  59220. this.activeSubSystems = new Array();
  59221. }
  59222. if (this.preWarmCycles) {
  59223. if (this.emitter instanceof BABYLON.AbstractMesh) {
  59224. this.emitter.computeWorldMatrix(true);
  59225. }
  59226. var noiseTextureAsProcedural_1 = this.noiseTexture;
  59227. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  59228. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  59229. setTimeout(function () {
  59230. for (var index = 0; index < _this.preWarmCycles; index++) {
  59231. _this.animate(true);
  59232. noiseTextureAsProcedural_1.render();
  59233. }
  59234. });
  59235. });
  59236. }
  59237. else {
  59238. for (var index = 0; index < this.preWarmCycles; index++) {
  59239. this.animate(true);
  59240. }
  59241. }
  59242. }
  59243. // Animations
  59244. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  59245. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  59246. }
  59247. };
  59248. /**
  59249. * Stops the particle system.
  59250. * @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.
  59251. */
  59252. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  59253. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  59254. this._stopped = true;
  59255. if (stopSubEmitters) {
  59256. this._stopSubEmitters();
  59257. }
  59258. };
  59259. // animation sheet
  59260. /**
  59261. * Remove all active particles
  59262. */
  59263. ParticleSystem.prototype.reset = function () {
  59264. this._stockParticles = [];
  59265. this._particles = [];
  59266. };
  59267. /**
  59268. * @hidden (for internal use only)
  59269. */
  59270. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  59271. var offset = index * this._vertexBufferSize;
  59272. this._vertexData[offset++] = particle.position.x;
  59273. this._vertexData[offset++] = particle.position.y;
  59274. this._vertexData[offset++] = particle.position.z;
  59275. this._vertexData[offset++] = particle.color.r;
  59276. this._vertexData[offset++] = particle.color.g;
  59277. this._vertexData[offset++] = particle.color.b;
  59278. this._vertexData[offset++] = particle.color.a;
  59279. this._vertexData[offset++] = particle.angle;
  59280. this._vertexData[offset++] = particle.scale.x * particle.size;
  59281. this._vertexData[offset++] = particle.scale.y * particle.size;
  59282. if (this._isAnimationSheetEnabled) {
  59283. this._vertexData[offset++] = particle.cellIndex;
  59284. }
  59285. if (!this._isBillboardBased) {
  59286. if (particle._initialDirection) {
  59287. this._vertexData[offset++] = particle._initialDirection.x;
  59288. this._vertexData[offset++] = particle._initialDirection.y;
  59289. this._vertexData[offset++] = particle._initialDirection.z;
  59290. }
  59291. else {
  59292. this._vertexData[offset++] = particle.direction.x;
  59293. this._vertexData[offset++] = particle.direction.y;
  59294. this._vertexData[offset++] = particle.direction.z;
  59295. }
  59296. }
  59297. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59298. this._vertexData[offset++] = particle.direction.x;
  59299. this._vertexData[offset++] = particle.direction.y;
  59300. this._vertexData[offset++] = particle.direction.z;
  59301. }
  59302. if (this._useRampGradients) {
  59303. this._vertexData[offset++] = particle.remapData.x;
  59304. this._vertexData[offset++] = particle.remapData.y;
  59305. this._vertexData[offset++] = particle.remapData.z;
  59306. this._vertexData[offset++] = particle.remapData.w;
  59307. }
  59308. if (!this._useInstancing) {
  59309. if (this._isAnimationSheetEnabled) {
  59310. if (offsetX === 0)
  59311. offsetX = this._epsilon;
  59312. else if (offsetX === 1)
  59313. offsetX = 1 - this._epsilon;
  59314. if (offsetY === 0)
  59315. offsetY = this._epsilon;
  59316. else if (offsetY === 1)
  59317. offsetY = 1 - this._epsilon;
  59318. }
  59319. this._vertexData[offset++] = offsetX;
  59320. this._vertexData[offset++] = offsetY;
  59321. }
  59322. };
  59323. ParticleSystem.prototype._stopSubEmitters = function () {
  59324. if (!this.activeSubSystems) {
  59325. return;
  59326. }
  59327. this.activeSubSystems.forEach(function (subSystem) {
  59328. subSystem.stop(true);
  59329. });
  59330. this.activeSubSystems = new Array();
  59331. };
  59332. ParticleSystem.prototype._removeFromRoot = function () {
  59333. if (!this._rootParticleSystem) {
  59334. return;
  59335. }
  59336. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  59337. if (index !== -1) {
  59338. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  59339. }
  59340. this._rootParticleSystem = null;
  59341. };
  59342. // End of sub system methods
  59343. ParticleSystem.prototype._update = function (newParticles) {
  59344. var _this = this;
  59345. // Update current
  59346. this._alive = this._particles.length > 0;
  59347. if (this.emitter.position) {
  59348. var emitterMesh = this.emitter;
  59349. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  59350. }
  59351. else {
  59352. var emitterPosition = this.emitter;
  59353. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  59354. }
  59355. this.updateFunction(this._particles);
  59356. // Add new ones
  59357. var particle;
  59358. var _loop_2 = function () {
  59359. if (this_1._particles.length === this_1._capacity) {
  59360. return "break";
  59361. }
  59362. particle = this_1._createParticle();
  59363. this_1._particles.push(particle);
  59364. // Emitter
  59365. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  59366. if (this_1.startPositionFunction) {
  59367. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  59368. }
  59369. else {
  59370. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  59371. }
  59372. if (this_1.startDirectionFunction) {
  59373. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  59374. }
  59375. else {
  59376. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  59377. }
  59378. if (emitPower === 0) {
  59379. if (!particle._initialDirection) {
  59380. particle._initialDirection = particle.direction.clone();
  59381. }
  59382. else {
  59383. particle._initialDirection.copyFrom(particle.direction);
  59384. }
  59385. }
  59386. else {
  59387. particle._initialDirection = null;
  59388. }
  59389. particle.direction.scaleInPlace(emitPower);
  59390. // Life time
  59391. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  59392. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  59393. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  59394. var factorGradient1 = currentGradient;
  59395. var factorGradient2 = nextGradient;
  59396. var lifeTime1 = factorGradient1.getFactor();
  59397. var lifeTime2 = factorGradient2.getFactor();
  59398. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  59399. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  59400. });
  59401. }
  59402. else {
  59403. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  59404. }
  59405. // Size
  59406. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  59407. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  59408. }
  59409. else {
  59410. particle._currentSizeGradient = this_1._sizeGradients[0];
  59411. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  59412. particle.size = particle._currentSize1;
  59413. if (this_1._sizeGradients.length > 1) {
  59414. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  59415. }
  59416. else {
  59417. particle._currentSize2 = particle._currentSize1;
  59418. }
  59419. }
  59420. // Size and scale
  59421. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  59422. // Adjust scale by start size
  59423. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  59424. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  59425. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  59426. if (currentGradient !== _this._currentStartSizeGradient) {
  59427. _this._currentStartSize1 = _this._currentStartSize2;
  59428. _this._currentStartSize2 = nextGradient.getFactor();
  59429. _this._currentStartSizeGradient = currentGradient;
  59430. }
  59431. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  59432. particle.scale.scaleInPlace(value);
  59433. });
  59434. }
  59435. // Angle
  59436. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  59437. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  59438. }
  59439. else {
  59440. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  59441. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  59442. particle._currentAngularSpeed1 = particle.angularSpeed;
  59443. if (this_1._angularSpeedGradients.length > 1) {
  59444. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  59445. }
  59446. else {
  59447. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  59448. }
  59449. }
  59450. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  59451. // Velocity
  59452. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  59453. particle._currentVelocityGradient = this_1._velocityGradients[0];
  59454. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  59455. if (this_1._velocityGradients.length > 1) {
  59456. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  59457. }
  59458. else {
  59459. particle._currentVelocity2 = particle._currentVelocity1;
  59460. }
  59461. }
  59462. // Limit velocity
  59463. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  59464. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  59465. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  59466. if (this_1._limitVelocityGradients.length > 1) {
  59467. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  59468. }
  59469. else {
  59470. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  59471. }
  59472. }
  59473. // Drag
  59474. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  59475. particle._currentDragGradient = this_1._dragGradients[0];
  59476. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  59477. if (this_1._dragGradients.length > 1) {
  59478. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  59479. }
  59480. else {
  59481. particle._currentDrag2 = particle._currentDrag1;
  59482. }
  59483. }
  59484. // Color
  59485. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  59486. step = BABYLON.Scalar.RandomRange(0, 1.0);
  59487. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  59488. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  59489. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  59490. }
  59491. else {
  59492. particle._currentColorGradient = this_1._colorGradients[0];
  59493. particle._currentColorGradient.getColorToRef(particle.color);
  59494. particle._currentColor1.copyFrom(particle.color);
  59495. if (this_1._colorGradients.length > 1) {
  59496. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  59497. }
  59498. else {
  59499. particle._currentColor2.copyFrom(particle.color);
  59500. }
  59501. }
  59502. // Sheet
  59503. if (this_1._isAnimationSheetEnabled) {
  59504. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  59505. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  59506. }
  59507. // Inherited Velocity
  59508. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  59509. // Ramp
  59510. if (this_1._useRampGradients) {
  59511. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  59512. }
  59513. // Noise texture coordinates
  59514. if (this_1.noiseTexture) {
  59515. if (particle._randomNoiseCoordinates1) {
  59516. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  59517. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  59518. }
  59519. else {
  59520. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  59521. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  59522. }
  59523. }
  59524. // Update the position of the attached sub-emitters to match their attached particle
  59525. particle._inheritParticleInfoToSubEmitters();
  59526. };
  59527. var this_1 = this, step;
  59528. for (var index = 0; index < newParticles; index++) {
  59529. var state_1 = _loop_2();
  59530. if (state_1 === "break")
  59531. break;
  59532. }
  59533. };
  59534. /** @hidden */
  59535. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  59536. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59537. if (isBillboardBased === void 0) { isBillboardBased = false; }
  59538. if (useRampGradients === void 0) { useRampGradients = false; }
  59539. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  59540. if (isAnimationSheetEnabled) {
  59541. attributeNamesOrOptions.push("cellIndex");
  59542. }
  59543. if (!isBillboardBased) {
  59544. attributeNamesOrOptions.push("direction");
  59545. }
  59546. if (useRampGradients) {
  59547. attributeNamesOrOptions.push("remapData");
  59548. }
  59549. return attributeNamesOrOptions;
  59550. };
  59551. /** @hidden */
  59552. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  59553. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59554. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  59555. if (isAnimationSheetEnabled) {
  59556. effectCreationOption.push("particlesInfos");
  59557. }
  59558. return effectCreationOption;
  59559. };
  59560. /** @hidden */
  59561. ParticleSystem.prototype._getEffect = function (blendMode) {
  59562. if (this._customEffect) {
  59563. return this._customEffect;
  59564. }
  59565. ;
  59566. var defines = [];
  59567. if (this._scene.clipPlane) {
  59568. defines.push("#define CLIPPLANE");
  59569. }
  59570. if (this._scene.clipPlane2) {
  59571. defines.push("#define CLIPPLANE2");
  59572. }
  59573. if (this._scene.clipPlane3) {
  59574. defines.push("#define CLIPPLANE3");
  59575. }
  59576. if (this._scene.clipPlane4) {
  59577. defines.push("#define CLIPPLANE4");
  59578. }
  59579. if (this._isAnimationSheetEnabled) {
  59580. defines.push("#define ANIMATESHEET");
  59581. }
  59582. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  59583. defines.push("#define BLENDMULTIPLYMODE");
  59584. }
  59585. if (this._useRampGradients) {
  59586. defines.push("#define RAMPGRADIENT");
  59587. }
  59588. if (this._isBillboardBased) {
  59589. defines.push("#define BILLBOARD");
  59590. switch (this.billboardMode) {
  59591. case ParticleSystem.BILLBOARDMODE_Y:
  59592. defines.push("#define BILLBOARDY");
  59593. break;
  59594. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  59595. defines.push("#define BILLBOARDSTRETCHED");
  59596. break;
  59597. case ParticleSystem.BILLBOARDMODE_ALL:
  59598. default:
  59599. break;
  59600. }
  59601. }
  59602. if (this._imageProcessingConfiguration) {
  59603. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  59604. defines.push(this._imageProcessingConfigurationDefines.toString());
  59605. }
  59606. // Effect
  59607. var join = defines.join("\n");
  59608. if (this._cachedDefines !== join) {
  59609. this._cachedDefines = join;
  59610. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  59611. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  59612. var samplers = ["diffuseSampler", "rampSampler"];
  59613. if (BABYLON.ImageProcessingConfiguration) {
  59614. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  59615. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  59616. }
  59617. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  59618. }
  59619. return this._effect;
  59620. };
  59621. /**
  59622. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  59623. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  59624. */
  59625. ParticleSystem.prototype.animate = function (preWarmOnly) {
  59626. var _this = this;
  59627. if (preWarmOnly === void 0) { preWarmOnly = false; }
  59628. if (!this._started)
  59629. return;
  59630. if (!preWarmOnly) {
  59631. // Check
  59632. if (!this.isReady())
  59633. return;
  59634. if (this._currentRenderId === this._scene.getRenderId()) {
  59635. return;
  59636. }
  59637. this._currentRenderId = this._scene.getRenderId();
  59638. }
  59639. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  59640. // Determine the number of particles we need to create
  59641. var newParticles;
  59642. if (this.manualEmitCount > -1) {
  59643. newParticles = this.manualEmitCount;
  59644. this._newPartsExcess = 0;
  59645. this.manualEmitCount = 0;
  59646. }
  59647. else {
  59648. var rate_1 = this.emitRate;
  59649. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  59650. var ratio = this._actualFrame / this.targetStopDuration;
  59651. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  59652. if (currentGradient !== _this._currentEmitRateGradient) {
  59653. _this._currentEmitRate1 = _this._currentEmitRate2;
  59654. _this._currentEmitRate2 = nextGradient.getFactor();
  59655. _this._currentEmitRateGradient = currentGradient;
  59656. }
  59657. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  59658. });
  59659. }
  59660. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  59661. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  59662. }
  59663. if (this._newPartsExcess > 1.0) {
  59664. newParticles += this._newPartsExcess >> 0;
  59665. this._newPartsExcess -= this._newPartsExcess >> 0;
  59666. }
  59667. this._alive = false;
  59668. if (!this._stopped) {
  59669. this._actualFrame += this._scaledUpdateSpeed;
  59670. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  59671. this.stop();
  59672. }
  59673. else {
  59674. newParticles = 0;
  59675. }
  59676. this._update(newParticles);
  59677. // Stopped?
  59678. if (this._stopped) {
  59679. if (!this._alive) {
  59680. this._started = false;
  59681. if (this.onAnimationEnd) {
  59682. this.onAnimationEnd();
  59683. }
  59684. if (this.disposeOnStop) {
  59685. this._scene._toBeDisposed.push(this);
  59686. }
  59687. }
  59688. }
  59689. if (!preWarmOnly) {
  59690. // Update VBO
  59691. var offset = 0;
  59692. for (var index = 0; index < this._particles.length; index++) {
  59693. var particle = this._particles[index];
  59694. this._appendParticleVertices(offset, particle);
  59695. offset += this._useInstancing ? 1 : 4;
  59696. }
  59697. if (this._vertexBuffer) {
  59698. this._vertexBuffer.update(this._vertexData);
  59699. }
  59700. }
  59701. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  59702. this.stop();
  59703. }
  59704. };
  59705. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  59706. this._appendParticleVertex(offset++, particle, 0, 0);
  59707. if (!this._useInstancing) {
  59708. this._appendParticleVertex(offset++, particle, 1, 0);
  59709. this._appendParticleVertex(offset++, particle, 1, 1);
  59710. this._appendParticleVertex(offset++, particle, 0, 1);
  59711. }
  59712. };
  59713. /**
  59714. * Rebuilds the particle system.
  59715. */
  59716. ParticleSystem.prototype.rebuild = function () {
  59717. this._createIndexBuffer();
  59718. if (this._vertexBuffer) {
  59719. this._vertexBuffer._rebuild();
  59720. }
  59721. };
  59722. /**
  59723. * Is this system ready to be used/rendered
  59724. * @return true if the system is ready
  59725. */
  59726. ParticleSystem.prototype.isReady = function () {
  59727. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  59728. return false;
  59729. }
  59730. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  59731. if (!this._getEffect(this.blendMode).isReady()) {
  59732. return false;
  59733. }
  59734. }
  59735. else {
  59736. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  59737. return false;
  59738. }
  59739. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  59740. return false;
  59741. }
  59742. }
  59743. return true;
  59744. };
  59745. ParticleSystem.prototype._render = function (blendMode) {
  59746. var effect = this._getEffect(blendMode);
  59747. var engine = this._scene.getEngine();
  59748. // Render
  59749. engine.enableEffect(effect);
  59750. var viewMatrix = this._scene.getViewMatrix();
  59751. effect.setTexture("diffuseSampler", this.particleTexture);
  59752. effect.setMatrix("view", viewMatrix);
  59753. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  59754. if (this._isAnimationSheetEnabled && this.particleTexture) {
  59755. var baseSize = this.particleTexture.getBaseSize();
  59756. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  59757. }
  59758. effect.setVector2("translationPivot", this.translationPivot);
  59759. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  59760. if (this._isBillboardBased) {
  59761. var camera = this._scene.activeCamera;
  59762. effect.setVector3("eyePosition", camera.globalPosition);
  59763. }
  59764. if (this._rampGradientsTexture) {
  59765. effect.setTexture("rampSampler", this._rampGradientsTexture);
  59766. }
  59767. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  59768. var invView = viewMatrix.clone();
  59769. invView.invert();
  59770. effect.setMatrix("invView", invView);
  59771. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  59772. }
  59773. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  59774. // image processing
  59775. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  59776. this._imageProcessingConfiguration.bind(effect);
  59777. }
  59778. // Draw order
  59779. switch (blendMode) {
  59780. case ParticleSystem.BLENDMODE_ADD:
  59781. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  59782. break;
  59783. case ParticleSystem.BLENDMODE_ONEONE:
  59784. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  59785. break;
  59786. case ParticleSystem.BLENDMODE_STANDARD:
  59787. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  59788. break;
  59789. case ParticleSystem.BLENDMODE_MULTIPLY:
  59790. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  59791. break;
  59792. }
  59793. if (this._useInstancing) {
  59794. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  59795. }
  59796. else {
  59797. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  59798. }
  59799. return this._particles.length;
  59800. };
  59801. /**
  59802. * Renders the particle system in its current state.
  59803. * @returns the current number of particles
  59804. */
  59805. ParticleSystem.prototype.render = function () {
  59806. // Check
  59807. if (!this.isReady() || !this._particles.length) {
  59808. return 0;
  59809. }
  59810. var engine = this._scene.getEngine();
  59811. engine.setState(false);
  59812. if (this.forceDepthWrite) {
  59813. engine.setDepthWrite(true);
  59814. }
  59815. var outparticles = 0;
  59816. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  59817. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  59818. }
  59819. outparticles = this._render(this.blendMode);
  59820. engine.unbindInstanceAttributes();
  59821. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59822. return outparticles;
  59823. };
  59824. /**
  59825. * Disposes the particle system and free the associated resources
  59826. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  59827. */
  59828. ParticleSystem.prototype.dispose = function (disposeTexture) {
  59829. if (disposeTexture === void 0) { disposeTexture = true; }
  59830. if (this._vertexBuffer) {
  59831. this._vertexBuffer.dispose();
  59832. this._vertexBuffer = null;
  59833. }
  59834. if (this._spriteBuffer) {
  59835. this._spriteBuffer.dispose();
  59836. this._spriteBuffer = null;
  59837. }
  59838. if (this._indexBuffer) {
  59839. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  59840. this._indexBuffer = null;
  59841. }
  59842. if (disposeTexture && this.particleTexture) {
  59843. this.particleTexture.dispose();
  59844. this.particleTexture = null;
  59845. }
  59846. if (disposeTexture && this.noiseTexture) {
  59847. this.noiseTexture.dispose();
  59848. this.noiseTexture = null;
  59849. }
  59850. if (this._rampGradientsTexture) {
  59851. this._rampGradientsTexture.dispose();
  59852. this._rampGradientsTexture = null;
  59853. }
  59854. this._removeFromRoot();
  59855. if (this._subEmitters && this._subEmitters.length) {
  59856. for (var index = 0; index < this._subEmitters.length; index++) {
  59857. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  59858. var subEmitter = _a[_i];
  59859. subEmitter.dispose();
  59860. }
  59861. }
  59862. this._subEmitters = [];
  59863. this.subEmitters = [];
  59864. }
  59865. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  59866. this.emitter.dispose(true);
  59867. }
  59868. // Remove from scene
  59869. var index = this._scene.particleSystems.indexOf(this);
  59870. if (index > -1) {
  59871. this._scene.particleSystems.splice(index, 1);
  59872. }
  59873. this._scene._activeParticleSystems.dispose();
  59874. // Callback
  59875. this.onDisposeObservable.notifyObservers(this);
  59876. this.onDisposeObservable.clear();
  59877. this.reset();
  59878. };
  59879. // Clone
  59880. /**
  59881. * Clones the particle system.
  59882. * @param name The name of the cloned object
  59883. * @param newEmitter The new emitter to use
  59884. * @returns the cloned particle system
  59885. */
  59886. ParticleSystem.prototype.clone = function (name, newEmitter) {
  59887. var custom = null;
  59888. var program = null;
  59889. if (this.customShader != null) {
  59890. program = this.customShader;
  59891. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  59892. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  59893. }
  59894. else if (this._customEffect) {
  59895. custom = this._customEffect;
  59896. }
  59897. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  59898. result.customShader = program;
  59899. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  59900. if (newEmitter === undefined) {
  59901. newEmitter = this.emitter;
  59902. }
  59903. result.noiseTexture = this.noiseTexture;
  59904. result.emitter = newEmitter;
  59905. if (this.particleTexture) {
  59906. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  59907. }
  59908. // Clone gradients
  59909. if (this._colorGradients) {
  59910. this._colorGradients.forEach(function (v) {
  59911. result.addColorGradient(v.gradient, v.color1, v.color2);
  59912. });
  59913. }
  59914. if (this._dragGradients) {
  59915. this._dragGradients.forEach(function (v) {
  59916. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  59917. });
  59918. }
  59919. if (this._angularSpeedGradients) {
  59920. this._angularSpeedGradients.forEach(function (v) {
  59921. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  59922. });
  59923. }
  59924. if (this._emitRateGradients) {
  59925. this._emitRateGradients.forEach(function (v) {
  59926. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  59927. });
  59928. }
  59929. if (this._lifeTimeGradients) {
  59930. this._lifeTimeGradients.forEach(function (v) {
  59931. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  59932. });
  59933. }
  59934. if (this._limitVelocityGradients) {
  59935. this._limitVelocityGradients.forEach(function (v) {
  59936. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  59937. });
  59938. }
  59939. if (this._sizeGradients) {
  59940. this._sizeGradients.forEach(function (v) {
  59941. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  59942. });
  59943. }
  59944. if (this._startSizeGradients) {
  59945. this._startSizeGradients.forEach(function (v) {
  59946. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  59947. });
  59948. }
  59949. if (this._velocityGradients) {
  59950. this._velocityGradients.forEach(function (v) {
  59951. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  59952. });
  59953. }
  59954. if (this._rampGradients) {
  59955. this._rampGradients.forEach(function (v) {
  59956. result.addRampGradient(v.gradient, v.color);
  59957. });
  59958. }
  59959. if (this._colorRemapGradients) {
  59960. this._colorRemapGradients.forEach(function (v) {
  59961. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  59962. });
  59963. }
  59964. if (this._alphaRemapGradients) {
  59965. this._alphaRemapGradients.forEach(function (v) {
  59966. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  59967. });
  59968. }
  59969. if (!this.preventAutoStart) {
  59970. result.start();
  59971. }
  59972. return result;
  59973. };
  59974. /**
  59975. * Serializes the particle system to a JSON object.
  59976. * @returns the JSON object
  59977. */
  59978. ParticleSystem.prototype.serialize = function () {
  59979. var serializationObject = {};
  59980. ParticleSystem._Serialize(serializationObject, this);
  59981. serializationObject.textureMask = this.textureMask.asArray();
  59982. serializationObject.customShader = this.customShader;
  59983. serializationObject.preventAutoStart = this.preventAutoStart;
  59984. // SubEmitters
  59985. if (this.subEmitters) {
  59986. serializationObject.subEmitters = [];
  59987. if (!this._subEmitters) {
  59988. this._prepareSubEmitterInternalArray();
  59989. }
  59990. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  59991. var subs = _a[_i];
  59992. var cell = [];
  59993. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  59994. var sub = subs_1[_b];
  59995. cell.push(sub.serialize());
  59996. }
  59997. serializationObject.subEmitters.push(cell);
  59998. }
  59999. }
  60000. return serializationObject;
  60001. };
  60002. /** @hidden */
  60003. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  60004. serializationObject.name = particleSystem.name;
  60005. serializationObject.id = particleSystem.id;
  60006. serializationObject.capacity = particleSystem.getCapacity();
  60007. // Emitter
  60008. if (particleSystem.emitter.position) {
  60009. var emitterMesh = particleSystem.emitter;
  60010. serializationObject.emitterId = emitterMesh.id;
  60011. }
  60012. else {
  60013. var emitterPosition = particleSystem.emitter;
  60014. serializationObject.emitter = emitterPosition.asArray();
  60015. }
  60016. // Emitter
  60017. if (particleSystem.particleEmitterType) {
  60018. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  60019. }
  60020. if (particleSystem.particleTexture) {
  60021. serializationObject.textureName = particleSystem.particleTexture.name;
  60022. serializationObject.invertY = particleSystem.particleTexture._invertY;
  60023. }
  60024. // Animations
  60025. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  60026. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  60027. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  60028. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  60029. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  60030. // Particle system
  60031. serializationObject.startDelay = particleSystem.startDelay;
  60032. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  60033. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  60034. serializationObject.billboardMode = particleSystem.billboardMode;
  60035. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  60036. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  60037. serializationObject.minSize = particleSystem.minSize;
  60038. serializationObject.maxSize = particleSystem.maxSize;
  60039. serializationObject.minScaleX = particleSystem.minScaleX;
  60040. serializationObject.maxScaleX = particleSystem.maxScaleX;
  60041. serializationObject.minScaleY = particleSystem.minScaleY;
  60042. serializationObject.maxScaleY = particleSystem.maxScaleY;
  60043. serializationObject.minEmitPower = particleSystem.minEmitPower;
  60044. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  60045. serializationObject.minLifeTime = particleSystem.minLifeTime;
  60046. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  60047. serializationObject.emitRate = particleSystem.emitRate;
  60048. serializationObject.gravity = particleSystem.gravity.asArray();
  60049. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  60050. serializationObject.color1 = particleSystem.color1.asArray();
  60051. serializationObject.color2 = particleSystem.color2.asArray();
  60052. serializationObject.colorDead = particleSystem.colorDead.asArray();
  60053. serializationObject.updateSpeed = particleSystem.updateSpeed;
  60054. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  60055. serializationObject.blendMode = particleSystem.blendMode;
  60056. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  60057. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  60058. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  60059. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  60060. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  60061. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  60062. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  60063. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  60064. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  60065. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  60066. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  60067. var colorGradients = particleSystem.getColorGradients();
  60068. if (colorGradients) {
  60069. serializationObject.colorGradients = [];
  60070. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  60071. var colorGradient = colorGradients_1[_i];
  60072. var serializedGradient = {
  60073. gradient: colorGradient.gradient,
  60074. color1: colorGradient.color1.asArray()
  60075. };
  60076. if (colorGradient.color2) {
  60077. serializedGradient.color2 = colorGradient.color2.asArray();
  60078. }
  60079. serializationObject.colorGradients.push(serializedGradient);
  60080. }
  60081. }
  60082. var rampGradients = particleSystem.getRampGradients();
  60083. if (rampGradients) {
  60084. serializationObject.rampGradients = [];
  60085. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  60086. var rampGradient = rampGradients_1[_a];
  60087. var serializedGradient = {
  60088. gradient: rampGradient.gradient,
  60089. color: rampGradient.color.asArray()
  60090. };
  60091. serializationObject.rampGradients.push(serializedGradient);
  60092. }
  60093. serializationObject.useRampGradients = particleSystem.useRampGradients;
  60094. }
  60095. var colorRemapGradients = particleSystem.getColorRemapGradients();
  60096. if (colorRemapGradients) {
  60097. serializationObject.colorRemapGradients = [];
  60098. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  60099. var colorRemapGradient = colorRemapGradients_1[_b];
  60100. var serializedGradient = {
  60101. gradient: colorRemapGradient.gradient,
  60102. factor1: colorRemapGradient.factor1
  60103. };
  60104. if (colorRemapGradient.factor2 !== undefined) {
  60105. serializedGradient.factor2 = colorRemapGradient.factor2;
  60106. }
  60107. serializationObject.colorRemapGradients.push(serializedGradient);
  60108. }
  60109. }
  60110. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  60111. if (alphaRemapGradients) {
  60112. serializationObject.alphaRemapGradients = [];
  60113. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  60114. var alphaRemapGradient = alphaRemapGradients_1[_c];
  60115. var serializedGradient = {
  60116. gradient: alphaRemapGradient.gradient,
  60117. factor1: alphaRemapGradient.factor1
  60118. };
  60119. if (alphaRemapGradient.factor2 !== undefined) {
  60120. serializedGradient.factor2 = alphaRemapGradient.factor2;
  60121. }
  60122. serializationObject.alphaRemapGradients.push(serializedGradient);
  60123. }
  60124. }
  60125. var sizeGradients = particleSystem.getSizeGradients();
  60126. if (sizeGradients) {
  60127. serializationObject.sizeGradients = [];
  60128. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  60129. var sizeGradient = sizeGradients_1[_d];
  60130. var serializedGradient = {
  60131. gradient: sizeGradient.gradient,
  60132. factor1: sizeGradient.factor1
  60133. };
  60134. if (sizeGradient.factor2 !== undefined) {
  60135. serializedGradient.factor2 = sizeGradient.factor2;
  60136. }
  60137. serializationObject.sizeGradients.push(serializedGradient);
  60138. }
  60139. }
  60140. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  60141. if (angularSpeedGradients) {
  60142. serializationObject.angularSpeedGradients = [];
  60143. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  60144. var angularSpeedGradient = angularSpeedGradients_1[_e];
  60145. var serializedGradient = {
  60146. gradient: angularSpeedGradient.gradient,
  60147. factor1: angularSpeedGradient.factor1
  60148. };
  60149. if (angularSpeedGradient.factor2 !== undefined) {
  60150. serializedGradient.factor2 = angularSpeedGradient.factor2;
  60151. }
  60152. serializationObject.angularSpeedGradients.push(serializedGradient);
  60153. }
  60154. }
  60155. var velocityGradients = particleSystem.getVelocityGradients();
  60156. if (velocityGradients) {
  60157. serializationObject.velocityGradients = [];
  60158. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  60159. var velocityGradient = velocityGradients_1[_f];
  60160. var serializedGradient = {
  60161. gradient: velocityGradient.gradient,
  60162. factor1: velocityGradient.factor1
  60163. };
  60164. if (velocityGradient.factor2 !== undefined) {
  60165. serializedGradient.factor2 = velocityGradient.factor2;
  60166. }
  60167. serializationObject.velocityGradients.push(serializedGradient);
  60168. }
  60169. }
  60170. var dragGradients = particleSystem.getDragGradients();
  60171. if (dragGradients) {
  60172. serializationObject.dragyGradients = [];
  60173. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  60174. var dragGradient = dragGradients_1[_g];
  60175. var serializedGradient = {
  60176. gradient: dragGradient.gradient,
  60177. factor1: dragGradient.factor1
  60178. };
  60179. if (dragGradient.factor2 !== undefined) {
  60180. serializedGradient.factor2 = dragGradient.factor2;
  60181. }
  60182. serializationObject.dragGradients.push(serializedGradient);
  60183. }
  60184. }
  60185. var emitRateGradients = particleSystem.getEmitRateGradients();
  60186. if (emitRateGradients) {
  60187. serializationObject.emitRateGradients = [];
  60188. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  60189. var emitRateGradient = emitRateGradients_1[_h];
  60190. var serializedGradient = {
  60191. gradient: emitRateGradient.gradient,
  60192. factor1: emitRateGradient.factor1
  60193. };
  60194. if (emitRateGradient.factor2 !== undefined) {
  60195. serializedGradient.factor2 = emitRateGradient.factor2;
  60196. }
  60197. serializationObject.emitRateGradients.push(serializedGradient);
  60198. }
  60199. }
  60200. var startSizeGradients = particleSystem.getStartSizeGradients();
  60201. if (startSizeGradients) {
  60202. serializationObject.startSizeGradients = [];
  60203. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  60204. var startSizeGradient = startSizeGradients_1[_j];
  60205. var serializedGradient = {
  60206. gradient: startSizeGradient.gradient,
  60207. factor1: startSizeGradient.factor1
  60208. };
  60209. if (startSizeGradient.factor2 !== undefined) {
  60210. serializedGradient.factor2 = startSizeGradient.factor2;
  60211. }
  60212. serializationObject.startSizeGradients.push(serializedGradient);
  60213. }
  60214. }
  60215. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  60216. if (lifeTimeGradients) {
  60217. serializationObject.lifeTimeGradients = [];
  60218. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  60219. var lifeTimeGradient = lifeTimeGradients_1[_k];
  60220. var serializedGradient = {
  60221. gradient: lifeTimeGradient.gradient,
  60222. factor1: lifeTimeGradient.factor1
  60223. };
  60224. if (lifeTimeGradient.factor2 !== undefined) {
  60225. serializedGradient.factor2 = lifeTimeGradient.factor2;
  60226. }
  60227. serializationObject.lifeTimeGradients.push(serializedGradient);
  60228. }
  60229. }
  60230. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  60231. if (limitVelocityGradients) {
  60232. serializationObject.limitVelocityGradients = [];
  60233. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  60234. var limitVelocityGradient = limitVelocityGradients_1[_l];
  60235. var serializedGradient = {
  60236. gradient: limitVelocityGradient.gradient,
  60237. factor1: limitVelocityGradient.factor1
  60238. };
  60239. if (limitVelocityGradient.factor2 !== undefined) {
  60240. serializedGradient.factor2 = limitVelocityGradient.factor2;
  60241. }
  60242. serializationObject.limitVelocityGradients.push(serializedGradient);
  60243. }
  60244. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  60245. }
  60246. if (particleSystem.noiseTexture) {
  60247. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  60248. }
  60249. };
  60250. /** @hidden */
  60251. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  60252. // Texture
  60253. if (parsedParticleSystem.textureName) {
  60254. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  60255. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  60256. }
  60257. // Emitter
  60258. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  60259. particleSystem.emitter = BABYLON.Vector3.Zero();
  60260. }
  60261. else if (parsedParticleSystem.emitterId) {
  60262. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  60263. }
  60264. else {
  60265. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  60266. }
  60267. // Misc.
  60268. if (parsedParticleSystem.renderingGroupId !== undefined) {
  60269. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  60270. }
  60271. if (parsedParticleSystem.isBillboardBased !== undefined) {
  60272. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  60273. }
  60274. if (parsedParticleSystem.billboardMode !== undefined) {
  60275. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  60276. }
  60277. // Animations
  60278. if (parsedParticleSystem.animations) {
  60279. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  60280. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  60281. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  60282. }
  60283. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  60284. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  60285. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  60286. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  60287. }
  60288. if (parsedParticleSystem.autoAnimate) {
  60289. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  60290. }
  60291. // Particle system
  60292. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  60293. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  60294. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  60295. particleSystem.minSize = parsedParticleSystem.minSize;
  60296. particleSystem.maxSize = parsedParticleSystem.maxSize;
  60297. if (parsedParticleSystem.minScaleX) {
  60298. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  60299. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  60300. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  60301. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  60302. }
  60303. if (parsedParticleSystem.preWarmCycles !== undefined) {
  60304. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  60305. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  60306. }
  60307. if (parsedParticleSystem.minInitialRotation !== undefined) {
  60308. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  60309. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  60310. }
  60311. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  60312. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  60313. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  60314. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  60315. particleSystem.emitRate = parsedParticleSystem.emitRate;
  60316. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  60317. if (parsedParticleSystem.noiseStrength) {
  60318. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  60319. }
  60320. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  60321. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  60322. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  60323. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  60324. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  60325. particleSystem.blendMode = parsedParticleSystem.blendMode;
  60326. if (parsedParticleSystem.colorGradients) {
  60327. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  60328. var colorGradient = _a[_i];
  60329. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  60330. }
  60331. }
  60332. if (parsedParticleSystem.rampGradients) {
  60333. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  60334. var rampGradient = _c[_b];
  60335. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  60336. }
  60337. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  60338. }
  60339. if (parsedParticleSystem.colorRemapGradients) {
  60340. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  60341. var colorRemapGradient = _e[_d];
  60342. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  60343. }
  60344. }
  60345. if (parsedParticleSystem.alphaRemapGradients) {
  60346. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  60347. var alphaRemapGradient = _g[_f];
  60348. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  60349. }
  60350. }
  60351. if (parsedParticleSystem.sizeGradients) {
  60352. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  60353. var sizeGradient = _j[_h];
  60354. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  60355. }
  60356. }
  60357. if (parsedParticleSystem.sizeGradients) {
  60358. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  60359. var sizeGradient = _l[_k];
  60360. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  60361. }
  60362. }
  60363. if (parsedParticleSystem.angularSpeedGradients) {
  60364. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  60365. var angularSpeedGradient = _o[_m];
  60366. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  60367. }
  60368. }
  60369. if (parsedParticleSystem.velocityGradients) {
  60370. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  60371. var velocityGradient = _q[_p];
  60372. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  60373. }
  60374. }
  60375. if (parsedParticleSystem.dragGradients) {
  60376. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  60377. var dragGradient = _s[_r];
  60378. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  60379. }
  60380. }
  60381. if (parsedParticleSystem.emitRateGradients) {
  60382. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  60383. var emitRateGradient = _u[_t];
  60384. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  60385. }
  60386. }
  60387. if (parsedParticleSystem.startSizeGradients) {
  60388. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  60389. var startSizeGradient = _w[_v];
  60390. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  60391. }
  60392. }
  60393. if (parsedParticleSystem.lifeTimeGradients) {
  60394. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  60395. var lifeTimeGradient = _y[_x];
  60396. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  60397. }
  60398. }
  60399. if (parsedParticleSystem.limitVelocityGradients) {
  60400. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  60401. var limitVelocityGradient = _0[_z];
  60402. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  60403. }
  60404. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  60405. }
  60406. if (parsedParticleSystem.noiseTexture) {
  60407. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  60408. }
  60409. // Emitter
  60410. var emitterType;
  60411. if (parsedParticleSystem.particleEmitterType) {
  60412. switch (parsedParticleSystem.particleEmitterType.type) {
  60413. case "SphereParticleEmitter":
  60414. emitterType = new BABYLON.SphereParticleEmitter();
  60415. break;
  60416. case "SphereDirectedParticleEmitter":
  60417. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  60418. break;
  60419. case "ConeEmitter":
  60420. case "ConeParticleEmitter":
  60421. emitterType = new BABYLON.ConeParticleEmitter();
  60422. break;
  60423. case "CylinderParticleEmitter":
  60424. emitterType = new BABYLON.CylinderParticleEmitter();
  60425. break;
  60426. case "HemisphericParticleEmitter":
  60427. emitterType = new BABYLON.HemisphericParticleEmitter();
  60428. break;
  60429. case "BoxEmitter":
  60430. case "BoxParticleEmitter":
  60431. default:
  60432. emitterType = new BABYLON.BoxParticleEmitter();
  60433. break;
  60434. }
  60435. emitterType.parse(parsedParticleSystem.particleEmitterType);
  60436. }
  60437. else {
  60438. emitterType = new BABYLON.BoxParticleEmitter();
  60439. emitterType.parse(parsedParticleSystem);
  60440. }
  60441. particleSystem.particleEmitterType = emitterType;
  60442. // Animation sheet
  60443. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  60444. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  60445. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  60446. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  60447. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  60448. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  60449. };
  60450. /**
  60451. * Parses a JSON object to create a particle system.
  60452. * @param parsedParticleSystem The JSON object to parse
  60453. * @param scene The scene to create the particle system in
  60454. * @param rootUrl The root url to use to load external dependencies like texture
  60455. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  60456. * @returns the Parsed particle system
  60457. */
  60458. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  60459. if (doNotStart === void 0) { doNotStart = false; }
  60460. var name = parsedParticleSystem.name;
  60461. var custom = null;
  60462. var program = null;
  60463. if (parsedParticleSystem.customShader) {
  60464. program = parsedParticleSystem.customShader;
  60465. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  60466. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  60467. }
  60468. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  60469. particleSystem.customShader = program;
  60470. if (parsedParticleSystem.id) {
  60471. particleSystem.id = parsedParticleSystem.id;
  60472. }
  60473. // SubEmitters
  60474. if (parsedParticleSystem.subEmitters) {
  60475. particleSystem.subEmitters = [];
  60476. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  60477. var cell = _a[_i];
  60478. var cellArray = [];
  60479. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  60480. var sub = cell_1[_b];
  60481. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  60482. }
  60483. particleSystem.subEmitters.push(cellArray);
  60484. }
  60485. }
  60486. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  60487. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  60488. // Auto start
  60489. if (parsedParticleSystem.preventAutoStart) {
  60490. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  60491. }
  60492. if (!doNotStart && !particleSystem.preventAutoStart) {
  60493. particleSystem.start();
  60494. }
  60495. return particleSystem;
  60496. };
  60497. /**
  60498. * Billboard mode will only apply to Y axis
  60499. */
  60500. ParticleSystem.BILLBOARDMODE_Y = 2;
  60501. /**
  60502. * Billboard mode will apply to all axes
  60503. */
  60504. ParticleSystem.BILLBOARDMODE_ALL = 7;
  60505. /**
  60506. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  60507. */
  60508. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  60509. return ParticleSystem;
  60510. }(BABYLON.BaseParticleSystem));
  60511. BABYLON.ParticleSystem = ParticleSystem;
  60512. })(BABYLON || (BABYLON = {}));
  60513. //# sourceMappingURL=babylon.particleSystem.js.map
  60514. var BABYLON;
  60515. (function (BABYLON) {
  60516. /**
  60517. * Particle emitter emitting particles from the inside of a box.
  60518. * It emits the particles randomly between 2 given directions.
  60519. */
  60520. var BoxParticleEmitter = /** @class */ (function () {
  60521. /**
  60522. * Creates a new instance BoxParticleEmitter
  60523. */
  60524. function BoxParticleEmitter() {
  60525. /**
  60526. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60527. */
  60528. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  60529. /**
  60530. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60531. */
  60532. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  60533. /**
  60534. * 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.
  60535. */
  60536. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  60537. /**
  60538. * 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.
  60539. */
  60540. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  60541. }
  60542. /**
  60543. * Called by the particle System when the direction is computed for the created particle.
  60544. * @param worldMatrix is the world matrix of the particle system
  60545. * @param directionToUpdate is the direction vector to update with the result
  60546. * @param particle is the particle we are computed the direction for
  60547. */
  60548. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60549. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60550. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60551. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60552. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60553. };
  60554. /**
  60555. * Called by the particle System when the position is computed for the created particle.
  60556. * @param worldMatrix is the world matrix of the particle system
  60557. * @param positionToUpdate is the position vector to update with the result
  60558. * @param particle is the particle we are computed the position for
  60559. */
  60560. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60561. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  60562. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  60563. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  60564. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  60565. };
  60566. /**
  60567. * Clones the current emitter and returns a copy of it
  60568. * @returns the new emitter
  60569. */
  60570. BoxParticleEmitter.prototype.clone = function () {
  60571. var newOne = new BoxParticleEmitter();
  60572. BABYLON.Tools.DeepCopy(this, newOne);
  60573. return newOne;
  60574. };
  60575. /**
  60576. * Called by the GPUParticleSystem to setup the update shader
  60577. * @param effect defines the update shader
  60578. */
  60579. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  60580. effect.setVector3("direction1", this.direction1);
  60581. effect.setVector3("direction2", this.direction2);
  60582. effect.setVector3("minEmitBox", this.minEmitBox);
  60583. effect.setVector3("maxEmitBox", this.maxEmitBox);
  60584. };
  60585. /**
  60586. * Returns a string to use to update the GPU particles update shader
  60587. * @returns a string containng the defines string
  60588. */
  60589. BoxParticleEmitter.prototype.getEffectDefines = function () {
  60590. return "#define BOXEMITTER";
  60591. };
  60592. /**
  60593. * Returns the string "BoxParticleEmitter"
  60594. * @returns a string containing the class name
  60595. */
  60596. BoxParticleEmitter.prototype.getClassName = function () {
  60597. return "BoxParticleEmitter";
  60598. };
  60599. /**
  60600. * Serializes the particle system to a JSON object.
  60601. * @returns the JSON object
  60602. */
  60603. BoxParticleEmitter.prototype.serialize = function () {
  60604. var serializationObject = {};
  60605. serializationObject.type = this.getClassName();
  60606. serializationObject.direction1 = this.direction1.asArray();
  60607. serializationObject.direction2 = this.direction2.asArray();
  60608. serializationObject.minEmitBox = this.minEmitBox.asArray();
  60609. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  60610. return serializationObject;
  60611. };
  60612. /**
  60613. * Parse properties from a JSON object
  60614. * @param serializationObject defines the JSON object
  60615. */
  60616. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  60617. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  60618. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  60619. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  60620. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  60621. };
  60622. return BoxParticleEmitter;
  60623. }());
  60624. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  60625. })(BABYLON || (BABYLON = {}));
  60626. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  60627. var BABYLON;
  60628. (function (BABYLON) {
  60629. /**
  60630. * Particle emitter emitting particles from the inside of a cylinder.
  60631. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  60632. */
  60633. var CylinderParticleEmitter = /** @class */ (function () {
  60634. /**
  60635. * Creates a new instance CylinderParticleEmitter
  60636. * @param radius the radius of the emission cylinder (1 by default)
  60637. * @param height the height of the emission cylinder (1 by default)
  60638. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60639. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  60640. */
  60641. function CylinderParticleEmitter(
  60642. /**
  60643. * The radius of the emission cylinder.
  60644. */
  60645. radius,
  60646. /**
  60647. * The height of the emission cylinder.
  60648. */
  60649. height,
  60650. /**
  60651. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  60652. */
  60653. radiusRange,
  60654. /**
  60655. * How much to randomize the particle direction [0-1].
  60656. */
  60657. directionRandomizer) {
  60658. if (radius === void 0) { radius = 1; }
  60659. if (height === void 0) { height = 1; }
  60660. if (radiusRange === void 0) { radiusRange = 1; }
  60661. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60662. this.radius = radius;
  60663. this.height = height;
  60664. this.radiusRange = radiusRange;
  60665. this.directionRandomizer = directionRandomizer;
  60666. }
  60667. /**
  60668. * Called by the particle System when the direction is computed for the created particle.
  60669. * @param worldMatrix is the world matrix of the particle system
  60670. * @param directionToUpdate is the direction vector to update with the result
  60671. * @param particle is the particle we are computed the direction for
  60672. */
  60673. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60674. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60675. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  60676. var angle = Math.atan2(direction.x, direction.z);
  60677. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  60678. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  60679. direction.x = Math.sin(angle);
  60680. direction.z = Math.cos(angle);
  60681. direction.normalize();
  60682. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60683. };
  60684. /**
  60685. * Called by the particle System when the position is computed for the created particle.
  60686. * @param worldMatrix is the world matrix of the particle system
  60687. * @param positionToUpdate is the position vector to update with the result
  60688. * @param particle is the particle we are computed the position for
  60689. */
  60690. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60691. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  60692. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  60693. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  60694. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  60695. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  60696. var xPos = positionRadius * Math.cos(angle);
  60697. var zPos = positionRadius * Math.sin(angle);
  60698. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  60699. };
  60700. /**
  60701. * Clones the current emitter and returns a copy of it
  60702. * @returns the new emitter
  60703. */
  60704. CylinderParticleEmitter.prototype.clone = function () {
  60705. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  60706. BABYLON.Tools.DeepCopy(this, newOne);
  60707. return newOne;
  60708. };
  60709. /**
  60710. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60711. * @param effect defines the update shader
  60712. */
  60713. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  60714. effect.setFloat("radius", this.radius);
  60715. effect.setFloat("height", this.height);
  60716. effect.setFloat("radiusRange", this.radiusRange);
  60717. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60718. };
  60719. /**
  60720. * Returns a string to use to update the GPU particles update shader
  60721. * @returns a string containng the defines string
  60722. */
  60723. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  60724. return "#define CYLINDEREMITTER";
  60725. };
  60726. /**
  60727. * Returns the string "CylinderParticleEmitter"
  60728. * @returns a string containing the class name
  60729. */
  60730. CylinderParticleEmitter.prototype.getClassName = function () {
  60731. return "CylinderParticleEmitter";
  60732. };
  60733. /**
  60734. * Serializes the particle system to a JSON object.
  60735. * @returns the JSON object
  60736. */
  60737. CylinderParticleEmitter.prototype.serialize = function () {
  60738. var serializationObject = {};
  60739. serializationObject.type = this.getClassName();
  60740. serializationObject.radius = this.radius;
  60741. serializationObject.height = this.height;
  60742. serializationObject.radiusRange = this.radiusRange;
  60743. serializationObject.directionRandomizer = this.directionRandomizer;
  60744. return serializationObject;
  60745. };
  60746. /**
  60747. * Parse properties from a JSON object
  60748. * @param serializationObject defines the JSON object
  60749. */
  60750. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  60751. this.radius = serializationObject.radius;
  60752. this.height = serializationObject.height;
  60753. this.radiusRange = serializationObject.radiusRange;
  60754. this.directionRandomizer = serializationObject.directionRandomizer;
  60755. };
  60756. return CylinderParticleEmitter;
  60757. }());
  60758. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  60759. /**
  60760. * Particle emitter emitting particles from the inside of a cylinder.
  60761. * It emits the particles randomly between two vectors.
  60762. */
  60763. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  60764. __extends(CylinderDirectedParticleEmitter, _super);
  60765. /**
  60766. * Creates a new instance CylinderDirectedParticleEmitter
  60767. * @param radius the radius of the emission cylinder (1 by default)
  60768. * @param height the height of the emission cylinder (1 by default)
  60769. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  60770. * @param direction1 the min limit of the emission direction (up vector by default)
  60771. * @param direction2 the max limit of the emission direction (up vector by default)
  60772. */
  60773. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  60774. /**
  60775. * The min limit of the emission direction.
  60776. */
  60777. direction1,
  60778. /**
  60779. * The max limit of the emission direction.
  60780. */
  60781. direction2) {
  60782. if (radius === void 0) { radius = 1; }
  60783. if (height === void 0) { height = 1; }
  60784. if (radiusRange === void 0) { radiusRange = 1; }
  60785. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  60786. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  60787. var _this = _super.call(this, radius, height, radiusRange) || this;
  60788. _this.direction1 = direction1;
  60789. _this.direction2 = direction2;
  60790. return _this;
  60791. }
  60792. /**
  60793. * Called by the particle System when the direction is computed for the created particle.
  60794. * @param worldMatrix is the world matrix of the particle system
  60795. * @param directionToUpdate is the direction vector to update with the result
  60796. * @param particle is the particle we are computed the direction for
  60797. */
  60798. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60799. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60800. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60801. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60802. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60803. };
  60804. /**
  60805. * Clones the current emitter and returns a copy of it
  60806. * @returns the new emitter
  60807. */
  60808. CylinderDirectedParticleEmitter.prototype.clone = function () {
  60809. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  60810. BABYLON.Tools.DeepCopy(this, newOne);
  60811. return newOne;
  60812. };
  60813. /**
  60814. * Called by the GPUParticleSystem to setup the update shader
  60815. * @param effect defines the update shader
  60816. */
  60817. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  60818. effect.setFloat("radius", this.radius);
  60819. effect.setFloat("height", this.height);
  60820. effect.setFloat("radiusRange", this.radiusRange);
  60821. effect.setVector3("direction1", this.direction1);
  60822. effect.setVector3("direction2", this.direction2);
  60823. };
  60824. /**
  60825. * Returns a string to use to update the GPU particles update shader
  60826. * @returns a string containng the defines string
  60827. */
  60828. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  60829. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  60830. };
  60831. /**
  60832. * Returns the string "CylinderDirectedParticleEmitter"
  60833. * @returns a string containing the class name
  60834. */
  60835. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  60836. return "CylinderDirectedParticleEmitter";
  60837. };
  60838. /**
  60839. * Serializes the particle system to a JSON object.
  60840. * @returns the JSON object
  60841. */
  60842. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  60843. var serializationObject = _super.prototype.serialize.call(this);
  60844. serializationObject.direction1 = this.direction1.asArray();
  60845. serializationObject.direction2 = this.direction2.asArray();
  60846. return serializationObject;
  60847. };
  60848. /**
  60849. * Parse properties from a JSON object
  60850. * @param serializationObject defines the JSON object
  60851. */
  60852. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  60853. _super.prototype.parse.call(this, serializationObject);
  60854. this.direction1.copyFrom(serializationObject.direction1);
  60855. this.direction2.copyFrom(serializationObject.direction2);
  60856. };
  60857. return CylinderDirectedParticleEmitter;
  60858. }(CylinderParticleEmitter));
  60859. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  60860. })(BABYLON || (BABYLON = {}));
  60861. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  60862. var BABYLON;
  60863. (function (BABYLON) {
  60864. /**
  60865. * Particle emitter emitting particles from the inside of a cone.
  60866. * It emits the particles alongside the cone volume from the base to the particle.
  60867. * The emission direction might be randomized.
  60868. */
  60869. var ConeParticleEmitter = /** @class */ (function () {
  60870. /**
  60871. * Creates a new instance ConeParticleEmitter
  60872. * @param radius the radius of the emission cone (1 by default)
  60873. * @param angles the cone base angle (PI by default)
  60874. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  60875. */
  60876. function ConeParticleEmitter(radius, angle,
  60877. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  60878. directionRandomizer) {
  60879. if (radius === void 0) { radius = 1; }
  60880. if (angle === void 0) { angle = Math.PI; }
  60881. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  60882. this.directionRandomizer = directionRandomizer;
  60883. /**
  60884. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  60885. */
  60886. this.radiusRange = 1;
  60887. /**
  60888. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  60889. */
  60890. this.heightRange = 1;
  60891. /**
  60892. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  60893. */
  60894. this.emitFromSpawnPointOnly = false;
  60895. this.angle = angle;
  60896. this.radius = radius;
  60897. }
  60898. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  60899. /**
  60900. * Gets or sets the radius of the emission cone
  60901. */
  60902. get: function () {
  60903. return this._radius;
  60904. },
  60905. set: function (value) {
  60906. this._radius = value;
  60907. this._buildHeight();
  60908. },
  60909. enumerable: true,
  60910. configurable: true
  60911. });
  60912. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  60913. /**
  60914. * Gets or sets the angle of the emission cone
  60915. */
  60916. get: function () {
  60917. return this._angle;
  60918. },
  60919. set: function (value) {
  60920. this._angle = value;
  60921. this._buildHeight();
  60922. },
  60923. enumerable: true,
  60924. configurable: true
  60925. });
  60926. ConeParticleEmitter.prototype._buildHeight = function () {
  60927. if (this._angle !== 0) {
  60928. this._height = this._radius / Math.tan(this._angle / 2);
  60929. }
  60930. else {
  60931. this._height = 1;
  60932. }
  60933. };
  60934. /**
  60935. * Called by the particle System when the direction is computed for the created particle.
  60936. * @param worldMatrix is the world matrix of the particle system
  60937. * @param directionToUpdate is the direction vector to update with the result
  60938. * @param particle is the particle we are computed the direction for
  60939. */
  60940. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60941. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  60942. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  60943. }
  60944. else {
  60945. // measure the direction Vector from the emitter to the particle.
  60946. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  60947. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60948. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60949. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  60950. direction.x += randX;
  60951. direction.y += randY;
  60952. direction.z += randZ;
  60953. direction.normalize();
  60954. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  60955. }
  60956. };
  60957. /**
  60958. * Called by the particle System when the position is computed for the created particle.
  60959. * @param worldMatrix is the world matrix of the particle system
  60960. * @param positionToUpdate is the position vector to update with the result
  60961. * @param particle is the particle we are computed the position for
  60962. */
  60963. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60964. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  60965. var h;
  60966. if (!this.emitFromSpawnPointOnly) {
  60967. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  60968. // Better distribution in a cone at normal angles.
  60969. h = 1 - h * h;
  60970. }
  60971. else {
  60972. h = 0.0001;
  60973. }
  60974. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  60975. radius = radius * h;
  60976. var randX = radius * Math.sin(s);
  60977. var randZ = radius * Math.cos(s);
  60978. var randY = h * this._height;
  60979. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  60980. };
  60981. /**
  60982. * Clones the current emitter and returns a copy of it
  60983. * @returns the new emitter
  60984. */
  60985. ConeParticleEmitter.prototype.clone = function () {
  60986. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  60987. BABYLON.Tools.DeepCopy(this, newOne);
  60988. return newOne;
  60989. };
  60990. /**
  60991. * Called by the GPUParticleSystem to setup the update shader
  60992. * @param effect defines the update shader
  60993. */
  60994. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  60995. effect.setFloat2("radius", this._radius, this.radiusRange);
  60996. effect.setFloat("coneAngle", this._angle);
  60997. effect.setFloat2("height", this._height, this.heightRange);
  60998. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60999. };
  61000. /**
  61001. * Returns a string to use to update the GPU particles update shader
  61002. * @returns a string containng the defines string
  61003. */
  61004. ConeParticleEmitter.prototype.getEffectDefines = function () {
  61005. var defines = "#define CONEEMITTER";
  61006. if (this.emitFromSpawnPointOnly) {
  61007. defines += "\n#define CONEEMITTERSPAWNPOINT";
  61008. }
  61009. return defines;
  61010. };
  61011. /**
  61012. * Returns the string "ConeParticleEmitter"
  61013. * @returns a string containing the class name
  61014. */
  61015. ConeParticleEmitter.prototype.getClassName = function () {
  61016. return "ConeParticleEmitter";
  61017. };
  61018. /**
  61019. * Serializes the particle system to a JSON object.
  61020. * @returns the JSON object
  61021. */
  61022. ConeParticleEmitter.prototype.serialize = function () {
  61023. var serializationObject = {};
  61024. serializationObject.type = this.getClassName();
  61025. serializationObject.radius = this._radius;
  61026. serializationObject.angle = this._angle;
  61027. serializationObject.directionRandomizer = this.directionRandomizer;
  61028. return serializationObject;
  61029. };
  61030. /**
  61031. * Parse properties from a JSON object
  61032. * @param serializationObject defines the JSON object
  61033. */
  61034. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  61035. this.radius = serializationObject.radius;
  61036. this.angle = serializationObject.angle;
  61037. this.directionRandomizer = serializationObject.directionRandomizer;
  61038. };
  61039. return ConeParticleEmitter;
  61040. }());
  61041. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  61042. })(BABYLON || (BABYLON = {}));
  61043. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  61044. var BABYLON;
  61045. (function (BABYLON) {
  61046. /**
  61047. * Particle emitter emitting particles from the inside of a sphere.
  61048. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  61049. */
  61050. var SphereParticleEmitter = /** @class */ (function () {
  61051. /**
  61052. * Creates a new instance SphereParticleEmitter
  61053. * @param radius the radius of the emission sphere (1 by default)
  61054. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61055. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61056. */
  61057. function SphereParticleEmitter(
  61058. /**
  61059. * The radius of the emission sphere.
  61060. */
  61061. radius,
  61062. /**
  61063. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61064. */
  61065. radiusRange,
  61066. /**
  61067. * How much to randomize the particle direction [0-1].
  61068. */
  61069. directionRandomizer) {
  61070. if (radius === void 0) { radius = 1; }
  61071. if (radiusRange === void 0) { radiusRange = 1; }
  61072. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61073. this.radius = radius;
  61074. this.radiusRange = radiusRange;
  61075. this.directionRandomizer = directionRandomizer;
  61076. }
  61077. /**
  61078. * Called by the particle System when the direction is computed for the created particle.
  61079. * @param worldMatrix is the world matrix of the particle system
  61080. * @param directionToUpdate is the direction vector to update with the result
  61081. * @param particle is the particle we are computed the direction for
  61082. */
  61083. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61084. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61085. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61086. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61087. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61088. direction.x += randX;
  61089. direction.y += randY;
  61090. direction.z += randZ;
  61091. direction.normalize();
  61092. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61093. };
  61094. /**
  61095. * Called by the particle System when the position is computed for the created particle.
  61096. * @param worldMatrix is the world matrix of the particle system
  61097. * @param positionToUpdate is the position vector to update with the result
  61098. * @param particle is the particle we are computed the position for
  61099. */
  61100. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61101. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  61102. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  61103. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61104. var theta = Math.acos(2 * v - 1);
  61105. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  61106. var randY = randRadius * Math.cos(theta);
  61107. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  61108. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61109. };
  61110. /**
  61111. * Clones the current emitter and returns a copy of it
  61112. * @returns the new emitter
  61113. */
  61114. SphereParticleEmitter.prototype.clone = function () {
  61115. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  61116. BABYLON.Tools.DeepCopy(this, newOne);
  61117. return newOne;
  61118. };
  61119. /**
  61120. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  61121. * @param effect defines the update shader
  61122. */
  61123. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  61124. effect.setFloat("radius", this.radius);
  61125. effect.setFloat("radiusRange", this.radiusRange);
  61126. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61127. };
  61128. /**
  61129. * Returns a string to use to update the GPU particles update shader
  61130. * @returns a string containng the defines string
  61131. */
  61132. SphereParticleEmitter.prototype.getEffectDefines = function () {
  61133. return "#define SPHEREEMITTER";
  61134. };
  61135. /**
  61136. * Returns the string "SphereParticleEmitter"
  61137. * @returns a string containing the class name
  61138. */
  61139. SphereParticleEmitter.prototype.getClassName = function () {
  61140. return "SphereParticleEmitter";
  61141. };
  61142. /**
  61143. * Serializes the particle system to a JSON object.
  61144. * @returns the JSON object
  61145. */
  61146. SphereParticleEmitter.prototype.serialize = function () {
  61147. var serializationObject = {};
  61148. serializationObject.type = this.getClassName();
  61149. serializationObject.radius = this.radius;
  61150. serializationObject.radiusRange = this.radiusRange;
  61151. serializationObject.directionRandomizer = this.directionRandomizer;
  61152. return serializationObject;
  61153. };
  61154. /**
  61155. * Parse properties from a JSON object
  61156. * @param serializationObject defines the JSON object
  61157. */
  61158. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  61159. this.radius = serializationObject.radius;
  61160. this.radiusRange = serializationObject.radiusRange;
  61161. this.directionRandomizer = serializationObject.directionRandomizer;
  61162. };
  61163. return SphereParticleEmitter;
  61164. }());
  61165. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  61166. /**
  61167. * Particle emitter emitting particles from the inside of a sphere.
  61168. * It emits the particles randomly between two vectors.
  61169. */
  61170. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  61171. __extends(SphereDirectedParticleEmitter, _super);
  61172. /**
  61173. * Creates a new instance SphereDirectedParticleEmitter
  61174. * @param radius the radius of the emission sphere (1 by default)
  61175. * @param direction1 the min limit of the emission direction (up vector by default)
  61176. * @param direction2 the max limit of the emission direction (up vector by default)
  61177. */
  61178. function SphereDirectedParticleEmitter(radius,
  61179. /**
  61180. * The min limit of the emission direction.
  61181. */
  61182. direction1,
  61183. /**
  61184. * The max limit of the emission direction.
  61185. */
  61186. direction2) {
  61187. if (radius === void 0) { radius = 1; }
  61188. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  61189. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  61190. var _this = _super.call(this, radius) || this;
  61191. _this.direction1 = direction1;
  61192. _this.direction2 = direction2;
  61193. return _this;
  61194. }
  61195. /**
  61196. * Called by the particle System when the direction is computed for the created particle.
  61197. * @param worldMatrix is the world matrix of the particle system
  61198. * @param directionToUpdate is the direction vector to update with the result
  61199. * @param particle is the particle we are computed the direction for
  61200. */
  61201. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61202. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61203. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61204. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61205. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61206. };
  61207. /**
  61208. * Clones the current emitter and returns a copy of it
  61209. * @returns the new emitter
  61210. */
  61211. SphereDirectedParticleEmitter.prototype.clone = function () {
  61212. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  61213. BABYLON.Tools.DeepCopy(this, newOne);
  61214. return newOne;
  61215. };
  61216. /**
  61217. * Called by the GPUParticleSystem to setup the update shader
  61218. * @param effect defines the update shader
  61219. */
  61220. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  61221. effect.setFloat("radius", this.radius);
  61222. effect.setFloat("radiusRange", this.radiusRange);
  61223. effect.setVector3("direction1", this.direction1);
  61224. effect.setVector3("direction2", this.direction2);
  61225. };
  61226. /**
  61227. * Returns a string to use to update the GPU particles update shader
  61228. * @returns a string containng the defines string
  61229. */
  61230. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  61231. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  61232. };
  61233. /**
  61234. * Returns the string "SphereDirectedParticleEmitter"
  61235. * @returns a string containing the class name
  61236. */
  61237. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  61238. return "SphereDirectedParticleEmitter";
  61239. };
  61240. /**
  61241. * Serializes the particle system to a JSON object.
  61242. * @returns the JSON object
  61243. */
  61244. SphereDirectedParticleEmitter.prototype.serialize = function () {
  61245. var serializationObject = _super.prototype.serialize.call(this);
  61246. serializationObject.direction1 = this.direction1.asArray();
  61247. serializationObject.direction2 = this.direction2.asArray();
  61248. return serializationObject;
  61249. };
  61250. /**
  61251. * Parse properties from a JSON object
  61252. * @param serializationObject defines the JSON object
  61253. */
  61254. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  61255. _super.prototype.parse.call(this, serializationObject);
  61256. this.direction1.copyFrom(serializationObject.direction1);
  61257. this.direction2.copyFrom(serializationObject.direction2);
  61258. };
  61259. return SphereDirectedParticleEmitter;
  61260. }(SphereParticleEmitter));
  61261. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  61262. })(BABYLON || (BABYLON = {}));
  61263. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  61264. var BABYLON;
  61265. (function (BABYLON) {
  61266. /**
  61267. * Particle emitter emitting particles from the inside of a hemisphere.
  61268. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  61269. */
  61270. var HemisphericParticleEmitter = /** @class */ (function () {
  61271. /**
  61272. * Creates a new instance HemisphericParticleEmitter
  61273. * @param radius the radius of the emission hemisphere (1 by default)
  61274. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61275. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61276. */
  61277. function HemisphericParticleEmitter(
  61278. /**
  61279. * The radius of the emission hemisphere.
  61280. */
  61281. radius,
  61282. /**
  61283. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61284. */
  61285. radiusRange,
  61286. /**
  61287. * How much to randomize the particle direction [0-1].
  61288. */
  61289. directionRandomizer) {
  61290. if (radius === void 0) { radius = 1; }
  61291. if (radiusRange === void 0) { radiusRange = 1; }
  61292. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61293. this.radius = radius;
  61294. this.radiusRange = radiusRange;
  61295. this.directionRandomizer = directionRandomizer;
  61296. }
  61297. /**
  61298. * Called by the particle System when the direction is computed for the created particle.
  61299. * @param worldMatrix is the world matrix of the particle system
  61300. * @param directionToUpdate is the direction vector to update with the result
  61301. * @param particle is the particle we are computed the direction for
  61302. */
  61303. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61304. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61305. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61306. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61307. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61308. direction.x += randX;
  61309. direction.y += randY;
  61310. direction.z += randZ;
  61311. direction.normalize();
  61312. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61313. };
  61314. /**
  61315. * Called by the particle System when the position is computed for the created particle.
  61316. * @param worldMatrix is the world matrix of the particle system
  61317. * @param positionToUpdate is the position vector to update with the result
  61318. * @param particle is the particle we are computed the position for
  61319. */
  61320. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61321. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  61322. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  61323. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61324. var theta = Math.acos(2 * v - 1);
  61325. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  61326. var randY = randRadius * Math.cos(theta);
  61327. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  61328. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  61329. };
  61330. /**
  61331. * Clones the current emitter and returns a copy of it
  61332. * @returns the new emitter
  61333. */
  61334. HemisphericParticleEmitter.prototype.clone = function () {
  61335. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  61336. BABYLON.Tools.DeepCopy(this, newOne);
  61337. return newOne;
  61338. };
  61339. /**
  61340. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  61341. * @param effect defines the update shader
  61342. */
  61343. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  61344. effect.setFloat("radius", this.radius);
  61345. effect.setFloat("radiusRange", this.radiusRange);
  61346. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61347. };
  61348. /**
  61349. * Returns a string to use to update the GPU particles update shader
  61350. * @returns a string containng the defines string
  61351. */
  61352. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  61353. return "#define HEMISPHERICEMITTER";
  61354. };
  61355. /**
  61356. * Returns the string "HemisphericParticleEmitter"
  61357. * @returns a string containing the class name
  61358. */
  61359. HemisphericParticleEmitter.prototype.getClassName = function () {
  61360. return "HemisphericParticleEmitter";
  61361. };
  61362. /**
  61363. * Serializes the particle system to a JSON object.
  61364. * @returns the JSON object
  61365. */
  61366. HemisphericParticleEmitter.prototype.serialize = function () {
  61367. var serializationObject = {};
  61368. serializationObject.type = this.getClassName();
  61369. serializationObject.radius = this.radius;
  61370. serializationObject.radiusRange = this.radiusRange;
  61371. serializationObject.directionRandomizer = this.directionRandomizer;
  61372. return serializationObject;
  61373. };
  61374. /**
  61375. * Parse properties from a JSON object
  61376. * @param serializationObject defines the JSON object
  61377. */
  61378. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  61379. this.radius = serializationObject.radius;
  61380. this.radiusRange = serializationObject.radiusRange;
  61381. this.directionRandomizer = serializationObject.directionRandomizer;
  61382. };
  61383. return HemisphericParticleEmitter;
  61384. }());
  61385. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  61386. })(BABYLON || (BABYLON = {}));
  61387. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  61388. var BABYLON;
  61389. (function (BABYLON) {
  61390. /**
  61391. * Particle emitter emitting particles from a point.
  61392. * It emits the particles randomly between 2 given directions.
  61393. */
  61394. var PointParticleEmitter = /** @class */ (function () {
  61395. /**
  61396. * Creates a new instance PointParticleEmitter
  61397. */
  61398. function PointParticleEmitter() {
  61399. /**
  61400. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61401. */
  61402. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  61403. /**
  61404. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61405. */
  61406. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  61407. }
  61408. /**
  61409. * Called by the particle System when the direction is computed for the created particle.
  61410. * @param worldMatrix is the world matrix of the particle system
  61411. * @param directionToUpdate is the direction vector to update with the result
  61412. * @param particle is the particle we are computed the direction for
  61413. */
  61414. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61415. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61416. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61417. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61418. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61419. };
  61420. /**
  61421. * Called by the particle System when the position is computed for the created particle.
  61422. * @param worldMatrix is the world matrix of the particle system
  61423. * @param positionToUpdate is the position vector to update with the result
  61424. * @param particle is the particle we are computed the position for
  61425. */
  61426. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61427. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  61428. };
  61429. /**
  61430. * Clones the current emitter and returns a copy of it
  61431. * @returns the new emitter
  61432. */
  61433. PointParticleEmitter.prototype.clone = function () {
  61434. var newOne = new PointParticleEmitter();
  61435. BABYLON.Tools.DeepCopy(this, newOne);
  61436. return newOne;
  61437. };
  61438. /**
  61439. * Called by the GPUParticleSystem to setup the update shader
  61440. * @param effect defines the update shader
  61441. */
  61442. PointParticleEmitter.prototype.applyToShader = function (effect) {
  61443. effect.setVector3("direction1", this.direction1);
  61444. effect.setVector3("direction2", this.direction2);
  61445. };
  61446. /**
  61447. * Returns a string to use to update the GPU particles update shader
  61448. * @returns a string containng the defines string
  61449. */
  61450. PointParticleEmitter.prototype.getEffectDefines = function () {
  61451. return "#define POINTEMITTER";
  61452. };
  61453. /**
  61454. * Returns the string "PointParticleEmitter"
  61455. * @returns a string containing the class name
  61456. */
  61457. PointParticleEmitter.prototype.getClassName = function () {
  61458. return "PointParticleEmitter";
  61459. };
  61460. /**
  61461. * Serializes the particle system to a JSON object.
  61462. * @returns the JSON object
  61463. */
  61464. PointParticleEmitter.prototype.serialize = function () {
  61465. var serializationObject = {};
  61466. serializationObject.type = this.getClassName();
  61467. serializationObject.direction1 = this.direction1.asArray();
  61468. serializationObject.direction2 = this.direction2.asArray();
  61469. return serializationObject;
  61470. };
  61471. /**
  61472. * Parse properties from a JSON object
  61473. * @param serializationObject defines the JSON object
  61474. */
  61475. PointParticleEmitter.prototype.parse = function (serializationObject) {
  61476. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  61477. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  61478. };
  61479. return PointParticleEmitter;
  61480. }());
  61481. BABYLON.PointParticleEmitter = PointParticleEmitter;
  61482. })(BABYLON || (BABYLON = {}));
  61483. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  61484. var BABYLON;
  61485. (function (BABYLON) {
  61486. // Adds the parsers to the scene parsers.
  61487. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  61488. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  61489. if (!individualParser) {
  61490. return;
  61491. }
  61492. // Particles Systems
  61493. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61494. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61495. var parsedParticleSystem = parsedData.particleSystems[index];
  61496. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  61497. }
  61498. }
  61499. });
  61500. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  61501. if (parsedParticleSystem.activeParticleCount) {
  61502. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61503. return ps;
  61504. }
  61505. else {
  61506. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61507. return ps;
  61508. }
  61509. });
  61510. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  61511. if (uniformsNames === void 0) { uniformsNames = []; }
  61512. if (samplers === void 0) { samplers = []; }
  61513. if (defines === void 0) { defines = ""; }
  61514. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  61515. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  61516. if (defines.indexOf(" BILLBOARD") === -1) {
  61517. defines += "\n#define BILLBOARD\n";
  61518. }
  61519. if (samplers.indexOf("diffuseSampler") === -1) {
  61520. samplers.push("diffuseSampler");
  61521. }
  61522. return this.createEffect({
  61523. vertex: "particles",
  61524. fragmentElement: fragmentName
  61525. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  61526. };
  61527. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  61528. var results = new Array();
  61529. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  61530. var particleSystem = this.getScene().particleSystems[index];
  61531. if (particleSystem.emitter === this) {
  61532. results.push(particleSystem);
  61533. }
  61534. }
  61535. return results;
  61536. };
  61537. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  61538. var results = new Array();
  61539. var descendants = this.getDescendants();
  61540. descendants.push(this);
  61541. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  61542. var particleSystem = this.getScene().particleSystems[index];
  61543. var emitter = particleSystem.emitter;
  61544. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  61545. results.push(particleSystem);
  61546. }
  61547. }
  61548. return results;
  61549. };
  61550. })(BABYLON || (BABYLON = {}));
  61551. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  61552. var BABYLON;
  61553. (function (BABYLON) {
  61554. /**
  61555. * Type of sub emitter
  61556. */
  61557. var SubEmitterType;
  61558. (function (SubEmitterType) {
  61559. /**
  61560. * Attached to the particle over it's lifetime
  61561. */
  61562. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  61563. /**
  61564. * Created when the particle dies
  61565. */
  61566. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  61567. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  61568. /**
  61569. * Sub emitter class used to emit particles from an existing particle
  61570. */
  61571. var SubEmitter = /** @class */ (function () {
  61572. /**
  61573. * Creates a sub emitter
  61574. * @param particleSystem the particle system to be used by the sub emitter
  61575. */
  61576. function SubEmitter(
  61577. /**
  61578. * the particle system to be used by the sub emitter
  61579. */
  61580. particleSystem) {
  61581. this.particleSystem = particleSystem;
  61582. /**
  61583. * Type of the submitter (Default: END)
  61584. */
  61585. this.type = SubEmitterType.END;
  61586. /**
  61587. * 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)
  61588. * Note: This only is supported when using an emitter of type Mesh
  61589. */
  61590. this.inheritDirection = false;
  61591. /**
  61592. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  61593. */
  61594. this.inheritedVelocityAmount = 0;
  61595. }
  61596. /**
  61597. * Clones the sub emitter
  61598. * @returns the cloned sub emitter
  61599. */
  61600. SubEmitter.prototype.clone = function () {
  61601. // Clone particle system
  61602. var emitter = this.particleSystem.emitter;
  61603. if (!emitter) {
  61604. emitter = new BABYLON.Vector3();
  61605. }
  61606. else if (emitter instanceof BABYLON.Vector3) {
  61607. emitter = emitter.clone();
  61608. }
  61609. else if (emitter instanceof BABYLON.AbstractMesh) {
  61610. emitter = new BABYLON.Mesh("", emitter.getScene());
  61611. emitter.isVisible = false;
  61612. }
  61613. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  61614. // Clone properties
  61615. clone.type = this.type;
  61616. clone.inheritDirection = this.inheritDirection;
  61617. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  61618. clone.particleSystem._disposeEmitterOnDispose = true;
  61619. clone.particleSystem.disposeOnStop = true;
  61620. return clone;
  61621. };
  61622. /**
  61623. * Serialize current object to a JSON object
  61624. * @returns the serialized object
  61625. */
  61626. SubEmitter.prototype.serialize = function () {
  61627. var serializationObject = {};
  61628. serializationObject.type = this.type;
  61629. serializationObject.inheritDirection = this.inheritDirection;
  61630. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  61631. serializationObject.particleSystem = this.particleSystem.serialize();
  61632. return serializationObject;
  61633. };
  61634. /**
  61635. * Creates a new SubEmitter from a serialized JSON version
  61636. * @param serializationObject defines the JSON object to read from
  61637. * @param scene defines the hosting scene
  61638. * @param rootUrl defines the rootUrl for data loading
  61639. * @returns a new SubEmitter
  61640. */
  61641. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  61642. var system = serializationObject.particleSystem;
  61643. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  61644. subEmitter.type = serializationObject.type;
  61645. subEmitter.inheritDirection = serializationObject.inheritDirection;
  61646. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  61647. subEmitter.particleSystem._isSubEmitter = true;
  61648. return subEmitter;
  61649. };
  61650. /** Release associated resources */
  61651. SubEmitter.prototype.dispose = function () {
  61652. this.particleSystem.dispose();
  61653. };
  61654. return SubEmitter;
  61655. }());
  61656. BABYLON.SubEmitter = SubEmitter;
  61657. })(BABYLON || (BABYLON = {}));
  61658. //# sourceMappingURL=babylon.subEmitter.js.map
  61659. var BABYLON;
  61660. (function (BABYLON) {
  61661. /**
  61662. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  61663. *
  61664. * This returned material effects how the mesh will look based on the code in the shaders.
  61665. *
  61666. * @see http://doc.babylonjs.com/how_to/shader_material
  61667. */
  61668. var ShaderMaterial = /** @class */ (function (_super) {
  61669. __extends(ShaderMaterial, _super);
  61670. /**
  61671. * Instantiate a new shader material.
  61672. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
  61673. * This returned material effects how the mesh will look based on the code in the shaders.
  61674. * @see http://doc.babylonjs.com/how_to/shader_material
  61675. * @param name Define the name of the material in the scene
  61676. * @param scene Define the scene the material belongs to
  61677. * @param shaderPath Defines the route to the shader code in one of three ways:
  61678. * - object - { vertex: "custom", fragment: "custom" }, used with BABYLON.Effect.ShadersStore["customVertexShader"] and BABYLON.Effect.ShadersStore["customFragmentShader"]
  61679. * - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in <script> tags
  61680. * - string - "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
  61681. * @param options Define the options used to create the shader
  61682. */
  61683. function ShaderMaterial(name, scene, shaderPath, options) {
  61684. if (options === void 0) { options = {}; }
  61685. var _this = _super.call(this, name, scene) || this;
  61686. _this._textures = {};
  61687. _this._textureArrays = {};
  61688. _this._floats = {};
  61689. _this._ints = {};
  61690. _this._floatsArrays = {};
  61691. _this._colors3 = {};
  61692. _this._colors3Arrays = {};
  61693. _this._colors4 = {};
  61694. _this._vectors2 = {};
  61695. _this._vectors3 = {};
  61696. _this._vectors4 = {};
  61697. _this._matrices = {};
  61698. _this._matrices3x3 = {};
  61699. _this._matrices2x2 = {};
  61700. _this._vectors2Arrays = {};
  61701. _this._vectors3Arrays = {};
  61702. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  61703. _this._shaderPath = shaderPath;
  61704. _this._options = __assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], defines: [] }, options);
  61705. return _this;
  61706. }
  61707. /**
  61708. * Gets the current class name of the material e.g. "ShaderMaterial"
  61709. * Mainly use in serialization.
  61710. * @returns the class name
  61711. */
  61712. ShaderMaterial.prototype.getClassName = function () {
  61713. return "ShaderMaterial";
  61714. };
  61715. /**
  61716. * Specifies if the material will require alpha blending
  61717. * @returns a boolean specifying if alpha blending is needed
  61718. */
  61719. ShaderMaterial.prototype.needAlphaBlending = function () {
  61720. return (this.alpha < 1.0);
  61721. };
  61722. /**
  61723. * Specifies if this material should be rendered in alpha test mode
  61724. * @returns a boolean specifying if an alpha test is needed.
  61725. */
  61726. ShaderMaterial.prototype.needAlphaTesting = function () {
  61727. return this._options.needAlphaTesting;
  61728. };
  61729. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  61730. if (this._options.uniforms.indexOf(uniformName) === -1) {
  61731. this._options.uniforms.push(uniformName);
  61732. }
  61733. };
  61734. /**
  61735. * Set a texture in the shader.
  61736. * @param name Define the name of the uniform samplers as defined in the shader
  61737. * @param texture Define the texture to bind to this sampler
  61738. * @return the material itself allowing "fluent" like uniform updates
  61739. */
  61740. ShaderMaterial.prototype.setTexture = function (name, texture) {
  61741. if (this._options.samplers.indexOf(name) === -1) {
  61742. this._options.samplers.push(name);
  61743. }
  61744. this._textures[name] = texture;
  61745. return this;
  61746. };
  61747. /**
  61748. * Set a texture array in the shader.
  61749. * @param name Define the name of the uniform sampler array as defined in the shader
  61750. * @param textures Define the list of textures to bind to this sampler
  61751. * @return the material itself allowing "fluent" like uniform updates
  61752. */
  61753. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  61754. if (this._options.samplers.indexOf(name) === -1) {
  61755. this._options.samplers.push(name);
  61756. }
  61757. this._checkUniform(name);
  61758. this._textureArrays[name] = textures;
  61759. return this;
  61760. };
  61761. /**
  61762. * Set a float in the shader.
  61763. * @param name Define the name of the uniform as defined in the shader
  61764. * @param value Define the value to give to the uniform
  61765. * @return the material itself allowing "fluent" like uniform updates
  61766. */
  61767. ShaderMaterial.prototype.setFloat = function (name, value) {
  61768. this._checkUniform(name);
  61769. this._floats[name] = value;
  61770. return this;
  61771. };
  61772. /**
  61773. * Set a int in the shader.
  61774. * @param name Define the name of the uniform as defined in the shader
  61775. * @param value Define the value to give to the uniform
  61776. * @return the material itself allowing "fluent" like uniform updates
  61777. */
  61778. ShaderMaterial.prototype.setInt = function (name, value) {
  61779. this._checkUniform(name);
  61780. this._ints[name] = value;
  61781. return this;
  61782. };
  61783. /**
  61784. * Set an array of floats in the shader.
  61785. * @param name Define the name of the uniform as defined in the shader
  61786. * @param value Define the value to give to the uniform
  61787. * @return the material itself allowing "fluent" like uniform updates
  61788. */
  61789. ShaderMaterial.prototype.setFloats = function (name, value) {
  61790. this._checkUniform(name);
  61791. this._floatsArrays[name] = value;
  61792. return this;
  61793. };
  61794. /**
  61795. * Set a vec3 in the shader from a Color3.
  61796. * @param name Define the name of the uniform as defined in the shader
  61797. * @param value Define the value to give to the uniform
  61798. * @return the material itself allowing "fluent" like uniform updates
  61799. */
  61800. ShaderMaterial.prototype.setColor3 = function (name, value) {
  61801. this._checkUniform(name);
  61802. this._colors3[name] = value;
  61803. return this;
  61804. };
  61805. /**
  61806. * Set a vec3 array in the shader from a Color3 array.
  61807. * @param name Define the name of the uniform as defined in the shader
  61808. * @param value Define the value to give to the uniform
  61809. * @return the material itself allowing "fluent" like uniform updates
  61810. */
  61811. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  61812. this._checkUniform(name);
  61813. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  61814. color.toArray(arr, arr.length);
  61815. return arr;
  61816. }, []);
  61817. return this;
  61818. };
  61819. /**
  61820. * Set a vec4 in the shader from a Color4.
  61821. * @param name Define the name of the uniform as defined in the shader
  61822. * @param value Define the value to give to the uniform
  61823. * @return the material itself allowing "fluent" like uniform updates
  61824. */
  61825. ShaderMaterial.prototype.setColor4 = function (name, value) {
  61826. this._checkUniform(name);
  61827. this._colors4[name] = value;
  61828. return this;
  61829. };
  61830. /**
  61831. * Set a vec2 in the shader from a Vector2.
  61832. * @param name Define the name of the uniform as defined in the shader
  61833. * @param value Define the value to give to the uniform
  61834. * @return the material itself allowing "fluent" like uniform updates
  61835. */
  61836. ShaderMaterial.prototype.setVector2 = function (name, value) {
  61837. this._checkUniform(name);
  61838. this._vectors2[name] = value;
  61839. return this;
  61840. };
  61841. /**
  61842. * Set a vec3 in the shader from a Vector3.
  61843. * @param name Define the name of the uniform as defined in the shader
  61844. * @param value Define the value to give to the uniform
  61845. * @return the material itself allowing "fluent" like uniform updates
  61846. */
  61847. ShaderMaterial.prototype.setVector3 = function (name, value) {
  61848. this._checkUniform(name);
  61849. this._vectors3[name] = value;
  61850. return this;
  61851. };
  61852. /**
  61853. * Set a vec4 in the shader from a Vector4.
  61854. * @param name Define the name of the uniform as defined in the shader
  61855. * @param value Define the value to give to the uniform
  61856. * @return the material itself allowing "fluent" like uniform updates
  61857. */
  61858. ShaderMaterial.prototype.setVector4 = function (name, value) {
  61859. this._checkUniform(name);
  61860. this._vectors4[name] = value;
  61861. return this;
  61862. };
  61863. /**
  61864. * Set a mat4 in the shader from a Matrix.
  61865. * @param name Define the name of the uniform as defined in the shader
  61866. * @param value Define the value to give to the uniform
  61867. * @return the material itself allowing "fluent" like uniform updates
  61868. */
  61869. ShaderMaterial.prototype.setMatrix = function (name, value) {
  61870. this._checkUniform(name);
  61871. this._matrices[name] = value;
  61872. return this;
  61873. };
  61874. /**
  61875. * Set a mat3 in the shader from a Float32Array.
  61876. * @param name Define the name of the uniform as defined in the shader
  61877. * @param value Define the value to give to the uniform
  61878. * @return the material itself allowing "fluent" like uniform updates
  61879. */
  61880. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  61881. this._checkUniform(name);
  61882. this._matrices3x3[name] = value;
  61883. return this;
  61884. };
  61885. /**
  61886. * Set a mat2 in the shader from a Float32Array.
  61887. * @param name Define the name of the uniform as defined in the shader
  61888. * @param value Define the value to give to the uniform
  61889. * @return the material itself allowing "fluent" like uniform updates
  61890. */
  61891. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  61892. this._checkUniform(name);
  61893. this._matrices2x2[name] = value;
  61894. return this;
  61895. };
  61896. /**
  61897. * Set a vec2 array in the shader from a number array.
  61898. * @param name Define the name of the uniform as defined in the shader
  61899. * @param value Define the value to give to the uniform
  61900. * @return the material itself allowing "fluent" like uniform updates
  61901. */
  61902. ShaderMaterial.prototype.setArray2 = function (name, value) {
  61903. this._checkUniform(name);
  61904. this._vectors2Arrays[name] = value;
  61905. return this;
  61906. };
  61907. /**
  61908. * Set a vec3 array in the shader from a number array.
  61909. * @param name Define the name of the uniform as defined in the shader
  61910. * @param value Define the value to give to the uniform
  61911. * @return the material itself allowing "fluent" like uniform updates
  61912. */
  61913. ShaderMaterial.prototype.setArray3 = function (name, value) {
  61914. this._checkUniform(name);
  61915. this._vectors3Arrays[name] = value;
  61916. return this;
  61917. };
  61918. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  61919. if (!mesh) {
  61920. return true;
  61921. }
  61922. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  61923. return false;
  61924. }
  61925. return false;
  61926. };
  61927. /**
  61928. * Checks if the material is ready to render the requested mesh
  61929. * @param mesh Define the mesh to render
  61930. * @param useInstances Define whether or not the material is used with instances
  61931. * @returns true if ready, otherwise false
  61932. */
  61933. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  61934. var scene = this.getScene();
  61935. var engine = scene.getEngine();
  61936. if (!this.checkReadyOnEveryCall) {
  61937. if (this._renderId === scene.getRenderId()) {
  61938. if (this._checkCache(scene, mesh, useInstances)) {
  61939. return true;
  61940. }
  61941. }
  61942. }
  61943. // Instances
  61944. var defines = [];
  61945. var attribs = [];
  61946. var fallbacks = new BABYLON.EffectFallbacks();
  61947. for (var index = 0; index < this._options.defines.length; index++) {
  61948. defines.push(this._options.defines[index]);
  61949. }
  61950. for (var index = 0; index < this._options.attributes.length; index++) {
  61951. attribs.push(this._options.attributes[index]);
  61952. }
  61953. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  61954. attribs.push(BABYLON.VertexBuffer.ColorKind);
  61955. defines.push("#define VERTEXCOLOR");
  61956. }
  61957. if (useInstances) {
  61958. defines.push("#define INSTANCES");
  61959. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  61960. }
  61961. // Bones
  61962. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61963. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61964. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61965. if (mesh.numBoneInfluencers > 4) {
  61966. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61967. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61968. }
  61969. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61970. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61971. fallbacks.addCPUSkinningFallback(0, mesh);
  61972. if (this._options.uniforms.indexOf("mBones") === -1) {
  61973. this._options.uniforms.push("mBones");
  61974. }
  61975. }
  61976. else {
  61977. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61978. }
  61979. // Textures
  61980. for (var name in this._textures) {
  61981. if (!this._textures[name].isReady()) {
  61982. return false;
  61983. }
  61984. }
  61985. // Alpha test
  61986. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  61987. defines.push("#define ALPHATEST");
  61988. }
  61989. var previousEffect = this._effect;
  61990. var join = defines.join("\n");
  61991. this._effect = engine.createEffect(this._shaderPath, {
  61992. attributes: attribs,
  61993. uniformsNames: this._options.uniforms,
  61994. uniformBuffersNames: this._options.uniformBuffers,
  61995. samplers: this._options.samplers,
  61996. defines: join,
  61997. fallbacks: fallbacks,
  61998. onCompiled: this.onCompiled,
  61999. onError: this.onError
  62000. }, engine);
  62001. if (!this._effect.isReady()) {
  62002. return false;
  62003. }
  62004. if (previousEffect !== this._effect) {
  62005. scene.resetCachedMaterial();
  62006. }
  62007. this._renderId = scene.getRenderId();
  62008. return true;
  62009. };
  62010. /**
  62011. * Binds the world matrix to the material
  62012. * @param world defines the world transformation matrix
  62013. */
  62014. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  62015. var scene = this.getScene();
  62016. if (!this._effect) {
  62017. return;
  62018. }
  62019. if (this._options.uniforms.indexOf("world") !== -1) {
  62020. this._effect.setMatrix("world", world);
  62021. }
  62022. if (this._options.uniforms.indexOf("worldView") !== -1) {
  62023. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  62024. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  62025. }
  62026. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  62027. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  62028. }
  62029. };
  62030. /**
  62031. * Binds the material to the mesh
  62032. * @param world defines the world transformation matrix
  62033. * @param mesh defines the mesh to bind the material to
  62034. */
  62035. ShaderMaterial.prototype.bind = function (world, mesh) {
  62036. // Std values
  62037. this.bindOnlyWorldMatrix(world);
  62038. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  62039. if (this._options.uniforms.indexOf("view") !== -1) {
  62040. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  62041. }
  62042. if (this._options.uniforms.indexOf("projection") !== -1) {
  62043. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  62044. }
  62045. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  62046. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  62047. }
  62048. // Bones
  62049. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  62050. var name;
  62051. // Texture
  62052. for (name in this._textures) {
  62053. this._effect.setTexture(name, this._textures[name]);
  62054. }
  62055. // Texture arrays
  62056. for (name in this._textureArrays) {
  62057. this._effect.setTextureArray(name, this._textureArrays[name]);
  62058. }
  62059. // Int
  62060. for (name in this._ints) {
  62061. this._effect.setInt(name, this._ints[name]);
  62062. }
  62063. // Float
  62064. for (name in this._floats) {
  62065. this._effect.setFloat(name, this._floats[name]);
  62066. }
  62067. // Floats
  62068. for (name in this._floatsArrays) {
  62069. this._effect.setArray(name, this._floatsArrays[name]);
  62070. }
  62071. // Color3
  62072. for (name in this._colors3) {
  62073. this._effect.setColor3(name, this._colors3[name]);
  62074. }
  62075. for (name in this._colors3Arrays) {
  62076. this._effect.setArray3(name, this._colors3Arrays[name]);
  62077. }
  62078. // Color4
  62079. for (name in this._colors4) {
  62080. var color = this._colors4[name];
  62081. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  62082. }
  62083. // Vector2
  62084. for (name in this._vectors2) {
  62085. this._effect.setVector2(name, this._vectors2[name]);
  62086. }
  62087. // Vector3
  62088. for (name in this._vectors3) {
  62089. this._effect.setVector3(name, this._vectors3[name]);
  62090. }
  62091. // Vector4
  62092. for (name in this._vectors4) {
  62093. this._effect.setVector4(name, this._vectors4[name]);
  62094. }
  62095. // Matrix
  62096. for (name in this._matrices) {
  62097. this._effect.setMatrix(name, this._matrices[name]);
  62098. }
  62099. // Matrix 3x3
  62100. for (name in this._matrices3x3) {
  62101. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  62102. }
  62103. // Matrix 2x2
  62104. for (name in this._matrices2x2) {
  62105. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  62106. }
  62107. // Vector2Array
  62108. for (name in this._vectors2Arrays) {
  62109. this._effect.setArray2(name, this._vectors2Arrays[name]);
  62110. }
  62111. // Vector3Array
  62112. for (name in this._vectors3Arrays) {
  62113. this._effect.setArray3(name, this._vectors3Arrays[name]);
  62114. }
  62115. }
  62116. this._afterBind(mesh);
  62117. };
  62118. /**
  62119. * Gets the active textures from the material
  62120. * @returns an array of textures
  62121. */
  62122. ShaderMaterial.prototype.getActiveTextures = function () {
  62123. var activeTextures = _super.prototype.getActiveTextures.call(this);
  62124. for (var name in this._textures) {
  62125. activeTextures.push(this._textures[name]);
  62126. }
  62127. for (var name in this._textureArrays) {
  62128. var array = this._textureArrays[name];
  62129. for (var index = 0; index < array.length; index++) {
  62130. activeTextures.push(array[index]);
  62131. }
  62132. }
  62133. return activeTextures;
  62134. };
  62135. /**
  62136. * Specifies if the material uses a texture
  62137. * @param texture defines the texture to check against the material
  62138. * @returns a boolean specifying if the material uses the texture
  62139. */
  62140. ShaderMaterial.prototype.hasTexture = function (texture) {
  62141. if (_super.prototype.hasTexture.call(this, texture)) {
  62142. return true;
  62143. }
  62144. for (var name in this._textures) {
  62145. if (this._textures[name] === texture) {
  62146. return true;
  62147. }
  62148. }
  62149. for (var name in this._textureArrays) {
  62150. var array = this._textureArrays[name];
  62151. for (var index = 0; index < array.length; index++) {
  62152. if (array[index] === texture) {
  62153. return true;
  62154. }
  62155. }
  62156. }
  62157. return false;
  62158. };
  62159. /**
  62160. * Makes a duplicate of the material, and gives it a new name
  62161. * @param name defines the new name for the duplicated material
  62162. * @returns the cloned material
  62163. */
  62164. ShaderMaterial.prototype.clone = function (name) {
  62165. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  62166. return newShaderMaterial;
  62167. };
  62168. /**
  62169. * Disposes the material
  62170. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  62171. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  62172. */
  62173. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  62174. if (forceDisposeTextures) {
  62175. var name;
  62176. for (name in this._textures) {
  62177. this._textures[name].dispose();
  62178. }
  62179. for (name in this._textureArrays) {
  62180. var array = this._textureArrays[name];
  62181. for (var index = 0; index < array.length; index++) {
  62182. array[index].dispose();
  62183. }
  62184. }
  62185. }
  62186. this._textures = {};
  62187. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62188. };
  62189. /**
  62190. * Serializes this material in a JSON representation
  62191. * @returns the serialized material object
  62192. */
  62193. ShaderMaterial.prototype.serialize = function () {
  62194. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  62195. serializationObject.customType = "BABYLON.ShaderMaterial";
  62196. serializationObject.options = this._options;
  62197. serializationObject.shaderPath = this._shaderPath;
  62198. var name;
  62199. // Texture
  62200. serializationObject.textures = {};
  62201. for (name in this._textures) {
  62202. serializationObject.textures[name] = this._textures[name].serialize();
  62203. }
  62204. // Texture arrays
  62205. serializationObject.textureArrays = {};
  62206. for (name in this._textureArrays) {
  62207. serializationObject.textureArrays[name] = [];
  62208. var array = this._textureArrays[name];
  62209. for (var index = 0; index < array.length; index++) {
  62210. serializationObject.textureArrays[name].push(array[index].serialize());
  62211. }
  62212. }
  62213. // Float
  62214. serializationObject.floats = {};
  62215. for (name in this._floats) {
  62216. serializationObject.floats[name] = this._floats[name];
  62217. }
  62218. // Float s
  62219. serializationObject.FloatArrays = {};
  62220. for (name in this._floatsArrays) {
  62221. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  62222. }
  62223. // Color3
  62224. serializationObject.colors3 = {};
  62225. for (name in this._colors3) {
  62226. serializationObject.colors3[name] = this._colors3[name].asArray();
  62227. }
  62228. // Color3 array
  62229. serializationObject.colors3Arrays = {};
  62230. for (name in this._colors3Arrays) {
  62231. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  62232. }
  62233. // Color4
  62234. serializationObject.colors4 = {};
  62235. for (name in this._colors4) {
  62236. serializationObject.colors4[name] = this._colors4[name].asArray();
  62237. }
  62238. // Vector2
  62239. serializationObject.vectors2 = {};
  62240. for (name in this._vectors2) {
  62241. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  62242. }
  62243. // Vector3
  62244. serializationObject.vectors3 = {};
  62245. for (name in this._vectors3) {
  62246. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  62247. }
  62248. // Vector4
  62249. serializationObject.vectors4 = {};
  62250. for (name in this._vectors4) {
  62251. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  62252. }
  62253. // Matrix
  62254. serializationObject.matrices = {};
  62255. for (name in this._matrices) {
  62256. serializationObject.matrices[name] = this._matrices[name].asArray();
  62257. }
  62258. // Matrix 3x3
  62259. serializationObject.matrices3x3 = {};
  62260. for (name in this._matrices3x3) {
  62261. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  62262. }
  62263. // Matrix 2x2
  62264. serializationObject.matrices2x2 = {};
  62265. for (name in this._matrices2x2) {
  62266. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  62267. }
  62268. // Vector2Array
  62269. serializationObject.vectors2Arrays = {};
  62270. for (name in this._vectors2Arrays) {
  62271. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  62272. }
  62273. // Vector3Array
  62274. serializationObject.vectors3Arrays = {};
  62275. for (name in this._vectors3Arrays) {
  62276. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  62277. }
  62278. return serializationObject;
  62279. };
  62280. /**
  62281. * Creates a shader material from parsed shader material data
  62282. * @param source defines the JSON represnetation of the material
  62283. * @param scene defines the hosting scene
  62284. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  62285. * @returns a new material
  62286. */
  62287. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  62288. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  62289. var name;
  62290. // Texture
  62291. for (name in source.textures) {
  62292. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  62293. }
  62294. // Texture arrays
  62295. for (name in source.textureArrays) {
  62296. var array = source.textureArrays[name];
  62297. var textureArray = new Array();
  62298. for (var index = 0; index < array.length; index++) {
  62299. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  62300. }
  62301. material.setTextureArray(name, textureArray);
  62302. }
  62303. // Float
  62304. for (name in source.floats) {
  62305. material.setFloat(name, source.floats[name]);
  62306. }
  62307. // Float s
  62308. for (name in source.floatsArrays) {
  62309. material.setFloats(name, source.floatsArrays[name]);
  62310. }
  62311. // Color3
  62312. for (name in source.colors3) {
  62313. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  62314. }
  62315. // Color3 arrays
  62316. for (name in source.colors3Arrays) {
  62317. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  62318. if (i % 3 === 0) {
  62319. arr.push([num]);
  62320. }
  62321. else {
  62322. arr[arr.length - 1].push(num);
  62323. }
  62324. return arr;
  62325. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  62326. material.setColor3Array(name, colors);
  62327. }
  62328. // Color4
  62329. for (name in source.colors4) {
  62330. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  62331. }
  62332. // Vector2
  62333. for (name in source.vectors2) {
  62334. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  62335. }
  62336. // Vector3
  62337. for (name in source.vectors3) {
  62338. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  62339. }
  62340. // Vector4
  62341. for (name in source.vectors4) {
  62342. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  62343. }
  62344. // Matrix
  62345. for (name in source.matrices) {
  62346. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  62347. }
  62348. // Matrix 3x3
  62349. for (name in source.matrices3x3) {
  62350. material.setMatrix3x3(name, source.matrices3x3[name]);
  62351. }
  62352. // Matrix 2x2
  62353. for (name in source.matrices2x2) {
  62354. material.setMatrix2x2(name, source.matrices2x2[name]);
  62355. }
  62356. // Vector2Array
  62357. for (name in source.vectors2Arrays) {
  62358. material.setArray2(name, source.vectors2Arrays[name]);
  62359. }
  62360. // Vector3Array
  62361. for (name in source.vectors3Arrays) {
  62362. material.setArray3(name, source.vectors3Arrays[name]);
  62363. }
  62364. return material;
  62365. };
  62366. return ShaderMaterial;
  62367. }(BABYLON.Material));
  62368. BABYLON.ShaderMaterial = ShaderMaterial;
  62369. })(BABYLON || (BABYLON = {}));
  62370. //# sourceMappingURL=babylon.shaderMaterial.js.map
  62371. var BABYLON;
  62372. (function (BABYLON) {
  62373. var GroundMesh = /** @class */ (function (_super) {
  62374. __extends(GroundMesh, _super);
  62375. function GroundMesh(name, scene) {
  62376. var _this = _super.call(this, name, scene) || this;
  62377. _this.generateOctree = false;
  62378. return _this;
  62379. }
  62380. GroundMesh.prototype.getClassName = function () {
  62381. return "GroundMesh";
  62382. };
  62383. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  62384. get: function () {
  62385. return Math.min(this._subdivisionsX, this._subdivisionsY);
  62386. },
  62387. enumerable: true,
  62388. configurable: true
  62389. });
  62390. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  62391. get: function () {
  62392. return this._subdivisionsX;
  62393. },
  62394. enumerable: true,
  62395. configurable: true
  62396. });
  62397. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  62398. get: function () {
  62399. return this._subdivisionsY;
  62400. },
  62401. enumerable: true,
  62402. configurable: true
  62403. });
  62404. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  62405. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  62406. this._subdivisionsX = chunksCount;
  62407. this._subdivisionsY = chunksCount;
  62408. this.subdivide(chunksCount);
  62409. // Call the octree system optimization if it is defined.
  62410. var thisAsAny = this;
  62411. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  62412. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  62413. }
  62414. };
  62415. /**
  62416. * Returns a height (y) value in the Worl system :
  62417. * the ground altitude at the coordinates (x, z) expressed in the World system.
  62418. * Returns the ground y position if (x, z) are outside the ground surface.
  62419. */
  62420. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  62421. var world = this.getWorldMatrix();
  62422. var invMat = BABYLON.Tmp.Matrix[5];
  62423. world.invertToRef(invMat);
  62424. var tmpVect = BABYLON.Tmp.Vector3[8];
  62425. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  62426. x = tmpVect.x;
  62427. z = tmpVect.z;
  62428. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  62429. return this.position.y;
  62430. }
  62431. if (!this._heightQuads || this._heightQuads.length == 0) {
  62432. this._initHeightQuads();
  62433. this._computeHeightQuads();
  62434. }
  62435. var facet = this._getFacetAt(x, z);
  62436. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  62437. // return y in the World system
  62438. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  62439. return tmpVect.y;
  62440. };
  62441. /**
  62442. * Returns a normalized vector (Vector3) orthogonal to the ground
  62443. * at the ground coordinates (x, z) expressed in the World system.
  62444. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  62445. */
  62446. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  62447. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  62448. this.getNormalAtCoordinatesToRef(x, z, normal);
  62449. return normal;
  62450. };
  62451. /**
  62452. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  62453. * at the ground coordinates (x, z) expressed in the World system.
  62454. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  62455. * Returns the GroundMesh.
  62456. */
  62457. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  62458. var world = this.getWorldMatrix();
  62459. var tmpMat = BABYLON.Tmp.Matrix[5];
  62460. world.invertToRef(tmpMat);
  62461. var tmpVect = BABYLON.Tmp.Vector3[8];
  62462. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  62463. x = tmpVect.x;
  62464. z = tmpVect.z;
  62465. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  62466. return this;
  62467. }
  62468. if (!this._heightQuads || this._heightQuads.length == 0) {
  62469. this._initHeightQuads();
  62470. this._computeHeightQuads();
  62471. }
  62472. var facet = this._getFacetAt(x, z);
  62473. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  62474. return this;
  62475. };
  62476. /**
  62477. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  62478. * if the ground has been updated.
  62479. * This can be used in the render loop.
  62480. * Returns the GroundMesh.
  62481. */
  62482. GroundMesh.prototype.updateCoordinateHeights = function () {
  62483. if (!this._heightQuads || this._heightQuads.length == 0) {
  62484. this._initHeightQuads();
  62485. }
  62486. this._computeHeightQuads();
  62487. return this;
  62488. };
  62489. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  62490. GroundMesh.prototype._getFacetAt = function (x, z) {
  62491. // retrieve col and row from x, z coordinates in the ground local system
  62492. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  62493. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  62494. var quad = this._heightQuads[row * this._subdivisionsX + col];
  62495. var facet;
  62496. if (z < quad.slope.x * x + quad.slope.y) {
  62497. facet = quad.facet1;
  62498. }
  62499. else {
  62500. facet = quad.facet2;
  62501. }
  62502. return facet;
  62503. };
  62504. // Creates and populates the heightMap array with "facet" elements :
  62505. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  62506. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  62507. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  62508. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  62509. // Returns the GroundMesh.
  62510. GroundMesh.prototype._initHeightQuads = function () {
  62511. var subdivisionsX = this._subdivisionsX;
  62512. var subdivisionsY = this._subdivisionsY;
  62513. this._heightQuads = new Array();
  62514. for (var row = 0; row < subdivisionsY; row++) {
  62515. for (var col = 0; col < subdivisionsX; col++) {
  62516. 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) };
  62517. this._heightQuads[row * subdivisionsX + col] = quad;
  62518. }
  62519. }
  62520. return this;
  62521. };
  62522. // Compute each quad element values and update the the heightMap array :
  62523. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  62524. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  62525. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  62526. // Returns the GroundMesh.
  62527. GroundMesh.prototype._computeHeightQuads = function () {
  62528. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62529. if (!positions) {
  62530. return this;
  62531. }
  62532. var v1 = BABYLON.Tmp.Vector3[3];
  62533. var v2 = BABYLON.Tmp.Vector3[2];
  62534. var v3 = BABYLON.Tmp.Vector3[1];
  62535. var v4 = BABYLON.Tmp.Vector3[0];
  62536. var v1v2 = BABYLON.Tmp.Vector3[4];
  62537. var v1v3 = BABYLON.Tmp.Vector3[5];
  62538. var v1v4 = BABYLON.Tmp.Vector3[6];
  62539. var norm1 = BABYLON.Tmp.Vector3[7];
  62540. var norm2 = BABYLON.Tmp.Vector3[8];
  62541. var i = 0;
  62542. var j = 0;
  62543. var k = 0;
  62544. var cd = 0; // 2D slope coefficient : z = cd * x + h
  62545. var h = 0;
  62546. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  62547. var d2 = 0;
  62548. var subdivisionsX = this._subdivisionsX;
  62549. var subdivisionsY = this._subdivisionsY;
  62550. for (var row = 0; row < subdivisionsY; row++) {
  62551. for (var col = 0; col < subdivisionsX; col++) {
  62552. i = col * 3;
  62553. j = row * (subdivisionsX + 1) * 3;
  62554. k = (row + 1) * (subdivisionsX + 1) * 3;
  62555. v1.x = positions[j + i];
  62556. v1.y = positions[j + i + 1];
  62557. v1.z = positions[j + i + 2];
  62558. v2.x = positions[j + i + 3];
  62559. v2.y = positions[j + i + 4];
  62560. v2.z = positions[j + i + 5];
  62561. v3.x = positions[k + i];
  62562. v3.y = positions[k + i + 1];
  62563. v3.z = positions[k + i + 2];
  62564. v4.x = positions[k + i + 3];
  62565. v4.y = positions[k + i + 4];
  62566. v4.z = positions[k + i + 5];
  62567. // 2D slope V1V4
  62568. cd = (v4.z - v1.z) / (v4.x - v1.x);
  62569. h = v1.z - cd * v1.x; // v1 belongs to the slope
  62570. // facet equations :
  62571. // we compute each facet normal vector
  62572. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  62573. // we compute the value d by applying the equation to v1 which belongs to the plane
  62574. // then we store the facet equation in a Vector4
  62575. v2.subtractToRef(v1, v1v2);
  62576. v3.subtractToRef(v1, v1v3);
  62577. v4.subtractToRef(v1, v1v4);
  62578. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  62579. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  62580. norm1.normalize();
  62581. norm2.normalize();
  62582. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  62583. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  62584. var quad = this._heightQuads[row * subdivisionsX + col];
  62585. quad.slope.copyFromFloats(cd, h);
  62586. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  62587. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  62588. }
  62589. }
  62590. return this;
  62591. };
  62592. GroundMesh.prototype.serialize = function (serializationObject) {
  62593. _super.prototype.serialize.call(this, serializationObject);
  62594. serializationObject.subdivisionsX = this._subdivisionsX;
  62595. serializationObject.subdivisionsY = this._subdivisionsY;
  62596. serializationObject.minX = this._minX;
  62597. serializationObject.maxX = this._maxX;
  62598. serializationObject.minZ = this._minZ;
  62599. serializationObject.maxZ = this._maxZ;
  62600. serializationObject.width = this._width;
  62601. serializationObject.height = this._height;
  62602. };
  62603. GroundMesh.Parse = function (parsedMesh, scene) {
  62604. var result = new GroundMesh(parsedMesh.name, scene);
  62605. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  62606. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  62607. result._minX = parsedMesh.minX;
  62608. result._maxX = parsedMesh.maxX;
  62609. result._minZ = parsedMesh.minZ;
  62610. result._maxZ = parsedMesh.maxZ;
  62611. result._width = parsedMesh.width;
  62612. result._height = parsedMesh.height;
  62613. return result;
  62614. };
  62615. return GroundMesh;
  62616. }(BABYLON.Mesh));
  62617. BABYLON.GroundMesh = GroundMesh;
  62618. })(BABYLON || (BABYLON = {}));
  62619. //# sourceMappingURL=babylon.groundMesh.js.map
  62620. var BABYLON;
  62621. (function (BABYLON) {
  62622. /**
  62623. * Creates an instance based on a source mesh.
  62624. */
  62625. var InstancedMesh = /** @class */ (function (_super) {
  62626. __extends(InstancedMesh, _super);
  62627. function InstancedMesh(name, source) {
  62628. var _this = _super.call(this, name, source.getScene()) || this;
  62629. source.instances.push(_this);
  62630. _this._sourceMesh = source;
  62631. _this.position.copyFrom(source.position);
  62632. _this.rotation.copyFrom(source.rotation);
  62633. _this.scaling.copyFrom(source.scaling);
  62634. if (source.rotationQuaternion) {
  62635. _this.rotationQuaternion = source.rotationQuaternion.clone();
  62636. }
  62637. _this.infiniteDistance = source.infiniteDistance;
  62638. _this.setPivotMatrix(source.getPivotMatrix());
  62639. _this.refreshBoundingInfo();
  62640. _this._syncSubMeshes();
  62641. return _this;
  62642. }
  62643. /**
  62644. * Returns the string "InstancedMesh".
  62645. */
  62646. InstancedMesh.prototype.getClassName = function () {
  62647. return "InstancedMesh";
  62648. };
  62649. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  62650. // Methods
  62651. get: function () {
  62652. return this._sourceMesh.receiveShadows;
  62653. },
  62654. enumerable: true,
  62655. configurable: true
  62656. });
  62657. Object.defineProperty(InstancedMesh.prototype, "material", {
  62658. get: function () {
  62659. return this._sourceMesh.material;
  62660. },
  62661. enumerable: true,
  62662. configurable: true
  62663. });
  62664. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  62665. get: function () {
  62666. return this._sourceMesh.visibility;
  62667. },
  62668. enumerable: true,
  62669. configurable: true
  62670. });
  62671. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  62672. get: function () {
  62673. return this._sourceMesh.skeleton;
  62674. },
  62675. enumerable: true,
  62676. configurable: true
  62677. });
  62678. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  62679. get: function () {
  62680. return this._sourceMesh.renderingGroupId;
  62681. },
  62682. set: function (value) {
  62683. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  62684. return;
  62685. }
  62686. //no-op with warning
  62687. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  62688. },
  62689. enumerable: true,
  62690. configurable: true
  62691. });
  62692. /**
  62693. * Returns the total number of vertices (integer).
  62694. */
  62695. InstancedMesh.prototype.getTotalVertices = function () {
  62696. return this._sourceMesh.getTotalVertices();
  62697. };
  62698. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  62699. get: function () {
  62700. return this._sourceMesh;
  62701. },
  62702. enumerable: true,
  62703. configurable: true
  62704. });
  62705. /**
  62706. * Is this node ready to be used/rendered
  62707. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  62708. * @return {boolean} is it ready
  62709. */
  62710. InstancedMesh.prototype.isReady = function (completeCheck) {
  62711. if (completeCheck === void 0) { completeCheck = false; }
  62712. return this._sourceMesh.isReady(completeCheck, true);
  62713. };
  62714. /**
  62715. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  62716. */
  62717. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  62718. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  62719. };
  62720. /**
  62721. * Sets the vertex data of the mesh geometry for the requested `kind`.
  62722. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  62723. * The `data` are either a numeric array either a Float32Array.
  62724. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  62725. * 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).
  62726. * Note that a new underlying VertexBuffer object is created each call.
  62727. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  62728. *
  62729. * Possible `kind` values :
  62730. * - BABYLON.VertexBuffer.PositionKind
  62731. * - BABYLON.VertexBuffer.UVKind
  62732. * - BABYLON.VertexBuffer.UV2Kind
  62733. * - BABYLON.VertexBuffer.UV3Kind
  62734. * - BABYLON.VertexBuffer.UV4Kind
  62735. * - BABYLON.VertexBuffer.UV5Kind
  62736. * - BABYLON.VertexBuffer.UV6Kind
  62737. * - BABYLON.VertexBuffer.ColorKind
  62738. * - BABYLON.VertexBuffer.MatricesIndicesKind
  62739. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  62740. * - BABYLON.VertexBuffer.MatricesWeightsKind
  62741. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  62742. *
  62743. * Returns the Mesh.
  62744. */
  62745. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  62746. if (this.sourceMesh) {
  62747. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  62748. }
  62749. return this.sourceMesh;
  62750. };
  62751. /**
  62752. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  62753. * If the mesh has no geometry, it is simply returned as it is.
  62754. * The `data` are either a numeric array either a Float32Array.
  62755. * No new underlying VertexBuffer object is created.
  62756. * 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.
  62757. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  62758. *
  62759. * Possible `kind` values :
  62760. * - BABYLON.VertexBuffer.PositionKind
  62761. * - BABYLON.VertexBuffer.UVKind
  62762. * - BABYLON.VertexBuffer.UV2Kind
  62763. * - BABYLON.VertexBuffer.UV3Kind
  62764. * - BABYLON.VertexBuffer.UV4Kind
  62765. * - BABYLON.VertexBuffer.UV5Kind
  62766. * - BABYLON.VertexBuffer.UV6Kind
  62767. * - BABYLON.VertexBuffer.ColorKind
  62768. * - BABYLON.VertexBuffer.MatricesIndicesKind
  62769. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  62770. * - BABYLON.VertexBuffer.MatricesWeightsKind
  62771. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  62772. *
  62773. * Returns the Mesh.
  62774. */
  62775. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  62776. if (this.sourceMesh) {
  62777. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  62778. }
  62779. return this.sourceMesh;
  62780. };
  62781. /**
  62782. * Sets the mesh indices.
  62783. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  62784. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  62785. * This method creates a new index buffer each call.
  62786. * Returns the Mesh.
  62787. */
  62788. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  62789. if (totalVertices === void 0) { totalVertices = null; }
  62790. if (this.sourceMesh) {
  62791. this.sourceMesh.setIndices(indices, totalVertices);
  62792. }
  62793. return this.sourceMesh;
  62794. };
  62795. /**
  62796. * Boolean : True if the mesh owns the requested kind of data.
  62797. */
  62798. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  62799. return this._sourceMesh.isVerticesDataPresent(kind);
  62800. };
  62801. /**
  62802. * Returns an array of indices (IndicesArray).
  62803. */
  62804. InstancedMesh.prototype.getIndices = function () {
  62805. return this._sourceMesh.getIndices();
  62806. };
  62807. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  62808. get: function () {
  62809. return this._sourceMesh._positions;
  62810. },
  62811. enumerable: true,
  62812. configurable: true
  62813. });
  62814. /**
  62815. * Sets a new updated BoundingInfo to the mesh.
  62816. * Returns the mesh.
  62817. */
  62818. InstancedMesh.prototype.refreshBoundingInfo = function () {
  62819. var meshBB = this._sourceMesh.getBoundingInfo();
  62820. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  62821. this._updateBoundingInfo();
  62822. return this;
  62823. };
  62824. /** @hidden */
  62825. InstancedMesh.prototype._preActivate = function () {
  62826. if (this._currentLOD) {
  62827. this._currentLOD._preActivate();
  62828. }
  62829. return this;
  62830. };
  62831. /** @hidden */
  62832. InstancedMesh.prototype._activate = function (renderId) {
  62833. if (this._currentLOD) {
  62834. this._currentLOD._registerInstanceForRenderId(this, renderId);
  62835. }
  62836. return this;
  62837. };
  62838. /**
  62839. * Returns the current associated LOD AbstractMesh.
  62840. */
  62841. InstancedMesh.prototype.getLOD = function (camera) {
  62842. if (!camera) {
  62843. return this;
  62844. }
  62845. var boundingInfo = this.getBoundingInfo();
  62846. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  62847. if (this._currentLOD === this.sourceMesh) {
  62848. return this;
  62849. }
  62850. return this._currentLOD;
  62851. };
  62852. /** @hidden */
  62853. InstancedMesh.prototype._syncSubMeshes = function () {
  62854. this.releaseSubMeshes();
  62855. if (this._sourceMesh.subMeshes) {
  62856. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  62857. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  62858. }
  62859. }
  62860. return this;
  62861. };
  62862. /** @hidden */
  62863. InstancedMesh.prototype._generatePointsArray = function () {
  62864. return this._sourceMesh._generatePointsArray();
  62865. };
  62866. /**
  62867. * Creates a new InstancedMesh from the current mesh.
  62868. * - name (string) : the cloned mesh name
  62869. * - newParent (optional Node) : the optional Node to parent the clone to.
  62870. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  62871. *
  62872. * Returns the clone.
  62873. */
  62874. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  62875. var result = this._sourceMesh.createInstance(name);
  62876. // Deep copy
  62877. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  62878. // Bounding info
  62879. this.refreshBoundingInfo();
  62880. // Parent
  62881. if (newParent) {
  62882. result.parent = newParent;
  62883. }
  62884. if (!doNotCloneChildren) {
  62885. // Children
  62886. for (var index = 0; index < this.getScene().meshes.length; index++) {
  62887. var mesh = this.getScene().meshes[index];
  62888. if (mesh.parent === this) {
  62889. mesh.clone(mesh.name, result);
  62890. }
  62891. }
  62892. }
  62893. result.computeWorldMatrix(true);
  62894. return result;
  62895. };
  62896. /**
  62897. * Disposes the InstancedMesh.
  62898. * Returns nothing.
  62899. */
  62900. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  62901. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  62902. // Remove from mesh
  62903. var index = this._sourceMesh.instances.indexOf(this);
  62904. this._sourceMesh.instances.splice(index, 1);
  62905. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  62906. };
  62907. return InstancedMesh;
  62908. }(BABYLON.AbstractMesh));
  62909. BABYLON.InstancedMesh = InstancedMesh;
  62910. })(BABYLON || (BABYLON = {}));
  62911. //# sourceMappingURL=babylon.instancedMesh.js.map
  62912. var BABYLON;
  62913. (function (BABYLON) {
  62914. var LinesMesh = /** @class */ (function (_super) {
  62915. __extends(LinesMesh, _super);
  62916. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  62917. if (scene === void 0) { scene = null; }
  62918. if (parent === void 0) { parent = null; }
  62919. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  62920. _this.useVertexColor = useVertexColor;
  62921. _this.useVertexAlpha = useVertexAlpha;
  62922. _this.color = new BABYLON.Color3(1, 1, 1);
  62923. _this.alpha = 1;
  62924. if (source) {
  62925. _this.color = source.color.clone();
  62926. _this.alpha = source.alpha;
  62927. _this.useVertexColor = source.useVertexColor;
  62928. _this.useVertexAlpha = source.useVertexAlpha;
  62929. }
  62930. _this._intersectionThreshold = 0.1;
  62931. var defines = [];
  62932. var options = {
  62933. attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
  62934. uniforms: ["world", "viewProjection"],
  62935. needAlphaBlending: true,
  62936. defines: defines
  62937. };
  62938. if (useVertexAlpha === false) {
  62939. options.needAlphaBlending = false;
  62940. }
  62941. if (!useVertexColor) {
  62942. options.uniforms.push("color");
  62943. }
  62944. else {
  62945. options.defines.push("#define VERTEXCOLOR");
  62946. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  62947. }
  62948. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  62949. return _this;
  62950. }
  62951. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  62952. /**
  62953. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  62954. * This margin is expressed in world space coordinates, so its value may vary.
  62955. * Default value is 0.1
  62956. * @returns the intersection Threshold value.
  62957. */
  62958. get: function () {
  62959. return this._intersectionThreshold;
  62960. },
  62961. /**
  62962. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  62963. * This margin is expressed in world space coordinates, so its value may vary.
  62964. * @param value the new threshold to apply
  62965. */
  62966. set: function (value) {
  62967. if (this._intersectionThreshold === value) {
  62968. return;
  62969. }
  62970. this._intersectionThreshold = value;
  62971. if (this.geometry) {
  62972. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  62973. }
  62974. },
  62975. enumerable: true,
  62976. configurable: true
  62977. });
  62978. /**
  62979. * Returns the string "LineMesh"
  62980. */
  62981. LinesMesh.prototype.getClassName = function () {
  62982. return "LinesMesh";
  62983. };
  62984. Object.defineProperty(LinesMesh.prototype, "material", {
  62985. /**
  62986. * @hidden
  62987. */
  62988. get: function () {
  62989. return this._colorShader;
  62990. },
  62991. /**
  62992. * @hidden
  62993. */
  62994. set: function (value) {
  62995. // Do nothing
  62996. },
  62997. enumerable: true,
  62998. configurable: true
  62999. });
  63000. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  63001. /**
  63002. * @hidden
  63003. */
  63004. get: function () {
  63005. return false;
  63006. },
  63007. enumerable: true,
  63008. configurable: true
  63009. });
  63010. /** @hidden */
  63011. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  63012. if (!this._geometry) {
  63013. return this;
  63014. }
  63015. // VBOs
  63016. this._geometry._bind(this._colorShader.getEffect());
  63017. // Color
  63018. if (!this.useVertexColor) {
  63019. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  63020. }
  63021. return this;
  63022. };
  63023. /** @hidden */
  63024. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  63025. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  63026. return this;
  63027. }
  63028. var engine = this.getScene().getEngine();
  63029. // Draw order
  63030. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  63031. return this;
  63032. };
  63033. LinesMesh.prototype.dispose = function (doNotRecurse) {
  63034. this._colorShader.dispose();
  63035. _super.prototype.dispose.call(this, doNotRecurse);
  63036. };
  63037. /**
  63038. * Returns a new LineMesh object cloned from the current one.
  63039. */
  63040. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  63041. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  63042. };
  63043. return LinesMesh;
  63044. }(BABYLON.Mesh));
  63045. BABYLON.LinesMesh = LinesMesh;
  63046. })(BABYLON || (BABYLON = {}));
  63047. //# sourceMappingURL=babylon.linesMesh.js.map
  63048. var BABYLON;
  63049. (function (BABYLON) {
  63050. /**
  63051. * This class implement a typical dictionary using a string as key and the generic type T as value.
  63052. * The underlying implementation relies on an associative array to ensure the best performances.
  63053. * The value can be anything including 'null' but except 'undefined'
  63054. */
  63055. var StringDictionary = /** @class */ (function () {
  63056. function StringDictionary() {
  63057. this._count = 0;
  63058. this._data = {};
  63059. }
  63060. /**
  63061. * This will clear this dictionary and copy the content from the 'source' one.
  63062. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  63063. * @param source the dictionary to take the content from and copy to this dictionary
  63064. */
  63065. StringDictionary.prototype.copyFrom = function (source) {
  63066. var _this = this;
  63067. this.clear();
  63068. source.forEach(function (t, v) { return _this.add(t, v); });
  63069. };
  63070. /**
  63071. * Get a value based from its key
  63072. * @param key the given key to get the matching value from
  63073. * @return the value if found, otherwise undefined is returned
  63074. */
  63075. StringDictionary.prototype.get = function (key) {
  63076. var val = this._data[key];
  63077. if (val !== undefined) {
  63078. return val;
  63079. }
  63080. return undefined;
  63081. };
  63082. /**
  63083. * Get a value from its key or add it if it doesn't exist.
  63084. * This method will ensure you that a given key/data will be present in the dictionary.
  63085. * @param key the given key to get the matching value from
  63086. * @param factory the factory that will create the value if the key is not present in the dictionary.
  63087. * The factory will only be invoked if there's no data for the given key.
  63088. * @return the value corresponding to the key.
  63089. */
  63090. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  63091. var val = this.get(key);
  63092. if (val !== undefined) {
  63093. return val;
  63094. }
  63095. val = factory(key);
  63096. if (val) {
  63097. this.add(key, val);
  63098. }
  63099. return val;
  63100. };
  63101. /**
  63102. * Get a value from its key if present in the dictionary otherwise add it
  63103. * @param key the key to get the value from
  63104. * @param val if there's no such key/value pair in the dictionary add it with this value
  63105. * @return the value corresponding to the key
  63106. */
  63107. StringDictionary.prototype.getOrAdd = function (key, val) {
  63108. var curVal = this.get(key);
  63109. if (curVal !== undefined) {
  63110. return curVal;
  63111. }
  63112. this.add(key, val);
  63113. return val;
  63114. };
  63115. /**
  63116. * Check if there's a given key in the dictionary
  63117. * @param key the key to check for
  63118. * @return true if the key is present, false otherwise
  63119. */
  63120. StringDictionary.prototype.contains = function (key) {
  63121. return this._data[key] !== undefined;
  63122. };
  63123. /**
  63124. * Add a new key and its corresponding value
  63125. * @param key the key to add
  63126. * @param value the value corresponding to the key
  63127. * @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
  63128. */
  63129. StringDictionary.prototype.add = function (key, value) {
  63130. if (this._data[key] !== undefined) {
  63131. return false;
  63132. }
  63133. this._data[key] = value;
  63134. ++this._count;
  63135. return true;
  63136. };
  63137. StringDictionary.prototype.set = function (key, value) {
  63138. if (this._data[key] === undefined) {
  63139. return false;
  63140. }
  63141. this._data[key] = value;
  63142. return true;
  63143. };
  63144. /**
  63145. * Get the element of the given key and remove it from the dictionary
  63146. * @param key
  63147. */
  63148. StringDictionary.prototype.getAndRemove = function (key) {
  63149. var val = this.get(key);
  63150. if (val !== undefined) {
  63151. delete this._data[key];
  63152. --this._count;
  63153. return val;
  63154. }
  63155. return null;
  63156. };
  63157. /**
  63158. * Remove a key/value from the dictionary.
  63159. * @param key the key to remove
  63160. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  63161. */
  63162. StringDictionary.prototype.remove = function (key) {
  63163. if (this.contains(key)) {
  63164. delete this._data[key];
  63165. --this._count;
  63166. return true;
  63167. }
  63168. return false;
  63169. };
  63170. /**
  63171. * Clear the whole content of the dictionary
  63172. */
  63173. StringDictionary.prototype.clear = function () {
  63174. this._data = {};
  63175. this._count = 0;
  63176. };
  63177. Object.defineProperty(StringDictionary.prototype, "count", {
  63178. get: function () {
  63179. return this._count;
  63180. },
  63181. enumerable: true,
  63182. configurable: true
  63183. });
  63184. /**
  63185. * Execute a callback on each key/val of the dictionary.
  63186. * Note that you can remove any element in this dictionary in the callback implementation
  63187. * @param callback the callback to execute on a given key/value pair
  63188. */
  63189. StringDictionary.prototype.forEach = function (callback) {
  63190. for (var cur in this._data) {
  63191. var val = this._data[cur];
  63192. callback(cur, val);
  63193. }
  63194. };
  63195. /**
  63196. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  63197. * If the callback returns null or undefined the method will iterate to the next key/value pair
  63198. * Note that you can remove any element in this dictionary in the callback implementation
  63199. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  63200. */
  63201. StringDictionary.prototype.first = function (callback) {
  63202. for (var cur in this._data) {
  63203. var val = this._data[cur];
  63204. var res = callback(cur, val);
  63205. if (res) {
  63206. return res;
  63207. }
  63208. }
  63209. return null;
  63210. };
  63211. return StringDictionary;
  63212. }());
  63213. BABYLON.StringDictionary = StringDictionary;
  63214. })(BABYLON || (BABYLON = {}));
  63215. //# sourceMappingURL=babylon.stringDictionary.js.map
  63216. var BABYLON;
  63217. (function (BABYLON) {
  63218. var Debug;
  63219. (function (Debug) {
  63220. /**
  63221. * Class used to render a debug view of a given skeleton
  63222. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  63223. */
  63224. var SkeletonViewer = /** @class */ (function () {
  63225. /**
  63226. * Creates a new SkeletonViewer
  63227. * @param skeleton defines the skeleton to render
  63228. * @param mesh defines the mesh attached to the skeleton
  63229. * @param scene defines the hosting scene
  63230. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  63231. * @param renderingGroupId defines the rendering group id to use with the viewer
  63232. */
  63233. function SkeletonViewer(
  63234. /** defines the skeleton to render */
  63235. skeleton,
  63236. /** defines the mesh attached to the skeleton */
  63237. mesh, scene,
  63238. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  63239. autoUpdateBonesMatrices,
  63240. /** defines the rendering group id to use with the viewer */
  63241. renderingGroupId) {
  63242. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  63243. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  63244. this.skeleton = skeleton;
  63245. this.mesh = mesh;
  63246. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  63247. this.renderingGroupId = renderingGroupId;
  63248. /** Gets or sets the color used to render the skeleton */
  63249. this.color = BABYLON.Color3.White();
  63250. this._debugLines = new Array();
  63251. this._isEnabled = false;
  63252. this._scene = scene;
  63253. this.update();
  63254. this._renderFunction = this.update.bind(this);
  63255. }
  63256. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  63257. get: function () {
  63258. return this._isEnabled;
  63259. },
  63260. /** Gets or sets a boolean indicating if the viewer is enabled */
  63261. set: function (value) {
  63262. if (this._isEnabled === value) {
  63263. return;
  63264. }
  63265. this._isEnabled = value;
  63266. if (value) {
  63267. this._scene.registerBeforeRender(this._renderFunction);
  63268. }
  63269. else {
  63270. this._scene.unregisterBeforeRender(this._renderFunction);
  63271. }
  63272. },
  63273. enumerable: true,
  63274. configurable: true
  63275. });
  63276. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  63277. if (x === void 0) { x = 0; }
  63278. if (y === void 0) { y = 0; }
  63279. if (z === void 0) { z = 0; }
  63280. var tmat = BABYLON.Tmp.Matrix[0];
  63281. var parentBone = bone.getParent();
  63282. tmat.copyFrom(bone.getLocalMatrix());
  63283. if (x !== 0 || y !== 0 || z !== 0) {
  63284. var tmat2 = BABYLON.Tmp.Matrix[1];
  63285. BABYLON.Matrix.IdentityToRef(tmat2);
  63286. tmat2.m[12] = x;
  63287. tmat2.m[13] = y;
  63288. tmat2.m[14] = z;
  63289. tmat2.multiplyToRef(tmat, tmat);
  63290. }
  63291. if (parentBone) {
  63292. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  63293. }
  63294. tmat.multiplyToRef(meshMat, tmat);
  63295. position.x = tmat.m[12];
  63296. position.y = tmat.m[13];
  63297. position.z = tmat.m[14];
  63298. };
  63299. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  63300. var len = bones.length;
  63301. var meshPos = this.mesh.position;
  63302. for (var i = 0; i < len; i++) {
  63303. var bone = bones[i];
  63304. var points = this._debugLines[i];
  63305. if (!points) {
  63306. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63307. this._debugLines[i] = points;
  63308. }
  63309. this._getBonePosition(points[0], bone, meshMat);
  63310. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  63311. points[0].subtractInPlace(meshPos);
  63312. points[1].subtractInPlace(meshPos);
  63313. }
  63314. };
  63315. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  63316. var len = bones.length;
  63317. var boneNum = 0;
  63318. var meshPos = this.mesh.position;
  63319. for (var i = len - 1; i >= 0; i--) {
  63320. var childBone = bones[i];
  63321. var parentBone = childBone.getParent();
  63322. if (!parentBone) {
  63323. continue;
  63324. }
  63325. var points = this._debugLines[boneNum];
  63326. if (!points) {
  63327. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63328. this._debugLines[boneNum] = points;
  63329. }
  63330. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  63331. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  63332. points[0].subtractInPlace(meshPos);
  63333. points[1].subtractInPlace(meshPos);
  63334. boneNum++;
  63335. }
  63336. };
  63337. /** Update the viewer to sync with current skeleton state */
  63338. SkeletonViewer.prototype.update = function () {
  63339. if (this.autoUpdateBonesMatrices) {
  63340. this.skeleton.computeAbsoluteTransforms();
  63341. }
  63342. if (this.skeleton.bones[0].length === undefined) {
  63343. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  63344. }
  63345. else {
  63346. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  63347. }
  63348. if (!this._debugMesh) {
  63349. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  63350. this._debugMesh.renderingGroupId = this.renderingGroupId;
  63351. }
  63352. else {
  63353. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  63354. }
  63355. this._debugMesh.position.copyFrom(this.mesh.position);
  63356. this._debugMesh.color = this.color;
  63357. };
  63358. /** Release associated resources */
  63359. SkeletonViewer.prototype.dispose = function () {
  63360. if (this._debugMesh) {
  63361. this.isEnabled = false;
  63362. this._debugMesh.dispose();
  63363. this._debugMesh = null;
  63364. }
  63365. };
  63366. return SkeletonViewer;
  63367. }());
  63368. Debug.SkeletonViewer = SkeletonViewer;
  63369. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63370. })(BABYLON || (BABYLON = {}));
  63371. //# sourceMappingURL=babylon.skeletonViewer.js.map
  63372. /**
  63373. * Module Debug contains the (visual) components to debug a scene correctly
  63374. */
  63375. var BABYLON;
  63376. (function (BABYLON) {
  63377. var Debug;
  63378. (function (Debug) {
  63379. /**
  63380. * The Axes viewer will show 3 axes in a specific point in space
  63381. */
  63382. var AxesViewer = /** @class */ (function () {
  63383. /**
  63384. * Creates a new AxesViewer
  63385. * @param scene defines the hosting scene
  63386. * @param scaleLines defines a number used to scale line length (1 by default)
  63387. */
  63388. function AxesViewer(scene, scaleLines) {
  63389. if (scaleLines === void 0) { scaleLines = 1; }
  63390. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63391. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63392. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63393. /**
  63394. * Gets or sets a number used to scale line length
  63395. */
  63396. this.scaleLines = 1;
  63397. this.scaleLines = scaleLines;
  63398. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  63399. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  63400. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  63401. this._xmesh.renderingGroupId = 2;
  63402. this._ymesh.renderingGroupId = 2;
  63403. this._zmesh.renderingGroupId = 2;
  63404. this._xmesh.material.checkReadyOnlyOnce = true;
  63405. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  63406. this._ymesh.material.checkReadyOnlyOnce = true;
  63407. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  63408. this._zmesh.material.checkReadyOnlyOnce = true;
  63409. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  63410. this.scene = scene;
  63411. }
  63412. /**
  63413. * Force the viewer to update
  63414. * @param position defines the position of the viewer
  63415. * @param xaxis defines the x axis of the viewer
  63416. * @param yaxis defines the y axis of the viewer
  63417. * @param zaxis defines the z axis of the viewer
  63418. */
  63419. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  63420. var scaleLines = this.scaleLines;
  63421. if (this._xmesh) {
  63422. this._xmesh.position.copyFrom(position);
  63423. }
  63424. if (this._ymesh) {
  63425. this._ymesh.position.copyFrom(position);
  63426. }
  63427. if (this._zmesh) {
  63428. this._zmesh.position.copyFrom(position);
  63429. }
  63430. var point2 = this._xline[1];
  63431. point2.x = xaxis.x * scaleLines;
  63432. point2.y = xaxis.y * scaleLines;
  63433. point2.z = xaxis.z * scaleLines;
  63434. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  63435. point2 = this._yline[1];
  63436. point2.x = yaxis.x * scaleLines;
  63437. point2.y = yaxis.y * scaleLines;
  63438. point2.z = yaxis.z * scaleLines;
  63439. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  63440. point2 = this._zline[1];
  63441. point2.x = zaxis.x * scaleLines;
  63442. point2.y = zaxis.y * scaleLines;
  63443. point2.z = zaxis.z * scaleLines;
  63444. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  63445. };
  63446. /** Releases resources */
  63447. AxesViewer.prototype.dispose = function () {
  63448. if (this._xmesh) {
  63449. this._xmesh.dispose();
  63450. }
  63451. if (this._ymesh) {
  63452. this._ymesh.dispose();
  63453. }
  63454. if (this._zmesh) {
  63455. this._zmesh.dispose();
  63456. }
  63457. this._xmesh = null;
  63458. this._ymesh = null;
  63459. this._zmesh = null;
  63460. this.scene = null;
  63461. };
  63462. return AxesViewer;
  63463. }());
  63464. Debug.AxesViewer = AxesViewer;
  63465. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63466. })(BABYLON || (BABYLON = {}));
  63467. //# sourceMappingURL=babylon.axesViewer.js.map
  63468. var BABYLON;
  63469. (function (BABYLON) {
  63470. var Debug;
  63471. (function (Debug) {
  63472. /**
  63473. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  63474. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  63475. */
  63476. var BoneAxesViewer = /** @class */ (function (_super) {
  63477. __extends(BoneAxesViewer, _super);
  63478. /**
  63479. * Creates a new BoneAxesViewer
  63480. * @param scene defines the hosting scene
  63481. * @param bone defines the target bone
  63482. * @param mesh defines the target mesh
  63483. * @param scaleLines defines a scaling factor for line length (1 by default)
  63484. */
  63485. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  63486. if (scaleLines === void 0) { scaleLines = 1; }
  63487. var _this = _super.call(this, scene, scaleLines) || this;
  63488. /** Gets current position */
  63489. _this.pos = BABYLON.Vector3.Zero();
  63490. /** Gets direction of X axis */
  63491. _this.xaxis = BABYLON.Vector3.Zero();
  63492. /** Gets direction of Y axis */
  63493. _this.yaxis = BABYLON.Vector3.Zero();
  63494. /** Gets direction of Z axis */
  63495. _this.zaxis = BABYLON.Vector3.Zero();
  63496. _this.mesh = mesh;
  63497. _this.bone = bone;
  63498. return _this;
  63499. }
  63500. /**
  63501. * Force the viewer to update
  63502. */
  63503. BoneAxesViewer.prototype.update = function () {
  63504. if (!this.mesh || !this.bone) {
  63505. return;
  63506. }
  63507. var bone = this.bone;
  63508. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  63509. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  63510. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  63511. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  63512. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  63513. };
  63514. /** Releases resources */
  63515. BoneAxesViewer.prototype.dispose = function () {
  63516. if (this.mesh) {
  63517. this.mesh = null;
  63518. this.bone = null;
  63519. _super.prototype.dispose.call(this);
  63520. }
  63521. };
  63522. return BoneAxesViewer;
  63523. }(Debug.AxesViewer));
  63524. Debug.BoneAxesViewer = BoneAxesViewer;
  63525. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63526. })(BABYLON || (BABYLON = {}));
  63527. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  63528. var BABYLON;
  63529. (function (BABYLON) {
  63530. /**
  63531. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  63532. * in order to better appreciate the issue one might have.
  63533. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  63534. */
  63535. var RayHelper = /** @class */ (function () {
  63536. /**
  63537. * Instantiate a new ray helper.
  63538. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  63539. * in order to better appreciate the issue one might have.
  63540. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  63541. * @param ray Defines the ray we are currently tryin to visualize
  63542. */
  63543. function RayHelper(ray) {
  63544. this.ray = ray;
  63545. }
  63546. /**
  63547. * Helper function to create a colored helper in a scene in one line.
  63548. * @param ray Defines the ray we are currently tryin to visualize
  63549. * @param scene Defines the scene the ray is used in
  63550. * @param color Defines the color we want to see the ray in
  63551. * @returns The newly created ray helper.
  63552. */
  63553. RayHelper.CreateAndShow = function (ray, scene, color) {
  63554. var helper = new RayHelper(ray);
  63555. helper.show(scene, color);
  63556. return helper;
  63557. };
  63558. /**
  63559. * Shows the ray we are willing to debug.
  63560. * @param scene Defines the scene the ray needs to be rendered in
  63561. * @param color Defines the color the ray needs to be rendered in
  63562. */
  63563. RayHelper.prototype.show = function (scene, color) {
  63564. if (!this._renderFunction && this.ray) {
  63565. var ray = this.ray;
  63566. this._renderFunction = this._render.bind(this);
  63567. this._scene = scene;
  63568. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  63569. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  63570. if (this._renderFunction) {
  63571. this._scene.registerBeforeRender(this._renderFunction);
  63572. }
  63573. }
  63574. if (color && this._renderLine) {
  63575. this._renderLine.color.copyFrom(color);
  63576. }
  63577. };
  63578. /**
  63579. * Hides the ray we are debugging.
  63580. */
  63581. RayHelper.prototype.hide = function () {
  63582. if (this._renderFunction && this._scene) {
  63583. this._scene.unregisterBeforeRender(this._renderFunction);
  63584. this._scene = null;
  63585. this._renderFunction = null;
  63586. if (this._renderLine) {
  63587. this._renderLine.dispose();
  63588. this._renderLine = null;
  63589. }
  63590. this._renderPoints = [];
  63591. }
  63592. };
  63593. RayHelper.prototype._render = function () {
  63594. var ray = this.ray;
  63595. if (!ray) {
  63596. return;
  63597. }
  63598. var point = this._renderPoints[1];
  63599. var len = Math.min(ray.length, 1000000);
  63600. point.copyFrom(ray.direction);
  63601. point.scaleInPlace(len);
  63602. point.addInPlace(ray.origin);
  63603. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  63604. };
  63605. /**
  63606. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  63607. * @param mesh Defines the mesh we want the helper attached to
  63608. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  63609. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  63610. * @param length Defines the length of the ray
  63611. */
  63612. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  63613. this._attachedToMesh = mesh;
  63614. var ray = this.ray;
  63615. if (!ray) {
  63616. return;
  63617. }
  63618. if (!ray.direction) {
  63619. ray.direction = BABYLON.Vector3.Zero();
  63620. }
  63621. if (!ray.origin) {
  63622. ray.origin = BABYLON.Vector3.Zero();
  63623. }
  63624. if (length) {
  63625. ray.length = length;
  63626. }
  63627. if (!meshSpaceOrigin) {
  63628. meshSpaceOrigin = BABYLON.Vector3.Zero();
  63629. }
  63630. if (!meshSpaceDirection) {
  63631. // -1 so that this will work with Mesh.lookAt
  63632. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  63633. }
  63634. if (!this._meshSpaceDirection) {
  63635. this._meshSpaceDirection = meshSpaceDirection.clone();
  63636. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  63637. }
  63638. else {
  63639. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  63640. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  63641. }
  63642. if (!this._updateToMeshFunction) {
  63643. this._updateToMeshFunction = this._updateToMesh.bind(this);
  63644. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  63645. }
  63646. this._updateToMesh();
  63647. };
  63648. /**
  63649. * Detach the ray helper from the mesh it has previously been attached to.
  63650. */
  63651. RayHelper.prototype.detachFromMesh = function () {
  63652. if (this._attachedToMesh) {
  63653. if (this._updateToMeshFunction) {
  63654. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  63655. }
  63656. this._attachedToMesh = null;
  63657. this._updateToMeshFunction = null;
  63658. }
  63659. };
  63660. RayHelper.prototype._updateToMesh = function () {
  63661. var ray = this.ray;
  63662. if (!this._attachedToMesh || !ray) {
  63663. return;
  63664. }
  63665. if (this._attachedToMesh._isDisposed) {
  63666. this.detachFromMesh();
  63667. return;
  63668. }
  63669. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  63670. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  63671. };
  63672. /**
  63673. * Dispose the helper and release its associated resources.
  63674. */
  63675. RayHelper.prototype.dispose = function () {
  63676. this.hide();
  63677. this.detachFromMesh();
  63678. this.ray = null;
  63679. };
  63680. return RayHelper;
  63681. }());
  63682. BABYLON.RayHelper = RayHelper;
  63683. })(BABYLON || (BABYLON = {}));
  63684. //# sourceMappingURL=babylon.rayHelper.js.map
  63685. var BABYLON;
  63686. (function (BABYLON) {
  63687. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  63688. get: function () {
  63689. if (!this._debugLayer) {
  63690. this._debugLayer = new DebugLayer(this);
  63691. }
  63692. return this._debugLayer;
  63693. },
  63694. enumerable: true,
  63695. configurable: true
  63696. });
  63697. /**
  63698. * The debug layer (aka Inspector) is the go to tool in order to better understand
  63699. * what is happening in your scene
  63700. * @see http://doc.babylonjs.com/features/playground_debuglayer
  63701. */
  63702. var DebugLayer = /** @class */ (function () {
  63703. /**
  63704. * Instantiates a new debug layer.
  63705. * The debug layer (aka Inspector) is the go to tool in order to better understand
  63706. * what is happening in your scene
  63707. * @see http://doc.babylonjs.com/features/playground_debuglayer
  63708. * @param scene Defines the scene to inspect
  63709. */
  63710. function DebugLayer(scene) {
  63711. var _this = this;
  63712. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  63713. /**
  63714. * Observable triggered when a property is changed through the inspector.
  63715. */
  63716. this.onPropertyChangedObservable = new BABYLON.Observable();
  63717. this._scene = scene;
  63718. this._scene.onDisposeObservable.add(function () {
  63719. // Debug layer
  63720. if (_this._scene._debugLayer) {
  63721. _this._scene._debugLayer.hide();
  63722. }
  63723. });
  63724. }
  63725. /** Creates the inspector window. */
  63726. DebugLayer.prototype._createInspector = function (config) {
  63727. if (config === void 0) { config = {}; }
  63728. var popup = config.popup || false;
  63729. var initialTab = config.initialTab || 0;
  63730. var parentElement = config.parentElement || null;
  63731. if (!this._inspector) {
  63732. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  63733. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  63734. } // else nothing to do as instance is already created
  63735. };
  63736. /**
  63737. * Get if the inspector is visible or not.
  63738. * @returns true if visible otherwise, false
  63739. */
  63740. DebugLayer.prototype.isVisible = function () {
  63741. if (!this._inspector) {
  63742. return false;
  63743. }
  63744. return true;
  63745. };
  63746. /**
  63747. * Hide the inspector and close its window.
  63748. */
  63749. DebugLayer.prototype.hide = function () {
  63750. if (this._inspector) {
  63751. try {
  63752. this._inspector.dispose();
  63753. }
  63754. catch (e) {
  63755. // If the inspector has been removed directly from the inspector tool
  63756. }
  63757. this.onPropertyChangedObservable.clear();
  63758. this._inspector = null;
  63759. }
  63760. };
  63761. /**
  63762. *
  63763. * Launch the debugLayer.
  63764. *
  63765. * initialTab:
  63766. * | Value | Tab Name |
  63767. * | --- | --- |
  63768. * | 0 | Scene |
  63769. * | 1 | Console |
  63770. * | 2 | Stats |
  63771. * | 3 | Textures |
  63772. * | 4 | Mesh |
  63773. * | 5 | Light |
  63774. * | 6 | Material |
  63775. * | 7 | GLTF |
  63776. * | 8 | GUI |
  63777. * | 9 | Physics |
  63778. * | 10 | Camera |
  63779. * | 11 | Audio |
  63780. *
  63781. * @param config Define the configuration of the inspector
  63782. */
  63783. DebugLayer.prototype.show = function (config) {
  63784. if (config === void 0) { config = {}; }
  63785. if (typeof this.BJSINSPECTOR == 'undefined') {
  63786. // Load inspector and add it to the DOM
  63787. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  63788. }
  63789. else {
  63790. // Otherwise creates the inspector
  63791. this._createInspector(config);
  63792. }
  63793. };
  63794. /**
  63795. * Gets the active tab
  63796. * @return the index of the active tab or -1 if the inspector is hidden
  63797. */
  63798. DebugLayer.prototype.getActiveTab = function () {
  63799. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  63800. };
  63801. /**
  63802. * Define the url to get the inspector script from.
  63803. * By default it uses the babylonjs CDN.
  63804. * @ignoreNaming
  63805. */
  63806. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  63807. return DebugLayer;
  63808. }());
  63809. BABYLON.DebugLayer = DebugLayer;
  63810. })(BABYLON || (BABYLON = {}));
  63811. //# sourceMappingURL=babylon.debugLayer.js.map
  63812. var BABYLON;
  63813. (function (BABYLON) {
  63814. var Debug;
  63815. (function (Debug) {
  63816. /**
  63817. * Used to show the physics impostor around the specific mesh
  63818. */
  63819. var PhysicsViewer = /** @class */ (function () {
  63820. /**
  63821. * Creates a new PhysicsViewer
  63822. * @param scene defines the hosting scene
  63823. */
  63824. function PhysicsViewer(scene) {
  63825. /** @hidden */
  63826. this._impostors = [];
  63827. /** @hidden */
  63828. this._meshes = [];
  63829. /** @hidden */
  63830. this._numMeshes = 0;
  63831. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63832. var physicEngine = this._scene.getPhysicsEngine();
  63833. if (physicEngine) {
  63834. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  63835. }
  63836. }
  63837. /** @hidden */
  63838. PhysicsViewer.prototype._updateDebugMeshes = function () {
  63839. var plugin = this._physicsEnginePlugin;
  63840. for (var i = 0; i < this._numMeshes; i++) {
  63841. var impostor = this._impostors[i];
  63842. if (!impostor) {
  63843. continue;
  63844. }
  63845. if (impostor.isDisposed) {
  63846. this.hideImpostor(this._impostors[i--]);
  63847. }
  63848. else {
  63849. var mesh = this._meshes[i];
  63850. if (mesh && plugin) {
  63851. plugin.syncMeshWithImpostor(mesh, impostor);
  63852. }
  63853. }
  63854. }
  63855. };
  63856. /**
  63857. * Renders a specified physic impostor
  63858. * @param impostor defines the impostor to render
  63859. */
  63860. PhysicsViewer.prototype.showImpostor = function (impostor) {
  63861. if (!this._scene) {
  63862. return;
  63863. }
  63864. for (var i = 0; i < this._numMeshes; i++) {
  63865. if (this._impostors[i] == impostor) {
  63866. return;
  63867. }
  63868. }
  63869. var debugMesh = this._getDebugMesh(impostor, this._scene);
  63870. if (debugMesh) {
  63871. this._impostors[this._numMeshes] = impostor;
  63872. this._meshes[this._numMeshes] = debugMesh;
  63873. if (this._numMeshes === 0) {
  63874. this._renderFunction = this._updateDebugMeshes.bind(this);
  63875. this._scene.registerBeforeRender(this._renderFunction);
  63876. }
  63877. this._numMeshes++;
  63878. }
  63879. };
  63880. /**
  63881. * Hides a specified physic impostor
  63882. * @param impostor defines the impostor to hide
  63883. */
  63884. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  63885. if (!impostor || !this._scene) {
  63886. return;
  63887. }
  63888. var removed = false;
  63889. for (var i = 0; i < this._numMeshes; i++) {
  63890. if (this._impostors[i] == impostor) {
  63891. var mesh = this._meshes[i];
  63892. if (!mesh) {
  63893. continue;
  63894. }
  63895. this._scene.removeMesh(mesh);
  63896. mesh.dispose();
  63897. this._numMeshes--;
  63898. if (this._numMeshes > 0) {
  63899. this._meshes[i] = this._meshes[this._numMeshes];
  63900. this._impostors[i] = this._impostors[this._numMeshes];
  63901. this._meshes[this._numMeshes] = null;
  63902. this._impostors[this._numMeshes] = null;
  63903. }
  63904. else {
  63905. this._meshes[0] = null;
  63906. this._impostors[0] = null;
  63907. }
  63908. removed = true;
  63909. break;
  63910. }
  63911. }
  63912. if (removed && this._numMeshes === 0) {
  63913. this._scene.unregisterBeforeRender(this._renderFunction);
  63914. }
  63915. };
  63916. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  63917. if (!this._debugMaterial) {
  63918. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  63919. this._debugMaterial.wireframe = true;
  63920. }
  63921. return this._debugMaterial;
  63922. };
  63923. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  63924. if (!this._debugBoxMesh) {
  63925. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  63926. this._debugBoxMesh.renderingGroupId = 1;
  63927. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63928. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  63929. scene.removeMesh(this._debugBoxMesh);
  63930. }
  63931. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  63932. };
  63933. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  63934. if (!this._debugSphereMesh) {
  63935. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  63936. this._debugSphereMesh.renderingGroupId = 1;
  63937. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63938. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  63939. scene.removeMesh(this._debugSphereMesh);
  63940. }
  63941. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  63942. };
  63943. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  63944. var mesh = null;
  63945. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  63946. mesh = this._getDebugBoxMesh(scene);
  63947. impostor.getBoxSizeToRef(mesh.scaling);
  63948. }
  63949. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  63950. mesh = this._getDebugSphereMesh(scene);
  63951. var radius = impostor.getRadius();
  63952. mesh.scaling.x = radius * 2;
  63953. mesh.scaling.y = radius * 2;
  63954. mesh.scaling.z = radius * 2;
  63955. }
  63956. return mesh;
  63957. };
  63958. /** Releases all resources */
  63959. PhysicsViewer.prototype.dispose = function () {
  63960. for (var i = 0; i < this._numMeshes; i++) {
  63961. this.hideImpostor(this._impostors[i]);
  63962. }
  63963. if (this._debugBoxMesh) {
  63964. this._debugBoxMesh.dispose();
  63965. }
  63966. if (this._debugSphereMesh) {
  63967. this._debugSphereMesh.dispose();
  63968. }
  63969. if (this._debugMaterial) {
  63970. this._debugMaterial.dispose();
  63971. }
  63972. this._impostors.length = 0;
  63973. this._scene = null;
  63974. this._physicsEnginePlugin = null;
  63975. };
  63976. return PhysicsViewer;
  63977. }());
  63978. Debug.PhysicsViewer = PhysicsViewer;
  63979. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63980. })(BABYLON || (BABYLON = {}));
  63981. //# sourceMappingURL=babylon.physicsViewer.js.map
  63982. var BABYLON;
  63983. (function (BABYLON) {
  63984. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  63985. get: function () {
  63986. return this._forceShowBoundingBoxes || false;
  63987. },
  63988. set: function (value) {
  63989. this._forceShowBoundingBoxes = value;
  63990. // Lazyly creates a BB renderer if needed.
  63991. if (value) {
  63992. this.getBoundingBoxRenderer();
  63993. }
  63994. },
  63995. enumerable: true,
  63996. configurable: true
  63997. });
  63998. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  63999. if (!this._boundingBoxRenderer) {
  64000. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  64001. }
  64002. return this._boundingBoxRenderer;
  64003. };
  64004. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  64005. get: function () {
  64006. return this._showBoundingBox || false;
  64007. },
  64008. set: function (value) {
  64009. this._showBoundingBox = value;
  64010. // Lazyly creates a BB renderer if needed.
  64011. if (value) {
  64012. this.getScene().getBoundingBoxRenderer();
  64013. }
  64014. },
  64015. enumerable: true,
  64016. configurable: true
  64017. });
  64018. /**
  64019. * Component responsible of rendering the bounding box of the meshes in a scene.
  64020. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  64021. */
  64022. var BoundingBoxRenderer = /** @class */ (function () {
  64023. /**
  64024. * Instantiates a new bounding box renderer in a scene.
  64025. * @param scene the scene the renderer renders in
  64026. */
  64027. function BoundingBoxRenderer(scene) {
  64028. /**
  64029. * The component name helpfull to identify the component in the list of scene components.
  64030. */
  64031. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  64032. /**
  64033. * Color of the bounding box lines placed in front of an object
  64034. */
  64035. this.frontColor = new BABYLON.Color3(1, 1, 1);
  64036. /**
  64037. * Color of the bounding box lines placed behind an object
  64038. */
  64039. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  64040. /**
  64041. * Defines if the renderer should show the back lines or not
  64042. */
  64043. this.showBackLines = true;
  64044. /**
  64045. * @hidden
  64046. */
  64047. this.renderList = new BABYLON.SmartArray(32);
  64048. this._vertexBuffers = {};
  64049. this.scene = scene;
  64050. scene._addComponent(this);
  64051. }
  64052. /**
  64053. * Registers the component in a given scene
  64054. */
  64055. BoundingBoxRenderer.prototype.register = function () {
  64056. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  64057. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  64058. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  64059. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  64060. };
  64061. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  64062. if (mesh.showSubMeshesBoundingBox) {
  64063. var boundingInfo = subMesh.getBoundingInfo();
  64064. if (boundingInfo !== null && boundingInfo !== undefined) {
  64065. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  64066. this.renderList.push(boundingInfo.boundingBox);
  64067. }
  64068. }
  64069. };
  64070. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  64071. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  64072. var boundingInfo = sourceMesh.getBoundingInfo();
  64073. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  64074. this.renderList.push(boundingInfo.boundingBox);
  64075. }
  64076. };
  64077. BoundingBoxRenderer.prototype._prepareRessources = function () {
  64078. if (this._colorShader) {
  64079. return;
  64080. }
  64081. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  64082. attributes: [BABYLON.VertexBuffer.PositionKind],
  64083. uniforms: ["world", "viewProjection", "color"]
  64084. });
  64085. var engine = this.scene.getEngine();
  64086. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  64087. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  64088. this._createIndexBuffer();
  64089. };
  64090. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  64091. var engine = this.scene.getEngine();
  64092. 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]);
  64093. };
  64094. /**
  64095. * Rebuilds the elements related to this component in case of
  64096. * context lost for instance.
  64097. */
  64098. BoundingBoxRenderer.prototype.rebuild = function () {
  64099. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64100. if (vb) {
  64101. vb._rebuild();
  64102. }
  64103. this._createIndexBuffer();
  64104. };
  64105. /**
  64106. * @hidden
  64107. */
  64108. BoundingBoxRenderer.prototype.reset = function () {
  64109. this.renderList.reset();
  64110. };
  64111. /**
  64112. * Render the bounding boxes of a specific rendering group
  64113. * @param renderingGroupId defines the rendering group to render
  64114. */
  64115. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  64116. if (this.renderList.length === 0) {
  64117. return;
  64118. }
  64119. this._prepareRessources();
  64120. if (!this._colorShader.isReady()) {
  64121. return;
  64122. }
  64123. var engine = this.scene.getEngine();
  64124. engine.setDepthWrite(false);
  64125. this._colorShader._preBind();
  64126. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  64127. var boundingBox = this.renderList.data[boundingBoxIndex];
  64128. if (boundingBox._tag !== renderingGroupId) {
  64129. continue;
  64130. }
  64131. var min = boundingBox.minimum;
  64132. var max = boundingBox.maximum;
  64133. var diff = max.subtract(min);
  64134. var median = min.add(diff.scale(0.5));
  64135. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64136. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64137. .multiply(boundingBox.getWorldMatrix());
  64138. // VBOs
  64139. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64140. if (this.showBackLines) {
  64141. // Back
  64142. engine.setDepthFunctionToGreaterOrEqual();
  64143. this.scene.resetCachedMaterial();
  64144. this._colorShader.setColor4("color", this.backColor.toColor4());
  64145. this._colorShader.bind(worldMatrix);
  64146. // Draw order
  64147. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  64148. }
  64149. // Front
  64150. engine.setDepthFunctionToLess();
  64151. this.scene.resetCachedMaterial();
  64152. this._colorShader.setColor4("color", this.frontColor.toColor4());
  64153. this._colorShader.bind(worldMatrix);
  64154. // Draw order
  64155. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  64156. }
  64157. this._colorShader.unbind();
  64158. engine.setDepthFunctionToLessOrEqual();
  64159. engine.setDepthWrite(true);
  64160. };
  64161. /**
  64162. * In case of occlusion queries, we can render the occlusion bounding box through this method
  64163. * @param mesh Define the mesh to render the occlusion bounding box for
  64164. */
  64165. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  64166. this._prepareRessources();
  64167. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  64168. return;
  64169. }
  64170. var engine = this.scene.getEngine();
  64171. engine.setDepthWrite(false);
  64172. engine.setColorWrite(false);
  64173. this._colorShader._preBind();
  64174. var boundingBox = mesh._boundingInfo.boundingBox;
  64175. var min = boundingBox.minimum;
  64176. var max = boundingBox.maximum;
  64177. var diff = max.subtract(min);
  64178. var median = min.add(diff.scale(0.5));
  64179. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64180. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64181. .multiply(boundingBox.getWorldMatrix());
  64182. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64183. engine.setDepthFunctionToLess();
  64184. this.scene.resetCachedMaterial();
  64185. this._colorShader.bind(worldMatrix);
  64186. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  64187. this._colorShader.unbind();
  64188. engine.setDepthFunctionToLessOrEqual();
  64189. engine.setDepthWrite(true);
  64190. engine.setColorWrite(true);
  64191. };
  64192. /**
  64193. * Dispose and release the resources attached to this renderer.
  64194. */
  64195. BoundingBoxRenderer.prototype.dispose = function () {
  64196. if (!this._colorShader) {
  64197. return;
  64198. }
  64199. this.renderList.dispose();
  64200. this._colorShader.dispose();
  64201. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64202. if (buffer) {
  64203. buffer.dispose();
  64204. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64205. }
  64206. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  64207. };
  64208. return BoundingBoxRenderer;
  64209. }());
  64210. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  64211. })(BABYLON || (BABYLON = {}));
  64212. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  64213. var BABYLON;
  64214. (function (BABYLON) {
  64215. BABYLON.Engine.prototype.createTransformFeedback = function () {
  64216. return this._gl.createTransformFeedback();
  64217. };
  64218. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  64219. this._gl.deleteTransformFeedback(value);
  64220. };
  64221. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  64222. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  64223. };
  64224. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  64225. if (usePoints === void 0) { usePoints = true; }
  64226. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  64227. };
  64228. BABYLON.Engine.prototype.endTransformFeedback = function () {
  64229. this._gl.endTransformFeedback();
  64230. };
  64231. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  64232. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  64233. };
  64234. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  64235. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  64236. };
  64237. })(BABYLON || (BABYLON = {}));
  64238. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  64239. var BABYLON;
  64240. (function (BABYLON) {
  64241. /**
  64242. * This represents a GPU particle system in Babylon
  64243. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  64244. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  64245. */
  64246. var GPUParticleSystem = /** @class */ (function (_super) {
  64247. __extends(GPUParticleSystem, _super);
  64248. /**
  64249. * Instantiates a GPU particle system.
  64250. * 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.
  64251. * @param name The name of the particle system
  64252. * @param options The options used to create the system
  64253. * @param scene The scene the particle system belongs to
  64254. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  64255. */
  64256. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  64257. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  64258. var _this = _super.call(this, name) || this;
  64259. /**
  64260. * The layer mask we are rendering the particles through.
  64261. */
  64262. _this.layerMask = 0x0FFFFFFF;
  64263. _this._accumulatedCount = 0;
  64264. _this._targetIndex = 0;
  64265. _this._currentRenderId = -1;
  64266. _this._started = false;
  64267. _this._stopped = false;
  64268. _this._timeDelta = 0;
  64269. _this._attributesStrideSize = 21;
  64270. _this._actualFrame = 0;
  64271. _this._rawTextureWidth = 256;
  64272. /**
  64273. * An event triggered when the system is disposed.
  64274. */
  64275. _this.onDisposeObservable = new BABYLON.Observable();
  64276. /**
  64277. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  64278. * to override the particles.
  64279. */
  64280. _this.forceDepthWrite = false;
  64281. _this._preWarmDone = false;
  64282. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64283. // Setup the default processing configuration to the scene.
  64284. _this._attachImageProcessingConfiguration(null);
  64285. _this._engine = _this._scene.getEngine();
  64286. if (!options.randomTextureSize) {
  64287. delete options.randomTextureSize;
  64288. }
  64289. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  64290. var optionsAsNumber = options;
  64291. if (isFinite(optionsAsNumber)) {
  64292. fullOptions.capacity = optionsAsNumber;
  64293. }
  64294. _this._capacity = fullOptions.capacity;
  64295. _this._activeCount = fullOptions.capacity;
  64296. _this._currentActiveCount = 0;
  64297. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  64298. _this._scene.particleSystems.push(_this);
  64299. _this._updateEffectOptions = {
  64300. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  64301. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  64302. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  64303. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  64304. uniformBuffersNames: [],
  64305. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  64306. defines: "",
  64307. fallbacks: null,
  64308. onCompiled: null,
  64309. onError: null,
  64310. indexParameters: null,
  64311. maxSimultaneousLights: 0,
  64312. transformFeedbackVaryings: []
  64313. };
  64314. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  64315. // Random data
  64316. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  64317. var d = [];
  64318. for (var i = 0; i < maxTextureSize; ++i) {
  64319. d.push(Math.random());
  64320. d.push(Math.random());
  64321. d.push(Math.random());
  64322. d.push(Math.random());
  64323. }
  64324. _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);
  64325. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64326. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64327. d = [];
  64328. for (var i = 0; i < maxTextureSize; ++i) {
  64329. d.push(Math.random());
  64330. d.push(Math.random());
  64331. d.push(Math.random());
  64332. d.push(Math.random());
  64333. }
  64334. _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);
  64335. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64336. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64337. _this._randomTextureSize = maxTextureSize;
  64338. return _this;
  64339. }
  64340. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  64341. /**
  64342. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  64343. */
  64344. get: function () {
  64345. if (!BABYLON.Engine.LastCreatedEngine) {
  64346. return false;
  64347. }
  64348. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  64349. },
  64350. enumerable: true,
  64351. configurable: true
  64352. });
  64353. /**
  64354. * Gets the maximum number of particles active at the same time.
  64355. * @returns The max number of active particles.
  64356. */
  64357. GPUParticleSystem.prototype.getCapacity = function () {
  64358. return this._capacity;
  64359. };
  64360. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  64361. /**
  64362. * Gets or set the number of active particles
  64363. */
  64364. get: function () {
  64365. return this._activeCount;
  64366. },
  64367. set: function (value) {
  64368. this._activeCount = Math.min(value, this._capacity);
  64369. },
  64370. enumerable: true,
  64371. configurable: true
  64372. });
  64373. /**
  64374. * Is this system ready to be used/rendered
  64375. * @return true if the system is ready
  64376. */
  64377. GPUParticleSystem.prototype.isReady = function () {
  64378. if (!this._updateEffect) {
  64379. this._recreateUpdateEffect();
  64380. this._recreateRenderEffect();
  64381. return false;
  64382. }
  64383. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  64384. return false;
  64385. }
  64386. return true;
  64387. };
  64388. /**
  64389. * Gets if the system has been started. (Note: this will still be true after stop is called)
  64390. * @returns True if it has been started, otherwise false.
  64391. */
  64392. GPUParticleSystem.prototype.isStarted = function () {
  64393. return this._started;
  64394. };
  64395. /**
  64396. * Starts the particle system and begins to emit
  64397. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  64398. */
  64399. GPUParticleSystem.prototype.start = function (delay) {
  64400. var _this = this;
  64401. if (delay === void 0) { delay = this.startDelay; }
  64402. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  64403. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  64404. }
  64405. if (delay) {
  64406. setTimeout(function () {
  64407. _this.start(0);
  64408. }, delay);
  64409. return;
  64410. }
  64411. this._started = true;
  64412. this._stopped = false;
  64413. this._preWarmDone = false;
  64414. // Animations
  64415. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  64416. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  64417. }
  64418. };
  64419. /**
  64420. * Stops the particle system.
  64421. */
  64422. GPUParticleSystem.prototype.stop = function () {
  64423. this._stopped = true;
  64424. };
  64425. /**
  64426. * Remove all active particles
  64427. */
  64428. GPUParticleSystem.prototype.reset = function () {
  64429. this._releaseBuffers();
  64430. this._releaseVAOs();
  64431. this._currentActiveCount = 0;
  64432. this._targetIndex = 0;
  64433. };
  64434. /**
  64435. * Returns the string "GPUParticleSystem"
  64436. * @returns a string containing the class name
  64437. */
  64438. GPUParticleSystem.prototype.getClassName = function () {
  64439. return "GPUParticleSystem";
  64440. };
  64441. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  64442. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  64443. this._releaseBuffers();
  64444. return this;
  64445. };
  64446. /**
  64447. * Adds a new color gradient
  64448. * @param gradient defines the gradient to use (between 0 and 1)
  64449. * @param color1 defines the color to affect to the specified gradient
  64450. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  64451. * @returns the current particle system
  64452. */
  64453. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  64454. if (!this._colorGradients) {
  64455. this._colorGradients = [];
  64456. }
  64457. var colorGradient = new BABYLON.ColorGradient();
  64458. colorGradient.gradient = gradient;
  64459. colorGradient.color1 = color1;
  64460. this._colorGradients.push(colorGradient);
  64461. this._colorGradients.sort(function (a, b) {
  64462. if (a.gradient < b.gradient) {
  64463. return -1;
  64464. }
  64465. else if (a.gradient > b.gradient) {
  64466. return 1;
  64467. }
  64468. return 0;
  64469. });
  64470. if (this._colorGradientsTexture) {
  64471. this._colorGradientsTexture.dispose();
  64472. this._colorGradientsTexture = null;
  64473. }
  64474. this._releaseBuffers();
  64475. return this;
  64476. };
  64477. /**
  64478. * Remove a specific color gradient
  64479. * @param gradient defines the gradient to remove
  64480. * @returns the current particle system
  64481. */
  64482. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  64483. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  64484. this._colorGradientsTexture = null;
  64485. return this;
  64486. };
  64487. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  64488. var valueGradient = new BABYLON.FactorGradient();
  64489. valueGradient.gradient = gradient;
  64490. valueGradient.factor1 = factor;
  64491. factorGradients.push(valueGradient);
  64492. factorGradients.sort(function (a, b) {
  64493. if (a.gradient < b.gradient) {
  64494. return -1;
  64495. }
  64496. else if (a.gradient > b.gradient) {
  64497. return 1;
  64498. }
  64499. return 0;
  64500. });
  64501. this._releaseBuffers();
  64502. };
  64503. /**
  64504. * Adds a new size gradient
  64505. * @param gradient defines the gradient to use (between 0 and 1)
  64506. * @param factor defines the size factor to affect to the specified gradient
  64507. * @returns the current particle system
  64508. */
  64509. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  64510. if (!this._sizeGradients) {
  64511. this._sizeGradients = [];
  64512. }
  64513. this._addFactorGradient(this._sizeGradients, gradient, factor);
  64514. if (this._sizeGradientsTexture) {
  64515. this._sizeGradientsTexture.dispose();
  64516. this._sizeGradientsTexture = null;
  64517. }
  64518. this._releaseBuffers();
  64519. return this;
  64520. };
  64521. /**
  64522. * Remove a specific size gradient
  64523. * @param gradient defines the gradient to remove
  64524. * @returns the current particle system
  64525. */
  64526. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  64527. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  64528. this._sizeGradientsTexture = null;
  64529. return this;
  64530. };
  64531. /**
  64532. * Adds a new angular speed gradient
  64533. * @param gradient defines the gradient to use (between 0 and 1)
  64534. * @param factor defines the angular speed to affect to the specified gradient
  64535. * @returns the current particle system
  64536. */
  64537. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  64538. if (!this._angularSpeedGradients) {
  64539. this._angularSpeedGradients = [];
  64540. }
  64541. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  64542. if (this._angularSpeedGradientsTexture) {
  64543. this._angularSpeedGradientsTexture.dispose();
  64544. this._angularSpeedGradientsTexture = null;
  64545. }
  64546. this._releaseBuffers();
  64547. return this;
  64548. };
  64549. /**
  64550. * Remove a specific angular speed gradient
  64551. * @param gradient defines the gradient to remove
  64552. * @returns the current particle system
  64553. */
  64554. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  64555. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  64556. this._angularSpeedGradientsTexture = null;
  64557. return this;
  64558. };
  64559. /**
  64560. * Adds a new velocity gradient
  64561. * @param gradient defines the gradient to use (between 0 and 1)
  64562. * @param factor defines the velocity to affect to the specified gradient
  64563. * @returns the current particle system
  64564. */
  64565. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  64566. if (!this._velocityGradients) {
  64567. this._velocityGradients = [];
  64568. }
  64569. this._addFactorGradient(this._velocityGradients, gradient, factor);
  64570. if (this._velocityGradientsTexture) {
  64571. this._velocityGradientsTexture.dispose();
  64572. this._velocityGradientsTexture = null;
  64573. }
  64574. this._releaseBuffers();
  64575. return this;
  64576. };
  64577. /**
  64578. * Remove a specific velocity gradient
  64579. * @param gradient defines the gradient to remove
  64580. * @returns the current particle system
  64581. */
  64582. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  64583. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  64584. this._velocityGradientsTexture = null;
  64585. return this;
  64586. };
  64587. /**
  64588. * Adds a new limit velocity gradient
  64589. * @param gradient defines the gradient to use (between 0 and 1)
  64590. * @param factor defines the limit velocity value to affect to the specified gradient
  64591. * @returns the current particle system
  64592. */
  64593. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  64594. if (!this._limitVelocityGradients) {
  64595. this._limitVelocityGradients = [];
  64596. }
  64597. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  64598. if (this._limitVelocityGradientsTexture) {
  64599. this._limitVelocityGradientsTexture.dispose();
  64600. this._limitVelocityGradientsTexture = null;
  64601. }
  64602. this._releaseBuffers();
  64603. return this;
  64604. };
  64605. /**
  64606. * Remove a specific limit velocity gradient
  64607. * @param gradient defines the gradient to remove
  64608. * @returns the current particle system
  64609. */
  64610. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  64611. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  64612. this._limitVelocityGradientsTexture = null;
  64613. return this;
  64614. };
  64615. /**
  64616. * Adds a new drag gradient
  64617. * @param gradient defines the gradient to use (between 0 and 1)
  64618. * @param factor defines the drag value to affect to the specified gradient
  64619. * @returns the current particle system
  64620. */
  64621. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  64622. if (!this._dragGradients) {
  64623. this._dragGradients = [];
  64624. }
  64625. this._addFactorGradient(this._dragGradients, gradient, factor);
  64626. if (this._dragGradientsTexture) {
  64627. this._dragGradientsTexture.dispose();
  64628. this._dragGradientsTexture = null;
  64629. }
  64630. this._releaseBuffers();
  64631. return this;
  64632. };
  64633. /**
  64634. * Remove a specific drag gradient
  64635. * @param gradient defines the gradient to remove
  64636. * @returns the current particle system
  64637. */
  64638. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  64639. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  64640. this._dragGradientsTexture = null;
  64641. return this;
  64642. };
  64643. /**
  64644. * Not supported by GPUParticleSystem
  64645. * @param gradient defines the gradient to use (between 0 and 1)
  64646. * @param factor defines the emit rate value to affect to the specified gradient
  64647. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  64648. * @returns the current particle system
  64649. */
  64650. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  64651. // Do nothing as emit rate is not supported by GPUParticleSystem
  64652. return this;
  64653. };
  64654. /**
  64655. * Not supported by GPUParticleSystem
  64656. * @param gradient defines the gradient to remove
  64657. * @returns the current particle system
  64658. */
  64659. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  64660. // Do nothing as emit rate is not supported by GPUParticleSystem
  64661. return this;
  64662. };
  64663. /**
  64664. * Not supported by GPUParticleSystem
  64665. * @param gradient defines the gradient to use (between 0 and 1)
  64666. * @param factor defines the start size value to affect to the specified gradient
  64667. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  64668. * @returns the current particle system
  64669. */
  64670. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  64671. // Do nothing as start size is not supported by GPUParticleSystem
  64672. return this;
  64673. };
  64674. /**
  64675. * Not supported by GPUParticleSystem
  64676. * @param gradient defines the gradient to remove
  64677. * @returns the current particle system
  64678. */
  64679. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  64680. // Do nothing as start size is not supported by GPUParticleSystem
  64681. return this;
  64682. };
  64683. /**
  64684. * Not supported by GPUParticleSystem
  64685. * @param gradient defines the gradient to use (between 0 and 1)
  64686. * @param min defines the color remap minimal range
  64687. * @param max defines the color remap maximal range
  64688. * @returns the current particle system
  64689. */
  64690. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  64691. // Do nothing as start size is not supported by GPUParticleSystem
  64692. return this;
  64693. };
  64694. /**
  64695. * Not supported by GPUParticleSystem
  64696. * @param gradient defines the gradient to remove
  64697. * @returns the current particle system
  64698. */
  64699. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  64700. // Do nothing as start size is not supported by GPUParticleSystem
  64701. return this;
  64702. };
  64703. /**
  64704. * Not supported by GPUParticleSystem
  64705. * @param gradient defines the gradient to use (between 0 and 1)
  64706. * @param min defines the alpha remap minimal range
  64707. * @param max defines the alpha remap maximal range
  64708. * @returns the current particle system
  64709. */
  64710. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  64711. // Do nothing as start size is not supported by GPUParticleSystem
  64712. return this;
  64713. };
  64714. /**
  64715. * Not supported by GPUParticleSystem
  64716. * @param gradient defines the gradient to remove
  64717. * @returns the current particle system
  64718. */
  64719. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  64720. // Do nothing as start size is not supported by GPUParticleSystem
  64721. return this;
  64722. };
  64723. /**
  64724. * Not supported by GPUParticleSystem
  64725. * @param gradient defines the gradient to use (between 0 and 1)
  64726. * @param color defines the color to affect to the specified gradient
  64727. * @returns the current particle system
  64728. */
  64729. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  64730. //Not supported by GPUParticleSystem
  64731. return this;
  64732. };
  64733. /**
  64734. * Not supported by GPUParticleSystem
  64735. * @param gradient defines the gradient to remove
  64736. * @returns the current particle system
  64737. */
  64738. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  64739. //Not supported by GPUParticleSystem
  64740. return this;
  64741. };
  64742. /**
  64743. * Not supported by GPUParticleSystem
  64744. * @returns the list of ramp gradients
  64745. */
  64746. GPUParticleSystem.prototype.getRampGradients = function () {
  64747. return null;
  64748. };
  64749. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  64750. /**
  64751. * Not supported by GPUParticleSystem
  64752. * Gets or sets a boolean indicating that ramp gradients must be used
  64753. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  64754. */
  64755. get: function () {
  64756. //Not supported by GPUParticleSystem
  64757. return false;
  64758. },
  64759. set: function (value) {
  64760. //Not supported by GPUParticleSystem
  64761. },
  64762. enumerable: true,
  64763. configurable: true
  64764. });
  64765. /**
  64766. * Not supported by GPUParticleSystem
  64767. * @param gradient defines the gradient to use (between 0 and 1)
  64768. * @param factor defines the life time factor to affect to the specified gradient
  64769. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  64770. * @returns the current particle system
  64771. */
  64772. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  64773. //Not supported by GPUParticleSystem
  64774. return this;
  64775. };
  64776. /**
  64777. * Not supported by GPUParticleSystem
  64778. * @param gradient defines the gradient to remove
  64779. * @returns the current particle system
  64780. */
  64781. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  64782. //Not supported by GPUParticleSystem
  64783. return this;
  64784. };
  64785. GPUParticleSystem.prototype._reset = function () {
  64786. this._releaseBuffers();
  64787. };
  64788. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  64789. var updateVertexBuffers = {};
  64790. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  64791. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  64792. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  64793. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  64794. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  64795. var offset = 12;
  64796. if (!this._colorGradientsTexture) {
  64797. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  64798. offset += 4;
  64799. }
  64800. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  64801. offset += 3;
  64802. if (!this._isBillboardBased) {
  64803. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  64804. offset += 3;
  64805. }
  64806. if (this._angularSpeedGradientsTexture) {
  64807. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  64808. offset += 1;
  64809. }
  64810. else {
  64811. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  64812. offset += 2;
  64813. }
  64814. if (this._isAnimationSheetEnabled) {
  64815. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  64816. offset += 1;
  64817. if (this.spriteRandomStartCell) {
  64818. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  64819. offset += 1;
  64820. }
  64821. }
  64822. if (this.noiseTexture) {
  64823. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  64824. offset += 3;
  64825. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  64826. offset += 3;
  64827. }
  64828. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  64829. this._engine.bindArrayBuffer(null);
  64830. return vao;
  64831. };
  64832. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  64833. var renderVertexBuffers = {};
  64834. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  64835. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  64836. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  64837. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  64838. var offset = 12;
  64839. if (!this._colorGradientsTexture) {
  64840. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  64841. offset += 4;
  64842. }
  64843. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  64844. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  64845. }
  64846. offset += 3; // Direction
  64847. if (!this._isBillboardBased) {
  64848. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  64849. offset += 3;
  64850. }
  64851. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  64852. if (this._angularSpeedGradientsTexture) {
  64853. offset++;
  64854. }
  64855. else {
  64856. offset += 2;
  64857. }
  64858. if (this._isAnimationSheetEnabled) {
  64859. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  64860. offset += 1;
  64861. if (this.spriteRandomStartCell) {
  64862. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  64863. offset += 1;
  64864. }
  64865. }
  64866. if (this.noiseTexture) {
  64867. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  64868. offset += 3;
  64869. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  64870. offset += 3;
  64871. }
  64872. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  64873. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  64874. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  64875. this._engine.bindArrayBuffer(null);
  64876. return vao;
  64877. };
  64878. GPUParticleSystem.prototype._initialize = function (force) {
  64879. if (force === void 0) { force = false; }
  64880. if (this._buffer0 && !force) {
  64881. return;
  64882. }
  64883. var engine = this._scene.getEngine();
  64884. var data = new Array();
  64885. if (!this.isBillboardBased) {
  64886. this._attributesStrideSize += 3;
  64887. }
  64888. if (this._colorGradientsTexture) {
  64889. this._attributesStrideSize -= 4;
  64890. }
  64891. if (this._angularSpeedGradientsTexture) {
  64892. this._attributesStrideSize -= 1;
  64893. }
  64894. if (this._isAnimationSheetEnabled) {
  64895. this._attributesStrideSize += 1;
  64896. if (this.spriteRandomStartCell) {
  64897. this._attributesStrideSize += 1;
  64898. }
  64899. }
  64900. if (this.noiseTexture) {
  64901. this._attributesStrideSize += 6;
  64902. }
  64903. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  64904. // position
  64905. data.push(0.0);
  64906. data.push(0.0);
  64907. data.push(0.0);
  64908. // Age and life
  64909. data.push(0.0); // create the particle as a dead one to create a new one at start
  64910. data.push(0.0);
  64911. // Seed
  64912. data.push(Math.random());
  64913. data.push(Math.random());
  64914. data.push(Math.random());
  64915. data.push(Math.random());
  64916. // Size
  64917. data.push(0.0);
  64918. data.push(0.0);
  64919. data.push(0.0);
  64920. if (!this._colorGradientsTexture) {
  64921. // color
  64922. data.push(0.0);
  64923. data.push(0.0);
  64924. data.push(0.0);
  64925. data.push(0.0);
  64926. }
  64927. // direction
  64928. data.push(0.0);
  64929. data.push(0.0);
  64930. data.push(0.0);
  64931. if (!this.isBillboardBased) {
  64932. // initialDirection
  64933. data.push(0.0);
  64934. data.push(0.0);
  64935. data.push(0.0);
  64936. }
  64937. // angle
  64938. data.push(0.0);
  64939. if (!this._angularSpeedGradientsTexture) {
  64940. data.push(0.0);
  64941. }
  64942. if (this._isAnimationSheetEnabled) {
  64943. data.push(0.0);
  64944. if (this.spriteRandomStartCell) {
  64945. data.push(0.0);
  64946. }
  64947. }
  64948. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  64949. data.push(Math.random());
  64950. data.push(Math.random());
  64951. data.push(Math.random());
  64952. data.push(Math.random());
  64953. data.push(Math.random());
  64954. data.push(Math.random());
  64955. }
  64956. }
  64957. // Sprite data
  64958. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  64959. -0.5, 0.5, 0, 1,
  64960. -0.5, -0.5, 0, 0,
  64961. 0.5, -0.5, 1, 0]);
  64962. // Buffers
  64963. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  64964. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  64965. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  64966. // Update VAO
  64967. this._updateVAO = [];
  64968. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  64969. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  64970. // Render VAO
  64971. this._renderVAO = [];
  64972. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  64973. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  64974. // Links
  64975. this._sourceBuffer = this._buffer0;
  64976. this._targetBuffer = this._buffer1;
  64977. };
  64978. /** @hidden */
  64979. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  64980. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  64981. if (this._isBillboardBased) {
  64982. defines += "\n#define BILLBOARD";
  64983. }
  64984. if (this._colorGradientsTexture) {
  64985. defines += "\n#define COLORGRADIENTS";
  64986. }
  64987. if (this._sizeGradientsTexture) {
  64988. defines += "\n#define SIZEGRADIENTS";
  64989. }
  64990. if (this._angularSpeedGradientsTexture) {
  64991. defines += "\n#define ANGULARSPEEDGRADIENTS";
  64992. }
  64993. if (this._velocityGradientsTexture) {
  64994. defines += "\n#define VELOCITYGRADIENTS";
  64995. }
  64996. if (this._limitVelocityGradientsTexture) {
  64997. defines += "\n#define LIMITVELOCITYGRADIENTS";
  64998. }
  64999. if (this._dragGradientsTexture) {
  65000. defines += "\n#define DRAGGRADIENTS";
  65001. }
  65002. if (this.isAnimationSheetEnabled) {
  65003. defines += "\n#define ANIMATESHEET";
  65004. if (this.spriteRandomStartCell) {
  65005. defines += "\n#define ANIMATESHEETRANDOMSTART";
  65006. }
  65007. }
  65008. if (this.noiseTexture) {
  65009. defines += "\n#define NOISE";
  65010. }
  65011. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  65012. return;
  65013. }
  65014. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  65015. if (!this._colorGradientsTexture) {
  65016. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  65017. }
  65018. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  65019. if (!this._isBillboardBased) {
  65020. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  65021. }
  65022. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  65023. if (this.isAnimationSheetEnabled) {
  65024. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  65025. if (this.spriteRandomStartCell) {
  65026. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  65027. }
  65028. }
  65029. if (this.noiseTexture) {
  65030. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  65031. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  65032. }
  65033. this._updateEffectOptions.defines = defines;
  65034. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  65035. };
  65036. /** @hidden */
  65037. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  65038. var defines = "";
  65039. if (this._scene.clipPlane) {
  65040. defines = "\n#define CLIPPLANE";
  65041. }
  65042. if (this._scene.clipPlane2) {
  65043. defines = "\n#define CLIPPLANE2";
  65044. }
  65045. if (this._scene.clipPlane3) {
  65046. defines = "\n#define CLIPPLANE3";
  65047. }
  65048. if (this._scene.clipPlane4) {
  65049. defines = "\n#define CLIPPLANE4";
  65050. }
  65051. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  65052. defines = "\n#define BLENDMULTIPLYMODE";
  65053. }
  65054. if (this._isBillboardBased) {
  65055. defines += "\n#define BILLBOARD";
  65056. switch (this.billboardMode) {
  65057. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  65058. defines += "\n#define BILLBOARDY";
  65059. break;
  65060. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  65061. defines += "\n#define BILLBOARDSTRETCHED";
  65062. break;
  65063. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  65064. default:
  65065. break;
  65066. }
  65067. }
  65068. if (this._colorGradientsTexture) {
  65069. defines += "\n#define COLORGRADIENTS";
  65070. }
  65071. if (this.isAnimationSheetEnabled) {
  65072. defines += "\n#define ANIMATESHEET";
  65073. }
  65074. if (this._imageProcessingConfiguration) {
  65075. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  65076. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  65077. }
  65078. if (this._renderEffect && this._renderEffect.defines === defines) {
  65079. return;
  65080. }
  65081. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  65082. var samplers = ["textureSampler", "colorGradientSampler"];
  65083. if (BABYLON.ImageProcessingConfiguration) {
  65084. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  65085. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  65086. }
  65087. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  65088. };
  65089. /**
  65090. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  65091. * @param preWarm defines if we are in the pre-warmimg phase
  65092. */
  65093. GPUParticleSystem.prototype.animate = function (preWarm) {
  65094. if (preWarm === void 0) { preWarm = false; }
  65095. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  65096. this._actualFrame += this._timeDelta;
  65097. if (!this._stopped) {
  65098. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  65099. this.stop();
  65100. }
  65101. }
  65102. };
  65103. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  65104. var texture = this[textureName];
  65105. if (!factorGradients || !factorGradients.length || texture) {
  65106. return;
  65107. }
  65108. var data = new Float32Array(this._rawTextureWidth);
  65109. for (var x = 0; x < this._rawTextureWidth; x++) {
  65110. var ratio = x / this._rawTextureWidth;
  65111. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  65112. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  65113. });
  65114. }
  65115. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65116. };
  65117. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  65118. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  65119. };
  65120. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  65121. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  65122. };
  65123. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  65124. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  65125. };
  65126. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  65127. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  65128. };
  65129. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  65130. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  65131. };
  65132. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  65133. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  65134. return;
  65135. }
  65136. var data = new Uint8Array(this._rawTextureWidth * 4);
  65137. var tmpColor = BABYLON.Tmp.Color4[0];
  65138. for (var x = 0; x < this._rawTextureWidth; x++) {
  65139. var ratio = x / this._rawTextureWidth;
  65140. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  65141. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  65142. data[x * 4] = tmpColor.r * 255;
  65143. data[x * 4 + 1] = tmpColor.g * 255;
  65144. data[x * 4 + 2] = tmpColor.b * 255;
  65145. data[x * 4 + 3] = tmpColor.a * 255;
  65146. });
  65147. }
  65148. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65149. };
  65150. /**
  65151. * Renders the particle system in its current state
  65152. * @param preWarm defines if the system should only update the particles but not render them
  65153. * @returns the current number of particles
  65154. */
  65155. GPUParticleSystem.prototype.render = function (preWarm) {
  65156. if (preWarm === void 0) { preWarm = false; }
  65157. if (!this._started) {
  65158. return 0;
  65159. }
  65160. this._createColorGradientTexture();
  65161. this._createSizeGradientTexture();
  65162. this._createAngularSpeedGradientTexture();
  65163. this._createVelocityGradientTexture();
  65164. this._createLimitVelocityGradientTexture();
  65165. this._createDragGradientTexture();
  65166. this._recreateUpdateEffect();
  65167. this._recreateRenderEffect();
  65168. if (!this.isReady()) {
  65169. return 0;
  65170. }
  65171. if (!preWarm) {
  65172. if (!this._preWarmDone && this.preWarmCycles) {
  65173. for (var index = 0; index < this.preWarmCycles; index++) {
  65174. this.animate(true);
  65175. this.render(true);
  65176. }
  65177. this._preWarmDone = true;
  65178. }
  65179. if (this._currentRenderId === this._scene.getRenderId()) {
  65180. return 0;
  65181. }
  65182. this._currentRenderId = this._scene.getRenderId();
  65183. }
  65184. // Get everything ready to render
  65185. this._initialize();
  65186. this._accumulatedCount += this.emitRate * this._timeDelta;
  65187. if (this._accumulatedCount > 1) {
  65188. var intPart = this._accumulatedCount | 0;
  65189. this._accumulatedCount -= intPart;
  65190. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  65191. }
  65192. if (!this._currentActiveCount) {
  65193. return 0;
  65194. }
  65195. // Enable update effect
  65196. this._engine.enableEffect(this._updateEffect);
  65197. this._engine.setState(false);
  65198. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  65199. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  65200. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  65201. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  65202. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  65203. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  65204. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  65205. if (!this._colorGradientsTexture) {
  65206. this._updateEffect.setDirectColor4("color1", this.color1);
  65207. this._updateEffect.setDirectColor4("color2", this.color2);
  65208. }
  65209. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  65210. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  65211. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  65212. this._updateEffect.setVector3("gravity", this.gravity);
  65213. if (this._sizeGradientsTexture) {
  65214. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  65215. }
  65216. if (this._angularSpeedGradientsTexture) {
  65217. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  65218. }
  65219. if (this._velocityGradientsTexture) {
  65220. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  65221. }
  65222. if (this._limitVelocityGradientsTexture) {
  65223. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  65224. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  65225. }
  65226. if (this._dragGradientsTexture) {
  65227. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  65228. }
  65229. if (this.particleEmitterType) {
  65230. this.particleEmitterType.applyToShader(this._updateEffect);
  65231. }
  65232. if (this._isAnimationSheetEnabled) {
  65233. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  65234. }
  65235. if (this.noiseTexture) {
  65236. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  65237. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  65238. }
  65239. var emitterWM;
  65240. if (this.emitter.position) {
  65241. var emitterMesh = this.emitter;
  65242. emitterWM = emitterMesh.getWorldMatrix();
  65243. }
  65244. else {
  65245. var emitterPosition = this.emitter;
  65246. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  65247. }
  65248. this._updateEffect.setMatrix("emitterWM", emitterWM);
  65249. // Bind source VAO
  65250. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  65251. // Update
  65252. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  65253. this._engine.setRasterizerState(false);
  65254. this._engine.beginTransformFeedback(true);
  65255. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  65256. this._engine.endTransformFeedback();
  65257. this._engine.setRasterizerState(true);
  65258. this._engine.bindTransformFeedbackBuffer(null);
  65259. if (!preWarm) {
  65260. // Enable render effect
  65261. this._engine.enableEffect(this._renderEffect);
  65262. var viewMatrix = this._scene.getViewMatrix();
  65263. this._renderEffect.setMatrix("view", viewMatrix);
  65264. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  65265. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  65266. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  65267. if (this._colorGradientsTexture) {
  65268. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  65269. }
  65270. else {
  65271. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  65272. }
  65273. if (this._isAnimationSheetEnabled && this.particleTexture) {
  65274. var baseSize = this.particleTexture.getBaseSize();
  65275. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  65276. }
  65277. if (this._isBillboardBased) {
  65278. var camera = this._scene.activeCamera;
  65279. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  65280. }
  65281. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  65282. var invView = viewMatrix.clone();
  65283. invView.invert();
  65284. this._renderEffect.setMatrix("invView", invView);
  65285. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  65286. }
  65287. // image processing
  65288. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  65289. this._imageProcessingConfiguration.bind(this._renderEffect);
  65290. }
  65291. // Draw order
  65292. switch (this.blendMode) {
  65293. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  65294. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  65295. break;
  65296. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  65297. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  65298. break;
  65299. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  65300. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  65301. break;
  65302. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  65303. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  65304. break;
  65305. }
  65306. if (this.forceDepthWrite) {
  65307. this._engine.setDepthWrite(true);
  65308. }
  65309. // Bind source VAO
  65310. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  65311. // Render
  65312. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  65313. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65314. }
  65315. // Switch VAOs
  65316. this._targetIndex++;
  65317. if (this._targetIndex === 2) {
  65318. this._targetIndex = 0;
  65319. }
  65320. // Switch buffers
  65321. var tmpBuffer = this._sourceBuffer;
  65322. this._sourceBuffer = this._targetBuffer;
  65323. this._targetBuffer = tmpBuffer;
  65324. return this._currentActiveCount;
  65325. };
  65326. /**
  65327. * Rebuilds the particle system
  65328. */
  65329. GPUParticleSystem.prototype.rebuild = function () {
  65330. this._initialize(true);
  65331. };
  65332. GPUParticleSystem.prototype._releaseBuffers = function () {
  65333. if (this._buffer0) {
  65334. this._buffer0.dispose();
  65335. this._buffer0 = null;
  65336. }
  65337. if (this._buffer1) {
  65338. this._buffer1.dispose();
  65339. this._buffer1 = null;
  65340. }
  65341. if (this._spriteBuffer) {
  65342. this._spriteBuffer.dispose();
  65343. this._spriteBuffer = null;
  65344. }
  65345. };
  65346. GPUParticleSystem.prototype._releaseVAOs = function () {
  65347. if (!this._updateVAO) {
  65348. return;
  65349. }
  65350. for (var index = 0; index < this._updateVAO.length; index++) {
  65351. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  65352. }
  65353. this._updateVAO = [];
  65354. for (var index = 0; index < this._renderVAO.length; index++) {
  65355. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  65356. }
  65357. this._renderVAO = [];
  65358. };
  65359. /**
  65360. * Disposes the particle system and free the associated resources
  65361. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  65362. */
  65363. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  65364. if (disposeTexture === void 0) { disposeTexture = true; }
  65365. var index = this._scene.particleSystems.indexOf(this);
  65366. if (index > -1) {
  65367. this._scene.particleSystems.splice(index, 1);
  65368. }
  65369. this._releaseBuffers();
  65370. this._releaseVAOs();
  65371. if (this._colorGradientsTexture) {
  65372. this._colorGradientsTexture.dispose();
  65373. this._colorGradientsTexture = null;
  65374. }
  65375. if (this._sizeGradientsTexture) {
  65376. this._sizeGradientsTexture.dispose();
  65377. this._sizeGradientsTexture = null;
  65378. }
  65379. if (this._angularSpeedGradientsTexture) {
  65380. this._angularSpeedGradientsTexture.dispose();
  65381. this._angularSpeedGradientsTexture = null;
  65382. }
  65383. if (this._velocityGradientsTexture) {
  65384. this._velocityGradientsTexture.dispose();
  65385. this._velocityGradientsTexture = null;
  65386. }
  65387. if (this._limitVelocityGradientsTexture) {
  65388. this._limitVelocityGradientsTexture.dispose();
  65389. this._limitVelocityGradientsTexture = null;
  65390. }
  65391. if (this._dragGradientsTexture) {
  65392. this._dragGradientsTexture.dispose();
  65393. this._dragGradientsTexture = null;
  65394. }
  65395. if (this._randomTexture) {
  65396. this._randomTexture.dispose();
  65397. this._randomTexture = null;
  65398. }
  65399. if (this._randomTexture2) {
  65400. this._randomTexture2.dispose();
  65401. this._randomTexture2 = null;
  65402. }
  65403. if (disposeTexture && this.particleTexture) {
  65404. this.particleTexture.dispose();
  65405. this.particleTexture = null;
  65406. }
  65407. if (disposeTexture && this.noiseTexture) {
  65408. this.noiseTexture.dispose();
  65409. this.noiseTexture = null;
  65410. }
  65411. // Callback
  65412. this.onDisposeObservable.notifyObservers(this);
  65413. this.onDisposeObservable.clear();
  65414. };
  65415. /**
  65416. * Clones the particle system.
  65417. * @param name The name of the cloned object
  65418. * @param newEmitter The new emitter to use
  65419. * @returns the cloned particle system
  65420. */
  65421. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  65422. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  65423. BABYLON.Tools.DeepCopy(this, result);
  65424. if (newEmitter === undefined) {
  65425. newEmitter = this.emitter;
  65426. }
  65427. result.emitter = newEmitter;
  65428. if (this.particleTexture) {
  65429. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  65430. }
  65431. return result;
  65432. };
  65433. /**
  65434. * Serializes the particle system to a JSON object.
  65435. * @returns the JSON object
  65436. */
  65437. GPUParticleSystem.prototype.serialize = function () {
  65438. var serializationObject = {};
  65439. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  65440. serializationObject.activeParticleCount = this.activeParticleCount;
  65441. return serializationObject;
  65442. };
  65443. /**
  65444. * Parses a JSON object to create a GPU particle system.
  65445. * @param parsedParticleSystem The JSON object to parse
  65446. * @param scene The scene to create the particle system in
  65447. * @param rootUrl The root url to use to load external dependencies like texture
  65448. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  65449. * @returns the parsed GPU particle system
  65450. */
  65451. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  65452. if (doNotStart === void 0) { doNotStart = false; }
  65453. var name = parsedParticleSystem.name;
  65454. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  65455. if (parsedParticleSystem.activeParticleCount) {
  65456. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  65457. }
  65458. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  65459. // Auto start
  65460. if (parsedParticleSystem.preventAutoStart) {
  65461. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  65462. }
  65463. if (!doNotStart && !particleSystem.preventAutoStart) {
  65464. particleSystem.start();
  65465. }
  65466. return particleSystem;
  65467. };
  65468. return GPUParticleSystem;
  65469. }(BABYLON.BaseParticleSystem));
  65470. BABYLON.GPUParticleSystem = GPUParticleSystem;
  65471. })(BABYLON || (BABYLON = {}));
  65472. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  65473. var BABYLON;
  65474. (function (BABYLON) {
  65475. /**
  65476. * Represents one particle of a solid particle system.
  65477. */
  65478. var SolidParticle = /** @class */ (function () {
  65479. /**
  65480. * Creates a Solid Particle object.
  65481. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  65482. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  65483. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  65484. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  65485. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  65486. * @param shapeId (integer) is the model shape identifier in the SPS.
  65487. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  65488. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  65489. */
  65490. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  65491. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  65492. /**
  65493. * particle global index
  65494. */
  65495. this.idx = 0;
  65496. /**
  65497. * The color of the particle
  65498. */
  65499. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65500. /**
  65501. * The world space position of the particle.
  65502. */
  65503. this.position = BABYLON.Vector3.Zero();
  65504. /**
  65505. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  65506. */
  65507. this.rotation = BABYLON.Vector3.Zero();
  65508. /**
  65509. * The scaling of the particle.
  65510. */
  65511. this.scaling = BABYLON.Vector3.One();
  65512. /**
  65513. * The uvs of the particle.
  65514. */
  65515. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  65516. /**
  65517. * The current speed of the particle.
  65518. */
  65519. this.velocity = BABYLON.Vector3.Zero();
  65520. /**
  65521. * The pivot point in the particle local space.
  65522. */
  65523. this.pivot = BABYLON.Vector3.Zero();
  65524. /**
  65525. * Must the particle be translated from its pivot point in its local space ?
  65526. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  65527. * Default : false
  65528. */
  65529. this.translateFromPivot = false;
  65530. /**
  65531. * Is the particle active or not ?
  65532. */
  65533. this.alive = true;
  65534. /**
  65535. * Is the particle visible or not ?
  65536. */
  65537. this.isVisible = true;
  65538. /**
  65539. * Index of this particle in the global "positions" array (Internal use)
  65540. * @hidden
  65541. */
  65542. this._pos = 0;
  65543. /**
  65544. * @hidden Index of this particle in the global "indices" array (Internal use)
  65545. */
  65546. this._ind = 0;
  65547. /**
  65548. * ModelShape id of this particle
  65549. */
  65550. this.shapeId = 0;
  65551. /**
  65552. * Index of the particle in its shape id (Internal use)
  65553. */
  65554. this.idxInShape = 0;
  65555. /**
  65556. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  65557. */
  65558. this._stillInvisible = false;
  65559. /**
  65560. * @hidden Last computed particle rotation matrix
  65561. */
  65562. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  65563. /**
  65564. * Parent particle Id, if any.
  65565. * Default null.
  65566. */
  65567. this.parentId = null;
  65568. /**
  65569. * @hidden Internal global position in the SPS.
  65570. */
  65571. this._globalPosition = BABYLON.Vector3.Zero();
  65572. this.idx = particleIndex;
  65573. this._pos = positionIndex;
  65574. this._ind = indiceIndex;
  65575. this._model = model;
  65576. this.shapeId = shapeId;
  65577. this.idxInShape = idxInShape;
  65578. this._sps = sps;
  65579. if (modelBoundingInfo) {
  65580. this._modelBoundingInfo = modelBoundingInfo;
  65581. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  65582. }
  65583. }
  65584. Object.defineProperty(SolidParticle.prototype, "scale", {
  65585. /**
  65586. * Legacy support, changed scale to scaling
  65587. */
  65588. get: function () {
  65589. return this.scaling;
  65590. },
  65591. /**
  65592. * Legacy support, changed scale to scaling
  65593. */
  65594. set: function (scale) {
  65595. this.scaling = scale;
  65596. },
  65597. enumerable: true,
  65598. configurable: true
  65599. });
  65600. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  65601. /**
  65602. * Legacy support, changed quaternion to rotationQuaternion
  65603. */
  65604. get: function () {
  65605. return this.rotationQuaternion;
  65606. },
  65607. /**
  65608. * Legacy support, changed quaternion to rotationQuaternion
  65609. */
  65610. set: function (q) {
  65611. this.rotationQuaternion = q;
  65612. },
  65613. enumerable: true,
  65614. configurable: true
  65615. });
  65616. /**
  65617. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  65618. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  65619. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  65620. * @returns true if it intersects
  65621. */
  65622. SolidParticle.prototype.intersectsMesh = function (target) {
  65623. if (!this._boundingInfo || !target._boundingInfo) {
  65624. return false;
  65625. }
  65626. if (this._sps._bSphereOnly) {
  65627. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  65628. }
  65629. return this._boundingInfo.intersects(target._boundingInfo, false);
  65630. };
  65631. return SolidParticle;
  65632. }());
  65633. BABYLON.SolidParticle = SolidParticle;
  65634. /**
  65635. * Represents the shape of the model used by one particle of a solid particle system.
  65636. * SPS internal tool, don't use it manually.
  65637. */
  65638. var ModelShape = /** @class */ (function () {
  65639. /**
  65640. * 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.
  65641. * SPS internal tool, don't use it manually.
  65642. * @hidden
  65643. */
  65644. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  65645. /**
  65646. * length of the shape in the model indices array (internal use)
  65647. * @hidden
  65648. */
  65649. this._indicesLength = 0;
  65650. this.shapeID = id;
  65651. this._shape = shape;
  65652. this._indicesLength = indicesLength;
  65653. this._shapeUV = shapeUV;
  65654. this._positionFunction = posFunction;
  65655. this._vertexFunction = vtxFunction;
  65656. }
  65657. return ModelShape;
  65658. }());
  65659. BABYLON.ModelShape = ModelShape;
  65660. /**
  65661. * Represents a Depth Sorted Particle in the solid particle system.
  65662. */
  65663. var DepthSortedParticle = /** @class */ (function () {
  65664. function DepthSortedParticle() {
  65665. /**
  65666. * Index of the particle in the "indices" array
  65667. */
  65668. this.ind = 0;
  65669. /**
  65670. * Length of the particle shape in the "indices" array
  65671. */
  65672. this.indicesLength = 0;
  65673. /**
  65674. * Squared distance from the particle to the camera
  65675. */
  65676. this.sqDistance = 0.0;
  65677. }
  65678. return DepthSortedParticle;
  65679. }());
  65680. BABYLON.DepthSortedParticle = DepthSortedParticle;
  65681. })(BABYLON || (BABYLON = {}));
  65682. //# sourceMappingURL=babylon.solidParticle.js.map
  65683. var BABYLON;
  65684. (function (BABYLON) {
  65685. /**
  65686. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  65687. *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.
  65688. * The SPS is also a particle system. It provides some methods to manage the particles.
  65689. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  65690. *
  65691. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  65692. */
  65693. var SolidParticleSystem = /** @class */ (function () {
  65694. /**
  65695. * Creates a SPS (Solid Particle System) object.
  65696. * @param name (String) is the SPS name, this will be the underlying mesh name.
  65697. * @param scene (Scene) is the scene in which the SPS is added.
  65698. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  65699. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  65700. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  65701. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  65702. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  65703. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  65704. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  65705. */
  65706. function SolidParticleSystem(name, scene, options) {
  65707. /**
  65708. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  65709. * Example : var p = SPS.particles[i];
  65710. */
  65711. this.particles = new Array();
  65712. /**
  65713. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  65714. */
  65715. this.nbParticles = 0;
  65716. /**
  65717. * If the particles must ever face the camera (default false). Useful for planar particles.
  65718. */
  65719. this.billboard = false;
  65720. /**
  65721. * Recompute normals when adding a shape
  65722. */
  65723. this.recomputeNormals = true;
  65724. /**
  65725. * This a counter ofr your own usage. It's not set by any SPS functions.
  65726. */
  65727. this.counter = 0;
  65728. /**
  65729. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  65730. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  65731. */
  65732. this.vars = {};
  65733. /**
  65734. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  65735. * @hidden
  65736. */
  65737. this._bSphereOnly = false;
  65738. /**
  65739. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  65740. * @hidden
  65741. */
  65742. this._bSphereRadiusFactor = 1.0;
  65743. this._positions = new Array();
  65744. this._indices = new Array();
  65745. this._normals = new Array();
  65746. this._colors = new Array();
  65747. this._uvs = new Array();
  65748. this._index = 0; // indices index
  65749. this._updatable = true;
  65750. this._pickable = false;
  65751. this._isVisibilityBoxLocked = false;
  65752. this._alwaysVisible = false;
  65753. this._depthSort = false;
  65754. this._shapeCounter = 0;
  65755. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  65756. this._color = new BABYLON.Color4(0, 0, 0, 0);
  65757. this._computeParticleColor = true;
  65758. this._computeParticleTexture = true;
  65759. this._computeParticleRotation = true;
  65760. this._computeParticleVertex = false;
  65761. this._computeBoundingBox = false;
  65762. this._depthSortParticles = true;
  65763. this._cam_axisZ = BABYLON.Vector3.Zero();
  65764. this._cam_axisY = BABYLON.Vector3.Zero();
  65765. this._cam_axisX = BABYLON.Vector3.Zero();
  65766. this._axisZ = BABYLON.Axis.Z;
  65767. this._camDir = BABYLON.Vector3.Zero();
  65768. this._camInvertedPosition = BABYLON.Vector3.Zero();
  65769. this._rotMatrix = new BABYLON.Matrix();
  65770. this._invertMatrix = new BABYLON.Matrix();
  65771. this._rotated = BABYLON.Vector3.Zero();
  65772. this._quaternion = new BABYLON.Quaternion();
  65773. this._vertex = BABYLON.Vector3.Zero();
  65774. this._normal = BABYLON.Vector3.Zero();
  65775. this._yaw = 0.0;
  65776. this._pitch = 0.0;
  65777. this._roll = 0.0;
  65778. this._halfroll = 0.0;
  65779. this._halfpitch = 0.0;
  65780. this._halfyaw = 0.0;
  65781. this._sinRoll = 0.0;
  65782. this._cosRoll = 0.0;
  65783. this._sinPitch = 0.0;
  65784. this._cosPitch = 0.0;
  65785. this._sinYaw = 0.0;
  65786. this._cosYaw = 0.0;
  65787. this._mustUnrotateFixedNormals = false;
  65788. this._minimum = BABYLON.Vector3.Zero();
  65789. this._maximum = BABYLON.Vector3.Zero();
  65790. this._minBbox = BABYLON.Vector3.Zero();
  65791. this._maxBbox = BABYLON.Vector3.Zero();
  65792. this._particlesIntersect = false;
  65793. this._depthSortFunction = function (p1, p2) {
  65794. return (p2.sqDistance - p1.sqDistance);
  65795. };
  65796. this._needs32Bits = false;
  65797. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  65798. this._scaledPivot = BABYLON.Vector3.Zero();
  65799. this._particleHasParent = false;
  65800. this.name = name;
  65801. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65802. this._camera = scene.activeCamera;
  65803. this._pickable = options ? options.isPickable : false;
  65804. this._depthSort = options ? options.enableDepthSort : false;
  65805. this._particlesIntersect = options ? options.particleIntersection : false;
  65806. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  65807. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  65808. if (options && options.updatable !== undefined) {
  65809. this._updatable = options.updatable;
  65810. }
  65811. else {
  65812. this._updatable = true;
  65813. }
  65814. if (this._pickable) {
  65815. this.pickedParticles = [];
  65816. }
  65817. if (this._depthSort) {
  65818. this.depthSortedParticles = [];
  65819. }
  65820. }
  65821. /**
  65822. * Builds the SPS underlying mesh. Returns a standard Mesh.
  65823. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  65824. * @returns the created mesh
  65825. */
  65826. SolidParticleSystem.prototype.buildMesh = function () {
  65827. if (this.nbParticles === 0) {
  65828. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  65829. this.addShape(triangle, 1);
  65830. triangle.dispose();
  65831. }
  65832. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  65833. this._positions32 = new Float32Array(this._positions);
  65834. this._uvs32 = new Float32Array(this._uvs);
  65835. this._colors32 = new Float32Array(this._colors);
  65836. if (this.recomputeNormals) {
  65837. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  65838. }
  65839. this._normals32 = new Float32Array(this._normals);
  65840. this._fixedNormal32 = new Float32Array(this._normals);
  65841. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  65842. this._unrotateFixedNormals();
  65843. }
  65844. var vertexData = new BABYLON.VertexData();
  65845. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  65846. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  65847. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  65848. if (this._uvs32.length > 0) {
  65849. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  65850. }
  65851. if (this._colors32.length > 0) {
  65852. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  65853. }
  65854. var mesh = new BABYLON.Mesh(this.name, this._scene);
  65855. vertexData.applyToMesh(mesh, this._updatable);
  65856. this.mesh = mesh;
  65857. this.mesh.isPickable = this._pickable;
  65858. // free memory
  65859. if (!this._depthSort) {
  65860. this._indices = null;
  65861. }
  65862. this._positions = null;
  65863. this._normals = null;
  65864. this._uvs = null;
  65865. this._colors = null;
  65866. if (!this._updatable) {
  65867. this.particles.length = 0;
  65868. }
  65869. return mesh;
  65870. };
  65871. /**
  65872. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  65873. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  65874. * Thus the particles generated from `digest()` have their property `position` set yet.
  65875. * @param mesh ( Mesh ) is the mesh to be digested
  65876. * @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
  65877. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  65878. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  65879. * @returns the current SPS
  65880. */
  65881. SolidParticleSystem.prototype.digest = function (mesh, options) {
  65882. var size = (options && options.facetNb) || 1;
  65883. var number = (options && options.number) || 0;
  65884. var delta = (options && options.delta) || 0;
  65885. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65886. var meshInd = mesh.getIndices();
  65887. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65888. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65889. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65890. var f = 0; // facet counter
  65891. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  65892. // compute size from number
  65893. if (number) {
  65894. number = (number > totalFacets) ? totalFacets : number;
  65895. size = Math.round(totalFacets / number);
  65896. delta = 0;
  65897. }
  65898. else {
  65899. size = (size > totalFacets) ? totalFacets : size;
  65900. }
  65901. var facetPos = []; // submesh positions
  65902. var facetInd = []; // submesh indices
  65903. var facetUV = []; // submesh UV
  65904. var facetCol = []; // submesh colors
  65905. var barycenter = BABYLON.Vector3.Zero();
  65906. var sizeO = size;
  65907. while (f < totalFacets) {
  65908. size = sizeO + Math.floor((1 + delta) * Math.random());
  65909. if (f > totalFacets - size) {
  65910. size = totalFacets - f;
  65911. }
  65912. // reset temp arrays
  65913. facetPos.length = 0;
  65914. facetInd.length = 0;
  65915. facetUV.length = 0;
  65916. facetCol.length = 0;
  65917. // iterate over "size" facets
  65918. var fi = 0;
  65919. for (var j = f * 3; j < (f + size) * 3; j++) {
  65920. facetInd.push(fi);
  65921. var i = meshInd[j];
  65922. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  65923. if (meshUV) {
  65924. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  65925. }
  65926. if (meshCol) {
  65927. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  65928. }
  65929. fi++;
  65930. }
  65931. // create a model shape for each single particle
  65932. var idx = this.nbParticles;
  65933. var shape = this._posToShape(facetPos);
  65934. var shapeUV = this._uvsToShapeUV(facetUV);
  65935. // compute the barycenter of the shape
  65936. var v;
  65937. for (v = 0; v < shape.length; v++) {
  65938. barycenter.addInPlace(shape[v]);
  65939. }
  65940. barycenter.scaleInPlace(1 / shape.length);
  65941. // shift the shape from its barycenter to the origin
  65942. for (v = 0; v < shape.length; v++) {
  65943. shape[v].subtractInPlace(barycenter);
  65944. }
  65945. var bInfo;
  65946. if (this._particlesIntersect) {
  65947. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  65948. }
  65949. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  65950. // add the particle in the SPS
  65951. var currentPos = this._positions.length;
  65952. var currentInd = this._indices.length;
  65953. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  65954. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  65955. // initialize the particle position
  65956. this.particles[this.nbParticles].position.addInPlace(barycenter);
  65957. this._index += shape.length;
  65958. idx++;
  65959. this.nbParticles++;
  65960. this._shapeCounter++;
  65961. f += size;
  65962. }
  65963. return this;
  65964. };
  65965. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  65966. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  65967. var index = 0;
  65968. var idx = 0;
  65969. for (var p = 0; p < this.particles.length; p++) {
  65970. this._particle = this.particles[p];
  65971. this._shape = this._particle._model._shape;
  65972. if (this._particle.rotationQuaternion) {
  65973. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  65974. }
  65975. else {
  65976. this._yaw = this._particle.rotation.y;
  65977. this._pitch = this._particle.rotation.x;
  65978. this._roll = this._particle.rotation.z;
  65979. this._quaternionRotationYPR();
  65980. }
  65981. this._quaternionToRotationMatrix();
  65982. this._rotMatrix.invertToRef(this._invertMatrix);
  65983. for (var pt = 0; pt < this._shape.length; pt++) {
  65984. idx = index + pt * 3;
  65985. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  65986. this._fixedNormal32[idx] = this._normal.x;
  65987. this._fixedNormal32[idx + 1] = this._normal.y;
  65988. this._fixedNormal32[idx + 2] = this._normal.z;
  65989. }
  65990. index = idx + 3;
  65991. }
  65992. };
  65993. //reset copy
  65994. SolidParticleSystem.prototype._resetCopy = function () {
  65995. this._copy.position.x = 0;
  65996. this._copy.position.y = 0;
  65997. this._copy.position.z = 0;
  65998. this._copy.rotation.x = 0;
  65999. this._copy.rotation.y = 0;
  66000. this._copy.rotation.z = 0;
  66001. this._copy.rotationQuaternion = null;
  66002. this._copy.scaling.x = 1.0;
  66003. this._copy.scaling.y = 1.0;
  66004. this._copy.scaling.z = 1.0;
  66005. this._copy.uvs.x = 0;
  66006. this._copy.uvs.y = 0;
  66007. this._copy.uvs.z = 1.0;
  66008. this._copy.uvs.w = 1.0;
  66009. this._copy.color = null;
  66010. this._copy.translateFromPivot = false;
  66011. };
  66012. // _meshBuilder : inserts the shape model in the global SPS mesh
  66013. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  66014. var i;
  66015. var u = 0;
  66016. var c = 0;
  66017. var n = 0;
  66018. this._resetCopy();
  66019. if (options && options.positionFunction) { // call to custom positionFunction
  66020. options.positionFunction(this._copy, idx, idxInShape);
  66021. this._mustUnrotateFixedNormals = true;
  66022. }
  66023. if (this._copy.rotationQuaternion) {
  66024. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  66025. }
  66026. else {
  66027. this._yaw = this._copy.rotation.y;
  66028. this._pitch = this._copy.rotation.x;
  66029. this._roll = this._copy.rotation.z;
  66030. this._quaternionRotationYPR();
  66031. }
  66032. this._quaternionToRotationMatrix();
  66033. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  66034. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  66035. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  66036. if (this._copy.translateFromPivot) {
  66037. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  66038. }
  66039. else {
  66040. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  66041. }
  66042. for (i = 0; i < shape.length; i++) {
  66043. this._vertex.x = shape[i].x;
  66044. this._vertex.y = shape[i].y;
  66045. this._vertex.z = shape[i].z;
  66046. if (options && options.vertexFunction) {
  66047. options.vertexFunction(this._copy, this._vertex, i);
  66048. }
  66049. this._vertex.x *= this._copy.scaling.x;
  66050. this._vertex.y *= this._copy.scaling.y;
  66051. this._vertex.z *= this._copy.scaling.z;
  66052. this._vertex.x -= this._scaledPivot.x;
  66053. this._vertex.y -= this._scaledPivot.y;
  66054. this._vertex.z -= this._scaledPivot.z;
  66055. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  66056. this._rotated.addInPlace(this._pivotBackTranslation);
  66057. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  66058. if (meshUV) {
  66059. 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);
  66060. u += 2;
  66061. }
  66062. if (this._copy.color) {
  66063. this._color = this._copy.color;
  66064. }
  66065. else if (meshCol && meshCol[c] !== undefined) {
  66066. this._color.r = meshCol[c];
  66067. this._color.g = meshCol[c + 1];
  66068. this._color.b = meshCol[c + 2];
  66069. this._color.a = meshCol[c + 3];
  66070. }
  66071. else {
  66072. this._color.r = 1.0;
  66073. this._color.g = 1.0;
  66074. this._color.b = 1.0;
  66075. this._color.a = 1.0;
  66076. }
  66077. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  66078. c += 4;
  66079. if (!this.recomputeNormals && meshNor) {
  66080. this._normal.x = meshNor[n];
  66081. this._normal.y = meshNor[n + 1];
  66082. this._normal.z = meshNor[n + 2];
  66083. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  66084. normals.push(this._normal.x, this._normal.y, this._normal.z);
  66085. n += 3;
  66086. }
  66087. }
  66088. for (i = 0; i < meshInd.length; i++) {
  66089. var current_ind = p + meshInd[i];
  66090. indices.push(current_ind);
  66091. if (current_ind > 65535) {
  66092. this._needs32Bits = true;
  66093. }
  66094. }
  66095. if (this._pickable) {
  66096. var nbfaces = meshInd.length / 3;
  66097. for (i = 0; i < nbfaces; i++) {
  66098. this.pickedParticles.push({ idx: idx, faceId: i });
  66099. }
  66100. }
  66101. if (this._depthSort) {
  66102. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  66103. }
  66104. return this._copy;
  66105. };
  66106. // returns a shape array from positions array
  66107. SolidParticleSystem.prototype._posToShape = function (positions) {
  66108. var shape = [];
  66109. for (var i = 0; i < positions.length; i += 3) {
  66110. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  66111. }
  66112. return shape;
  66113. };
  66114. // returns a shapeUV array from a Vector4 uvs
  66115. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  66116. var shapeUV = [];
  66117. if (uvs) {
  66118. for (var i = 0; i < uvs.length; i++)
  66119. shapeUV.push(uvs[i]);
  66120. }
  66121. return shapeUV;
  66122. };
  66123. // adds a new particle object in the particles array
  66124. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  66125. if (bInfo === void 0) { bInfo = null; }
  66126. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  66127. this.particles.push(sp);
  66128. return sp;
  66129. };
  66130. /**
  66131. * Adds some particles to the SPS from the model shape. Returns the shape id.
  66132. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  66133. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  66134. * @param nb (positive integer) the number of particles to be created from this model
  66135. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  66136. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  66137. * @returns the number of shapes in the system
  66138. */
  66139. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  66140. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66141. var meshInd = mesh.getIndices();
  66142. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66143. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66144. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66145. var bbInfo;
  66146. if (this._particlesIntersect) {
  66147. bbInfo = mesh.getBoundingInfo();
  66148. }
  66149. var shape = this._posToShape(meshPos);
  66150. var shapeUV = this._uvsToShapeUV(meshUV);
  66151. var posfunc = options ? options.positionFunction : null;
  66152. var vtxfunc = options ? options.vertexFunction : null;
  66153. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  66154. // particles
  66155. var sp;
  66156. var currentCopy;
  66157. var idx = this.nbParticles;
  66158. for (var i = 0; i < nb; i++) {
  66159. var currentPos = this._positions.length;
  66160. var currentInd = this._indices.length;
  66161. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  66162. if (this._updatable) {
  66163. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  66164. sp.position.copyFrom(currentCopy.position);
  66165. sp.rotation.copyFrom(currentCopy.rotation);
  66166. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  66167. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  66168. }
  66169. if (currentCopy.color && sp.color) {
  66170. sp.color.copyFrom(currentCopy.color);
  66171. }
  66172. sp.scaling.copyFrom(currentCopy.scaling);
  66173. sp.uvs.copyFrom(currentCopy.uvs);
  66174. }
  66175. this._index += shape.length;
  66176. idx++;
  66177. }
  66178. this.nbParticles += nb;
  66179. this._shapeCounter++;
  66180. return this._shapeCounter - 1;
  66181. };
  66182. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  66183. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  66184. this._resetCopy();
  66185. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  66186. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  66187. }
  66188. if (this._copy.rotationQuaternion) {
  66189. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  66190. }
  66191. else {
  66192. this._yaw = this._copy.rotation.y;
  66193. this._pitch = this._copy.rotation.x;
  66194. this._roll = this._copy.rotation.z;
  66195. this._quaternionRotationYPR();
  66196. }
  66197. this._quaternionToRotationMatrix();
  66198. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  66199. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  66200. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  66201. if (this._copy.translateFromPivot) {
  66202. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  66203. }
  66204. else {
  66205. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  66206. }
  66207. this._shape = particle._model._shape;
  66208. for (var pt = 0; pt < this._shape.length; pt++) {
  66209. this._vertex.x = this._shape[pt].x;
  66210. this._vertex.y = this._shape[pt].y;
  66211. this._vertex.z = this._shape[pt].z;
  66212. if (particle._model._vertexFunction) {
  66213. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  66214. }
  66215. this._vertex.x *= this._copy.scaling.x;
  66216. this._vertex.y *= this._copy.scaling.y;
  66217. this._vertex.z *= this._copy.scaling.z;
  66218. this._vertex.x -= this._scaledPivot.x;
  66219. this._vertex.y -= this._scaledPivot.y;
  66220. this._vertex.z -= this._scaledPivot.z;
  66221. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  66222. this._rotated.addInPlace(this._pivotBackTranslation);
  66223. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  66224. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  66225. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  66226. }
  66227. particle.position.x = 0.0;
  66228. particle.position.y = 0.0;
  66229. particle.position.z = 0.0;
  66230. particle.rotation.x = 0.0;
  66231. particle.rotation.y = 0.0;
  66232. particle.rotation.z = 0.0;
  66233. particle.rotationQuaternion = null;
  66234. particle.scaling.x = 1.0;
  66235. particle.scaling.y = 1.0;
  66236. particle.scaling.z = 1.0;
  66237. particle.uvs.x = 0.0;
  66238. particle.uvs.y = 0.0;
  66239. particle.uvs.z = 1.0;
  66240. particle.uvs.w = 1.0;
  66241. particle.pivot.x = 0.0;
  66242. particle.pivot.y = 0.0;
  66243. particle.pivot.z = 0.0;
  66244. particle.translateFromPivot = false;
  66245. particle.parentId = null;
  66246. };
  66247. /**
  66248. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  66249. * @returns the SPS.
  66250. */
  66251. SolidParticleSystem.prototype.rebuildMesh = function () {
  66252. for (var p = 0; p < this.particles.length; p++) {
  66253. this._rebuildParticle(this.particles[p]);
  66254. }
  66255. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  66256. return this;
  66257. };
  66258. /**
  66259. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  66260. * This method calls `updateParticle()` for each particle of the SPS.
  66261. * For an animated SPS, it is usually called within the render loop.
  66262. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  66263. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  66264. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  66265. * @returns the SPS.
  66266. */
  66267. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  66268. if (start === void 0) { start = 0; }
  66269. if (end === void 0) { end = this.nbParticles - 1; }
  66270. if (update === void 0) { update = true; }
  66271. if (!this._updatable) {
  66272. return this;
  66273. }
  66274. // custom beforeUpdate
  66275. this.beforeUpdateParticles(start, end, update);
  66276. this._cam_axisX.x = 1.0;
  66277. this._cam_axisX.y = 0.0;
  66278. this._cam_axisX.z = 0.0;
  66279. this._cam_axisY.x = 0.0;
  66280. this._cam_axisY.y = 1.0;
  66281. this._cam_axisY.z = 0.0;
  66282. this._cam_axisZ.x = 0.0;
  66283. this._cam_axisZ.y = 0.0;
  66284. this._cam_axisZ.z = 1.0;
  66285. // cases when the World Matrix is to be computed first
  66286. if (this.billboard || this._depthSort) {
  66287. this.mesh.computeWorldMatrix(true);
  66288. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  66289. }
  66290. // if the particles will always face the camera
  66291. if (this.billboard) {
  66292. // compute the camera position and un-rotate it by the current mesh rotation
  66293. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  66294. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  66295. this._cam_axisZ.normalize();
  66296. // same for camera up vector extracted from the cam view matrix
  66297. var view = this._camera.getViewMatrix(true);
  66298. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  66299. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  66300. this._cam_axisY.normalize();
  66301. this._cam_axisX.normalize();
  66302. }
  66303. // if depthSort, compute the camera global position in the mesh local system
  66304. if (this._depthSort) {
  66305. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  66306. }
  66307. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  66308. var idx = 0; // current position index in the global array positions32
  66309. var index = 0; // position start index in the global array positions32 of the current particle
  66310. var colidx = 0; // current color index in the global array colors32
  66311. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  66312. var uvidx = 0; // current uv index in the global array uvs32
  66313. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  66314. var pt = 0; // current index in the particle model shape
  66315. if (this.mesh.isFacetDataEnabled) {
  66316. this._computeBoundingBox = true;
  66317. }
  66318. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  66319. if (this._computeBoundingBox) {
  66320. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  66321. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  66322. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  66323. }
  66324. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  66325. if (this.mesh._boundingInfo) {
  66326. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  66327. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  66328. }
  66329. }
  66330. }
  66331. // particle loop
  66332. index = this.particles[start]._pos;
  66333. var vpos = (index / 3) | 0;
  66334. colorIndex = vpos * 4;
  66335. uvIndex = vpos * 2;
  66336. for (var p = start; p <= end; p++) {
  66337. this._particle = this.particles[p];
  66338. this._shape = this._particle._model._shape;
  66339. this._shapeUV = this._particle._model._shapeUV;
  66340. // call to custom user function to update the particle properties
  66341. this.updateParticle(this._particle);
  66342. // camera-particle distance for depth sorting
  66343. if (this._depthSort && this._depthSortParticles) {
  66344. var dsp = this.depthSortedParticles[p];
  66345. dsp.ind = this._particle._ind;
  66346. dsp.indicesLength = this._particle._model._indicesLength;
  66347. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  66348. }
  66349. // skip the computations for inactive or already invisible particles
  66350. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  66351. // increment indexes for the next particle
  66352. pt = this._shape.length;
  66353. index += pt * 3;
  66354. colorIndex += pt * 4;
  66355. uvIndex += pt * 2;
  66356. continue;
  66357. }
  66358. if (this._particle.isVisible) {
  66359. this._particle._stillInvisible = false; // un-mark permanent invisibility
  66360. this._particleHasParent = (this._particle.parentId !== null);
  66361. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  66362. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  66363. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  66364. // particle rotation matrix
  66365. if (this.billboard) {
  66366. this._particle.rotation.x = 0.0;
  66367. this._particle.rotation.y = 0.0;
  66368. }
  66369. if (this._computeParticleRotation || this.billboard) {
  66370. if (this._particle.rotationQuaternion) {
  66371. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  66372. }
  66373. else {
  66374. this._yaw = this._particle.rotation.y;
  66375. this._pitch = this._particle.rotation.x;
  66376. this._roll = this._particle.rotation.z;
  66377. this._quaternionRotationYPR();
  66378. }
  66379. this._quaternionToRotationMatrix();
  66380. }
  66381. if (this._particleHasParent) {
  66382. this._parent = this.particles[this._particle.parentId];
  66383. 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];
  66384. 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];
  66385. 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];
  66386. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  66387. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  66388. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  66389. if (this._computeParticleRotation || this.billboard) {
  66390. 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];
  66391. 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];
  66392. 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];
  66393. 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];
  66394. 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];
  66395. 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];
  66396. 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];
  66397. 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];
  66398. 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];
  66399. }
  66400. }
  66401. else {
  66402. this._particle._globalPosition.x = this._particle.position.x;
  66403. this._particle._globalPosition.y = this._particle.position.y;
  66404. this._particle._globalPosition.z = this._particle.position.z;
  66405. if (this._computeParticleRotation || this.billboard) {
  66406. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  66407. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  66408. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  66409. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  66410. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  66411. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  66412. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  66413. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  66414. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  66415. }
  66416. }
  66417. if (this._particle.translateFromPivot) {
  66418. this._pivotBackTranslation.x = 0.0;
  66419. this._pivotBackTranslation.y = 0.0;
  66420. this._pivotBackTranslation.z = 0.0;
  66421. }
  66422. else {
  66423. this._pivotBackTranslation.x = this._scaledPivot.x;
  66424. this._pivotBackTranslation.y = this._scaledPivot.y;
  66425. this._pivotBackTranslation.z = this._scaledPivot.z;
  66426. }
  66427. // particle vertex loop
  66428. for (pt = 0; pt < this._shape.length; pt++) {
  66429. idx = index + pt * 3;
  66430. colidx = colorIndex + pt * 4;
  66431. uvidx = uvIndex + pt * 2;
  66432. this._vertex.x = this._shape[pt].x;
  66433. this._vertex.y = this._shape[pt].y;
  66434. this._vertex.z = this._shape[pt].z;
  66435. if (this._computeParticleVertex) {
  66436. this.updateParticleVertex(this._particle, this._vertex, pt);
  66437. }
  66438. // positions
  66439. this._vertex.x *= this._particle.scaling.x;
  66440. this._vertex.y *= this._particle.scaling.y;
  66441. this._vertex.z *= this._particle.scaling.z;
  66442. this._vertex.x -= this._scaledPivot.x;
  66443. this._vertex.y -= this._scaledPivot.y;
  66444. this._vertex.z -= this._scaledPivot.z;
  66445. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  66446. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  66447. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  66448. this._rotated.x += this._pivotBackTranslation.x;
  66449. this._rotated.y += this._pivotBackTranslation.y;
  66450. this._rotated.z += this._pivotBackTranslation.z;
  66451. 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;
  66452. 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;
  66453. 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;
  66454. if (this._computeBoundingBox) {
  66455. if (this._positions32[idx] < this._minimum.x) {
  66456. this._minimum.x = this._positions32[idx];
  66457. }
  66458. if (this._positions32[idx] > this._maximum.x) {
  66459. this._maximum.x = this._positions32[idx];
  66460. }
  66461. if (this._positions32[idx + 1] < this._minimum.y) {
  66462. this._minimum.y = this._positions32[idx + 1];
  66463. }
  66464. if (this._positions32[idx + 1] > this._maximum.y) {
  66465. this._maximum.y = this._positions32[idx + 1];
  66466. }
  66467. if (this._positions32[idx + 2] < this._minimum.z) {
  66468. this._minimum.z = this._positions32[idx + 2];
  66469. }
  66470. if (this._positions32[idx + 2] > this._maximum.z) {
  66471. this._maximum.z = this._positions32[idx + 2];
  66472. }
  66473. }
  66474. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  66475. if (!this._computeParticleVertex) {
  66476. this._normal.x = this._fixedNormal32[idx];
  66477. this._normal.y = this._fixedNormal32[idx + 1];
  66478. this._normal.z = this._fixedNormal32[idx + 2];
  66479. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  66480. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  66481. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  66482. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  66483. 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;
  66484. 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;
  66485. }
  66486. if (this._computeParticleColor && this._particle.color) {
  66487. this._colors32[colidx] = this._particle.color.r;
  66488. this._colors32[colidx + 1] = this._particle.color.g;
  66489. this._colors32[colidx + 2] = this._particle.color.b;
  66490. this._colors32[colidx + 3] = this._particle.color.a;
  66491. }
  66492. if (this._computeParticleTexture) {
  66493. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  66494. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  66495. }
  66496. }
  66497. }
  66498. // particle just set invisible : scaled to zero and positioned at the origin
  66499. else {
  66500. this._particle._stillInvisible = true; // mark the particle as invisible
  66501. for (pt = 0; pt < this._shape.length; pt++) {
  66502. idx = index + pt * 3;
  66503. colidx = colorIndex + pt * 4;
  66504. uvidx = uvIndex + pt * 2;
  66505. this._positions32[idx] = 0.0;
  66506. this._positions32[idx + 1] = 0.0;
  66507. this._positions32[idx + 2] = 0.0;
  66508. this._normals32[idx] = 0.0;
  66509. this._normals32[idx + 1] = 0.0;
  66510. this._normals32[idx + 2] = 0.0;
  66511. if (this._computeParticleColor && this._particle.color) {
  66512. this._colors32[colidx] = this._particle.color.r;
  66513. this._colors32[colidx + 1] = this._particle.color.g;
  66514. this._colors32[colidx + 2] = this._particle.color.b;
  66515. this._colors32[colidx + 3] = this._particle.color.a;
  66516. }
  66517. if (this._computeParticleTexture) {
  66518. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  66519. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  66520. }
  66521. }
  66522. }
  66523. // if the particle intersections must be computed : update the bbInfo
  66524. if (this._particlesIntersect) {
  66525. var bInfo = this._particle._boundingInfo;
  66526. var bBox = bInfo.boundingBox;
  66527. var bSphere = bInfo.boundingSphere;
  66528. if (!this._bSphereOnly) {
  66529. // place, scale and rotate the particle bbox within the SPS local system, then update it
  66530. for (var b = 0; b < bBox.vectors.length; b++) {
  66531. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  66532. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  66533. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  66534. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  66535. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  66536. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  66537. 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;
  66538. 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;
  66539. 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;
  66540. }
  66541. bBox._update(this.mesh._worldMatrix);
  66542. }
  66543. // place and scale the particle bouding sphere in the SPS local system, then update it
  66544. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  66545. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  66546. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  66547. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  66548. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  66549. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  66550. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  66551. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  66552. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  66553. 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));
  66554. bSphere._update(this.mesh._worldMatrix);
  66555. }
  66556. // increment indexes for the next particle
  66557. index = idx + 3;
  66558. colorIndex = colidx + 4;
  66559. uvIndex = uvidx + 2;
  66560. }
  66561. // if the VBO must be updated
  66562. if (update) {
  66563. if (this._computeParticleColor) {
  66564. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  66565. }
  66566. if (this._computeParticleTexture) {
  66567. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  66568. }
  66569. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  66570. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  66571. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  66572. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  66573. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  66574. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  66575. for (var i = 0; i < this._normals32.length; i++) {
  66576. this._fixedNormal32[i] = this._normals32[i];
  66577. }
  66578. }
  66579. if (!this.mesh.areNormalsFrozen) {
  66580. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  66581. }
  66582. }
  66583. if (this._depthSort && this._depthSortParticles) {
  66584. this.depthSortedParticles.sort(this._depthSortFunction);
  66585. var dspl = this.depthSortedParticles.length;
  66586. var sorted = 0;
  66587. var lind = 0;
  66588. var sind = 0;
  66589. var sid = 0;
  66590. for (sorted = 0; sorted < dspl; sorted++) {
  66591. lind = this.depthSortedParticles[sorted].indicesLength;
  66592. sind = this.depthSortedParticles[sorted].ind;
  66593. for (var i = 0; i < lind; i++) {
  66594. this._indices32[sid] = this._indices[sind + i];
  66595. sid++;
  66596. }
  66597. }
  66598. this.mesh.updateIndices(this._indices32);
  66599. }
  66600. }
  66601. if (this._computeBoundingBox) {
  66602. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  66603. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  66604. }
  66605. this.afterUpdateParticles(start, end, update);
  66606. return this;
  66607. };
  66608. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  66609. this._halfroll = this._roll * 0.5;
  66610. this._halfpitch = this._pitch * 0.5;
  66611. this._halfyaw = this._yaw * 0.5;
  66612. this._sinRoll = Math.sin(this._halfroll);
  66613. this._cosRoll = Math.cos(this._halfroll);
  66614. this._sinPitch = Math.sin(this._halfpitch);
  66615. this._cosPitch = Math.cos(this._halfpitch);
  66616. this._sinYaw = Math.sin(this._halfyaw);
  66617. this._cosYaw = Math.cos(this._halfyaw);
  66618. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  66619. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  66620. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  66621. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  66622. };
  66623. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  66624. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  66625. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  66626. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  66627. this._rotMatrix.m[3] = 0;
  66628. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  66629. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  66630. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  66631. this._rotMatrix.m[7] = 0;
  66632. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  66633. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  66634. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  66635. this._rotMatrix.m[11] = 0;
  66636. this._rotMatrix.m[12] = 0;
  66637. this._rotMatrix.m[13] = 0;
  66638. this._rotMatrix.m[14] = 0;
  66639. this._rotMatrix.m[15] = 1.0;
  66640. };
  66641. /**
  66642. * Disposes the SPS.
  66643. */
  66644. SolidParticleSystem.prototype.dispose = function () {
  66645. this.mesh.dispose();
  66646. this.vars = null;
  66647. // drop references to internal big arrays for the GC
  66648. this._positions = null;
  66649. this._indices = null;
  66650. this._normals = null;
  66651. this._uvs = null;
  66652. this._colors = null;
  66653. this._indices32 = null;
  66654. this._positions32 = null;
  66655. this._normals32 = null;
  66656. this._fixedNormal32 = null;
  66657. this._uvs32 = null;
  66658. this._colors32 = null;
  66659. this.pickedParticles = null;
  66660. };
  66661. /**
  66662. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  66663. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66664. * @returns the SPS.
  66665. */
  66666. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  66667. if (!this._isVisibilityBoxLocked) {
  66668. this.mesh.refreshBoundingInfo();
  66669. }
  66670. return this;
  66671. };
  66672. /**
  66673. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  66674. * @param size the size (float) of the visibility box
  66675. * note : this doesn't lock the SPS mesh bounding box.
  66676. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66677. */
  66678. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  66679. var vis = size / 2;
  66680. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  66681. };
  66682. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  66683. /**
  66684. * Gets whether the SPS as always visible or not
  66685. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66686. */
  66687. get: function () {
  66688. return this._alwaysVisible;
  66689. },
  66690. /**
  66691. * Sets the SPS as always visible or not
  66692. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66693. */
  66694. set: function (val) {
  66695. this._alwaysVisible = val;
  66696. this.mesh.alwaysSelectAsActiveMesh = val;
  66697. },
  66698. enumerable: true,
  66699. configurable: true
  66700. });
  66701. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  66702. /**
  66703. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  66704. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66705. */
  66706. get: function () {
  66707. return this._isVisibilityBoxLocked;
  66708. },
  66709. /**
  66710. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  66711. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  66712. */
  66713. set: function (val) {
  66714. this._isVisibilityBoxLocked = val;
  66715. var boundingInfo = this.mesh.getBoundingInfo();
  66716. boundingInfo.isLocked = val;
  66717. },
  66718. enumerable: true,
  66719. configurable: true
  66720. });
  66721. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  66722. /**
  66723. * Gets if `setParticles()` computes the particle rotations or not.
  66724. * Default value : true. The SPS is faster when it's set to false.
  66725. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  66726. */
  66727. get: function () {
  66728. return this._computeParticleRotation;
  66729. },
  66730. /**
  66731. * Tells to `setParticles()` to compute the particle rotations or not.
  66732. * Default value : true. The SPS is faster when it's set to false.
  66733. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  66734. */
  66735. set: function (val) {
  66736. this._computeParticleRotation = val;
  66737. },
  66738. enumerable: true,
  66739. configurable: true
  66740. });
  66741. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  66742. /**
  66743. * Gets if `setParticles()` computes the particle colors or not.
  66744. * Default value : true. The SPS is faster when it's set to false.
  66745. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  66746. */
  66747. get: function () {
  66748. return this._computeParticleColor;
  66749. },
  66750. /**
  66751. * Tells to `setParticles()` to compute the particle colors or not.
  66752. * Default value : true. The SPS is faster when it's set to false.
  66753. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  66754. */
  66755. set: function (val) {
  66756. this._computeParticleColor = val;
  66757. },
  66758. enumerable: true,
  66759. configurable: true
  66760. });
  66761. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  66762. /**
  66763. * Gets if `setParticles()` computes the particle textures or not.
  66764. * Default value : true. The SPS is faster when it's set to false.
  66765. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  66766. */
  66767. get: function () {
  66768. return this._computeParticleTexture;
  66769. },
  66770. set: function (val) {
  66771. this._computeParticleTexture = val;
  66772. },
  66773. enumerable: true,
  66774. configurable: true
  66775. });
  66776. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  66777. /**
  66778. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  66779. * Default value : false. The SPS is faster when it's set to false.
  66780. * Note : the particle custom vertex positions aren't stored values.
  66781. */
  66782. get: function () {
  66783. return this._computeParticleVertex;
  66784. },
  66785. /**
  66786. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  66787. * Default value : false. The SPS is faster when it's set to false.
  66788. * Note : the particle custom vertex positions aren't stored values.
  66789. */
  66790. set: function (val) {
  66791. this._computeParticleVertex = val;
  66792. },
  66793. enumerable: true,
  66794. configurable: true
  66795. });
  66796. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  66797. /**
  66798. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  66799. */
  66800. get: function () {
  66801. return this._computeBoundingBox;
  66802. },
  66803. /**
  66804. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  66805. */
  66806. set: function (val) {
  66807. this._computeBoundingBox = val;
  66808. },
  66809. enumerable: true,
  66810. configurable: true
  66811. });
  66812. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  66813. /**
  66814. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  66815. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  66816. * Default : `true`
  66817. */
  66818. get: function () {
  66819. return this._depthSortParticles;
  66820. },
  66821. /**
  66822. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  66823. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  66824. * Default : `true`
  66825. */
  66826. set: function (val) {
  66827. this._depthSortParticles = val;
  66828. },
  66829. enumerable: true,
  66830. configurable: true
  66831. });
  66832. // =======================================================================
  66833. // Particle behavior logic
  66834. // these following methods may be overwritten by the user to fit his needs
  66835. /**
  66836. * This function does nothing. It may be overwritten to set all the particle first values.
  66837. * The SPS doesn't call this function, you may have to call it by your own.
  66838. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  66839. */
  66840. SolidParticleSystem.prototype.initParticles = function () {
  66841. };
  66842. /**
  66843. * This function does nothing. It may be overwritten to recycle a particle.
  66844. * The SPS doesn't call this function, you may have to call it by your own.
  66845. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  66846. * @param particle The particle to recycle
  66847. * @returns the recycled particle
  66848. */
  66849. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  66850. return particle;
  66851. };
  66852. /**
  66853. * Updates a particle : this function should be overwritten by the user.
  66854. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  66855. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  66856. * @example : just set a particle position or velocity and recycle conditions
  66857. * @param particle The particle to update
  66858. * @returns the updated particle
  66859. */
  66860. SolidParticleSystem.prototype.updateParticle = function (particle) {
  66861. return particle;
  66862. };
  66863. /**
  66864. * Updates a vertex of a particle : it can be overwritten by the user.
  66865. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  66866. * @param particle the current particle
  66867. * @param vertex the current index of the current particle
  66868. * @param pt the index of the current vertex in the particle shape
  66869. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  66870. * @example : just set a vertex particle position
  66871. * @returns the updated vertex
  66872. */
  66873. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  66874. return vertex;
  66875. };
  66876. /**
  66877. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  66878. * This does nothing and may be overwritten by the user.
  66879. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66880. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66881. * @param update the boolean update value actually passed to setParticles()
  66882. */
  66883. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  66884. };
  66885. /**
  66886. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  66887. * This will be passed three parameters.
  66888. * This does nothing and may be overwritten by the user.
  66889. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66890. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  66891. * @param update the boolean update value actually passed to setParticles()
  66892. */
  66893. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  66894. };
  66895. return SolidParticleSystem;
  66896. }());
  66897. BABYLON.SolidParticleSystem = SolidParticleSystem;
  66898. })(BABYLON || (BABYLON = {}));
  66899. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  66900. var BABYLON;
  66901. (function (BABYLON) {
  66902. /**
  66903. * Class containing static functions to help procedurally build meshes
  66904. */
  66905. var MeshBuilder = /** @class */ (function () {
  66906. function MeshBuilder() {
  66907. }
  66908. MeshBuilder.updateSideOrientation = function (orientation) {
  66909. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  66910. return BABYLON.Mesh.DOUBLESIDE;
  66911. }
  66912. if (orientation === undefined || orientation === null) {
  66913. return BABYLON.Mesh.FRONTSIDE;
  66914. }
  66915. return orientation;
  66916. };
  66917. /**
  66918. * Creates a box mesh
  66919. * * The parameter `size` sets the size (float) of each box side (default 1)
  66920. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  66921. * * 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)
  66922. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  66923. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66924. * * 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
  66925. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66926. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  66927. * @param name defines the name of the mesh
  66928. * @param options defines the options used to create the mesh
  66929. * @param scene defines the hosting scene
  66930. * @returns the box mesh
  66931. */
  66932. MeshBuilder.CreateBox = function (name, options, scene) {
  66933. if (scene === void 0) { scene = null; }
  66934. var box = new BABYLON.Mesh(name, scene);
  66935. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66936. box._originalBuilderSideOrientation = options.sideOrientation;
  66937. var vertexData = BABYLON.VertexData.CreateBox(options);
  66938. vertexData.applyToMesh(box, options.updatable);
  66939. return box;
  66940. };
  66941. /**
  66942. * Creates a sphere mesh
  66943. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  66944. * * 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 of `diameter`)
  66945. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  66946. * * 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
  66947. * * 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)
  66948. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66949. * * 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
  66950. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66951. * @param name defines the name of the mesh
  66952. * @param options defines the options used to create the mesh
  66953. * @param scene defines the hosting scene
  66954. * @returns the sphere mesh
  66955. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  66956. */
  66957. MeshBuilder.CreateSphere = function (name, options, scene) {
  66958. var sphere = new BABYLON.Mesh(name, scene);
  66959. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66960. sphere._originalBuilderSideOrientation = options.sideOrientation;
  66961. var vertexData = BABYLON.VertexData.CreateSphere(options);
  66962. vertexData.applyToMesh(sphere, options.updatable);
  66963. return sphere;
  66964. };
  66965. /**
  66966. * Creates a plane polygonal mesh. By default, this is a disc
  66967. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  66968. * * 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
  66969. * * 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
  66970. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66971. * * 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
  66972. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66973. * @param name defines the name of the mesh
  66974. * @param options defines the options used to create the mesh
  66975. * @param scene defines the hosting scene
  66976. * @returns the plane polygonal mesh
  66977. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  66978. */
  66979. MeshBuilder.CreateDisc = function (name, options, scene) {
  66980. if (scene === void 0) { scene = null; }
  66981. var disc = new BABYLON.Mesh(name, scene);
  66982. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66983. disc._originalBuilderSideOrientation = options.sideOrientation;
  66984. var vertexData = BABYLON.VertexData.CreateDisc(options);
  66985. vertexData.applyToMesh(disc, options.updatable);
  66986. return disc;
  66987. };
  66988. /**
  66989. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  66990. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  66991. * * 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 of `radius`)
  66992. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  66993. * * 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
  66994. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66995. * * 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
  66996. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66997. * @param name defines the name of the mesh
  66998. * @param options defines the options used to create the mesh
  66999. * @param scene defines the hosting scene
  67000. * @returns the icosahedron mesh
  67001. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  67002. */
  67003. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  67004. var sphere = new BABYLON.Mesh(name, scene);
  67005. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67006. sphere._originalBuilderSideOrientation = options.sideOrientation;
  67007. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  67008. vertexData.applyToMesh(sphere, options.updatable);
  67009. return sphere;
  67010. };
  67011. ;
  67012. /**
  67013. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  67014. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  67015. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  67016. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  67017. * * 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
  67018. * * 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
  67019. * * 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
  67020. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67021. * * 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
  67022. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67023. * * 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
  67024. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  67025. * * 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
  67026. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  67027. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67028. * @param name defines the name of the mesh
  67029. * @param options defines the options used to create the mesh
  67030. * @param scene defines the hosting scene
  67031. * @returns the ribbon mesh
  67032. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  67033. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67034. */
  67035. MeshBuilder.CreateRibbon = function (name, options, scene) {
  67036. if (scene === void 0) { scene = null; }
  67037. var pathArray = options.pathArray;
  67038. var closeArray = options.closeArray;
  67039. var closePath = options.closePath;
  67040. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67041. var instance = options.instance;
  67042. var updatable = options.updatable;
  67043. if (instance) { // existing ribbon instance update
  67044. // positionFunction : ribbon case
  67045. // only pathArray and sideOrientation parameters are taken into account for positions update
  67046. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  67047. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  67048. var positionFunction = function (positions) {
  67049. var minlg = pathArray[0].length;
  67050. var mesh = instance;
  67051. var i = 0;
  67052. var ns = (mesh._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  67053. for (var si = 1; si <= ns; si++) {
  67054. for (var p = 0; p < pathArray.length; p++) {
  67055. var path = pathArray[p];
  67056. var l = path.length;
  67057. minlg = (minlg < l) ? minlg : l;
  67058. var j = 0;
  67059. while (j < minlg) {
  67060. positions[i] = path[j].x;
  67061. positions[i + 1] = path[j].y;
  67062. positions[i + 2] = path[j].z;
  67063. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  67064. BABYLON.Tmp.Vector3[0].x = path[j].x;
  67065. }
  67066. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  67067. BABYLON.Tmp.Vector3[1].x = path[j].x;
  67068. }
  67069. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  67070. BABYLON.Tmp.Vector3[0].y = path[j].y;
  67071. }
  67072. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  67073. BABYLON.Tmp.Vector3[1].y = path[j].y;
  67074. }
  67075. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  67076. BABYLON.Tmp.Vector3[0].z = path[j].z;
  67077. }
  67078. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  67079. BABYLON.Tmp.Vector3[1].z = path[j].z;
  67080. }
  67081. j++;
  67082. i += 3;
  67083. }
  67084. if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {
  67085. positions[i] = path[0].x;
  67086. positions[i + 1] = path[0].y;
  67087. positions[i + 2] = path[0].z;
  67088. i += 3;
  67089. }
  67090. }
  67091. }
  67092. };
  67093. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67094. positionFunction(positions);
  67095. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[2], BABYLON.Tmp.Vector3[3]);
  67096. instance._boundingInfo.update(instance._worldMatrix);
  67097. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  67098. if (options.colors) {
  67099. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67100. for (var c = 0; c < options.colors.length; c++) {
  67101. colors[c * 4] = options.colors[c].r;
  67102. colors[c * 4 + 1] = options.colors[c].g;
  67103. colors[c * 4 + 2] = options.colors[c].b;
  67104. colors[c * 4 + 3] = options.colors[c].a;
  67105. }
  67106. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  67107. }
  67108. if (options.uvs) {
  67109. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67110. for (var i = 0; i < options.uvs.length; i++) {
  67111. uvs[i * 2] = options.uvs[i].x;
  67112. uvs[i * 2 + 1] = options.uvs[i].y;
  67113. }
  67114. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  67115. }
  67116. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  67117. var indices = instance.getIndices();
  67118. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67119. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  67120. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  67121. if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
  67122. var indexFirst = 0;
  67123. var indexLast = 0;
  67124. for (var p = 0; p < pathArray.length; p++) {
  67125. indexFirst = instance._creationDataStorage.idx[p] * 3;
  67126. if (p + 1 < pathArray.length) {
  67127. indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
  67128. }
  67129. else {
  67130. indexLast = normals.length - 3;
  67131. }
  67132. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  67133. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  67134. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  67135. normals[indexLast] = normals[indexFirst];
  67136. normals[indexLast + 1] = normals[indexFirst + 1];
  67137. normals[indexLast + 2] = normals[indexFirst + 2];
  67138. }
  67139. }
  67140. if (!(instance.areNormalsFrozen)) {
  67141. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  67142. }
  67143. }
  67144. return instance;
  67145. }
  67146. else { // new ribbon creation
  67147. var ribbon = new BABYLON.Mesh(name, scene);
  67148. ribbon._originalBuilderSideOrientation = sideOrientation;
  67149. ribbon._creationDataStorage = new BABYLON._CreationDataStorage();
  67150. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  67151. if (closePath) {
  67152. ribbon._creationDataStorage.idx = vertexData._idx;
  67153. }
  67154. ribbon._creationDataStorage.closePath = closePath;
  67155. ribbon._creationDataStorage.closeArray = closeArray;
  67156. vertexData.applyToMesh(ribbon, updatable);
  67157. return ribbon;
  67158. }
  67159. };
  67160. /**
  67161. * Creates a cylinder or a cone mesh
  67162. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  67163. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  67164. * * 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.
  67165. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  67166. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  67167. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  67168. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  67169. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  67170. * * 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).
  67171. * * 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
  67172. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  67173. * * 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
  67174. * * 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.
  67175. * * If `enclose` is false, a ring surface is one element.
  67176. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  67177. * * 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
  67178. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67179. * * 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
  67180. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67181. * @param name defines the name of the mesh
  67182. * @param options defines the options used to create the mesh
  67183. * @param scene defines the hosting scene
  67184. * @returns the cylinder mesh
  67185. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  67186. */
  67187. MeshBuilder.CreateCylinder = function (name, options, scene) {
  67188. var cylinder = new BABYLON.Mesh(name, scene);
  67189. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67190. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  67191. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  67192. vertexData.applyToMesh(cylinder, options.updatable);
  67193. return cylinder;
  67194. };
  67195. /**
  67196. * Creates a torus mesh
  67197. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  67198. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  67199. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  67200. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67201. * * 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
  67202. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67203. * @param name defines the name of the mesh
  67204. * @param options defines the options used to create the mesh
  67205. * @param scene defines the hosting scene
  67206. * @returns the torus mesh
  67207. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  67208. */
  67209. MeshBuilder.CreateTorus = function (name, options, scene) {
  67210. var torus = new BABYLON.Mesh(name, scene);
  67211. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67212. torus._originalBuilderSideOrientation = options.sideOrientation;
  67213. var vertexData = BABYLON.VertexData.CreateTorus(options);
  67214. vertexData.applyToMesh(torus, options.updatable);
  67215. return torus;
  67216. };
  67217. /**
  67218. * Creates a torus knot mesh
  67219. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  67220. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  67221. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  67222. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  67223. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67224. * * 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
  67225. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67226. * @param name defines the name of the mesh
  67227. * @param options defines the options used to create the mesh
  67228. * @param scene defines the hosting scene
  67229. * @returns the torus knot mesh
  67230. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  67231. */
  67232. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  67233. var torusKnot = new BABYLON.Mesh(name, scene);
  67234. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67235. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  67236. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  67237. vertexData.applyToMesh(torusKnot, options.updatable);
  67238. return torusKnot;
  67239. };
  67240. /**
  67241. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  67242. * * 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
  67243. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  67244. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  67245. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  67246. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  67247. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  67248. * * 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
  67249. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  67250. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67251. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  67252. * @param name defines the name of the new line system
  67253. * @param options defines the options used to create the line system
  67254. * @param scene defines the hosting scene
  67255. * @returns a new line system mesh
  67256. */
  67257. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  67258. var instance = options.instance;
  67259. var lines = options.lines;
  67260. var colors = options.colors;
  67261. if (instance) { // lines update
  67262. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67263. var vertexColor;
  67264. var lineColors;
  67265. if (colors) {
  67266. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67267. }
  67268. var i = 0;
  67269. var c = 0;
  67270. for (var l = 0; l < lines.length; l++) {
  67271. var points = lines[l];
  67272. for (var p = 0; p < points.length; p++) {
  67273. positions[i] = points[p].x;
  67274. positions[i + 1] = points[p].y;
  67275. positions[i + 2] = points[p].z;
  67276. if (colors && vertexColor) {
  67277. lineColors = colors[l];
  67278. vertexColor[c] = lineColors[p].r;
  67279. vertexColor[c + 1] = lineColors[p].g;
  67280. vertexColor[c + 2] = lineColors[p].b;
  67281. vertexColor[c + 3] = lineColors[p].a;
  67282. c += 4;
  67283. }
  67284. i += 3;
  67285. }
  67286. }
  67287. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  67288. if (colors && vertexColor) {
  67289. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  67290. }
  67291. return instance;
  67292. }
  67293. // line system creation
  67294. var useVertexColor = (colors) ? true : false;
  67295. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  67296. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  67297. vertexData.applyToMesh(lineSystem, options.updatable);
  67298. return lineSystem;
  67299. };
  67300. /**
  67301. * Creates a line mesh
  67302. * 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
  67303. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  67304. * * The parameter `points` is an array successive Vector3
  67305. * * 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
  67306. * * The optional parameter `colors` is an array of successive Color4, one per line point
  67307. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  67308. * * When updating an instance, remember that only point positions can change, not the number of points
  67309. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67310. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  67311. * @param name defines the name of the new line system
  67312. * @param options defines the options used to create the line system
  67313. * @param scene defines the hosting scene
  67314. * @returns a new line mesh
  67315. */
  67316. MeshBuilder.CreateLines = function (name, options, scene) {
  67317. if (scene === void 0) { scene = null; }
  67318. var colors = (options.colors) ? [options.colors] : null;
  67319. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  67320. return lines;
  67321. };
  67322. /**
  67323. * Creates a dashed line mesh
  67324. * * 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
  67325. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  67326. * * The parameter `points` is an array successive Vector3
  67327. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  67328. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  67329. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  67330. * * 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
  67331. * * When updating an instance, remember that only point positions can change, not the number of points
  67332. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67333. * @param name defines the name of the mesh
  67334. * @param options defines the options used to create the mesh
  67335. * @param scene defines the hosting scene
  67336. * @returns the dashed line mesh
  67337. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  67338. */
  67339. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  67340. if (scene === void 0) { scene = null; }
  67341. var points = options.points;
  67342. var instance = options.instance;
  67343. var gapSize = options.gapSize || 1;
  67344. var dashSize = options.dashSize || 3;
  67345. if (instance) { // dashed lines update
  67346. var positionFunction = function (positions) {
  67347. var curvect = BABYLON.Vector3.Zero();
  67348. var nbSeg = positions.length / 6;
  67349. var lg = 0;
  67350. var nb = 0;
  67351. var shft = 0;
  67352. var dashshft = 0;
  67353. var curshft = 0;
  67354. var p = 0;
  67355. var i = 0;
  67356. var j = 0;
  67357. for (i = 0; i < points.length - 1; i++) {
  67358. points[i + 1].subtractToRef(points[i], curvect);
  67359. lg += curvect.length();
  67360. }
  67361. shft = lg / nbSeg;
  67362. var dashSize = instance._creationDataStorage.dashSize;
  67363. var gapSize = instance._creationDataStorage.gapSize;
  67364. dashshft = dashSize * shft / (dashSize + gapSize);
  67365. for (i = 0; i < points.length - 1; i++) {
  67366. points[i + 1].subtractToRef(points[i], curvect);
  67367. nb = Math.floor(curvect.length() / shft);
  67368. curvect.normalize();
  67369. j = 0;
  67370. while (j < nb && p < positions.length) {
  67371. curshft = shft * j;
  67372. positions[p] = points[i].x + curshft * curvect.x;
  67373. positions[p + 1] = points[i].y + curshft * curvect.y;
  67374. positions[p + 2] = points[i].z + curshft * curvect.z;
  67375. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  67376. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  67377. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  67378. p += 6;
  67379. j++;
  67380. }
  67381. }
  67382. while (p < positions.length) {
  67383. positions[p] = points[i].x;
  67384. positions[p + 1] = points[i].y;
  67385. positions[p + 2] = points[i].z;
  67386. p += 3;
  67387. }
  67388. };
  67389. instance.updateMeshPositions(positionFunction, false);
  67390. return instance;
  67391. }
  67392. // dashed lines creation
  67393. var dashedLines = new BABYLON.LinesMesh(name, scene);
  67394. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  67395. vertexData.applyToMesh(dashedLines, options.updatable);
  67396. dashedLines._creationDataStorage = new BABYLON._CreationDataStorage();
  67397. dashedLines._creationDataStorage.dashSize = dashSize;
  67398. dashedLines._creationDataStorage.gapSize = gapSize;
  67399. return dashedLines;
  67400. };
  67401. /**
  67402. * 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.
  67403. * * 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.
  67404. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  67405. * * 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.
  67406. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  67407. * * 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
  67408. * * 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
  67409. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  67410. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67411. * * 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
  67412. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  67413. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67414. * @param name defines the name of the mesh
  67415. * @param options defines the options used to create the mesh
  67416. * @param scene defines the hosting scene
  67417. * @returns the extruded shape mesh
  67418. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67419. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  67420. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  67421. */
  67422. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  67423. if (scene === void 0) { scene = null; }
  67424. var path = options.path;
  67425. var shape = options.shape;
  67426. var scale = options.scale || 1;
  67427. var rotation = options.rotation || 0;
  67428. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  67429. var updatable = options.updatable;
  67430. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67431. var instance = options.instance || null;
  67432. var invertUV = options.invertUV || false;
  67433. 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);
  67434. };
  67435. /**
  67436. * Creates an custom extruded shape mesh.
  67437. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  67438. * * 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.
  67439. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  67440. * * 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
  67441. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  67442. * * 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
  67443. * * It must returns a float value that will be the scale value applied to the shape on each path point
  67444. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  67445. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  67446. * * 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
  67447. * * 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
  67448. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  67449. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67450. * * 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
  67451. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67452. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67453. * @param name defines the name of the mesh
  67454. * @param options defines the options used to create the mesh
  67455. * @param scene defines the hosting scene
  67456. * @returns the custom extruded shape mesh
  67457. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  67458. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67459. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  67460. */
  67461. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  67462. var path = options.path;
  67463. var shape = options.shape;
  67464. var scaleFunction = options.scaleFunction || (function () { return 1; });
  67465. var rotationFunction = options.rotationFunction || (function () { return 0; });
  67466. var ribbonCloseArray = options.ribbonCloseArray || false;
  67467. var ribbonClosePath = options.ribbonClosePath || false;
  67468. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  67469. var updatable = options.updatable;
  67470. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67471. var instance = options.instance;
  67472. var invertUV = options.invertUV || false;
  67473. 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);
  67474. };
  67475. /**
  67476. * Creates lathe mesh.
  67477. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  67478. * * 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
  67479. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  67480. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  67481. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  67482. * * 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
  67483. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  67484. * * 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
  67485. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67486. * * 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
  67487. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67488. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67489. * @param name defines the name of the mesh
  67490. * @param options defines the options used to create the mesh
  67491. * @param scene defines the hosting scene
  67492. * @returns the lathe mesh
  67493. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  67494. */
  67495. MeshBuilder.CreateLathe = function (name, options, scene) {
  67496. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  67497. var closed = (options.closed === undefined) ? true : options.closed;
  67498. var shape = options.shape;
  67499. var radius = options.radius || 1;
  67500. var tessellation = options.tessellation || 64;
  67501. var clip = options.clip || 0;
  67502. var updatable = options.updatable;
  67503. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67504. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  67505. var pi2 = Math.PI * 2;
  67506. var paths = new Array();
  67507. var invertUV = options.invertUV || false;
  67508. var i = 0;
  67509. var p = 0;
  67510. var step = pi2 / tessellation * arc;
  67511. var rotated;
  67512. var path = new Array();
  67513. for (i = 0; i <= tessellation - clip; i++) {
  67514. var path = [];
  67515. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  67516. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  67517. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  67518. }
  67519. for (p = 0; p < shape.length; p++) {
  67520. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  67521. path.push(rotated);
  67522. }
  67523. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  67524. 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));
  67525. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  67526. }
  67527. paths.push(path);
  67528. }
  67529. // lathe ribbon
  67530. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  67531. return lathe;
  67532. };
  67533. /**
  67534. * Creates a plane mesh
  67535. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  67536. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  67537. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  67538. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67539. * * 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
  67540. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67541. * @param name defines the name of the mesh
  67542. * @param options defines the options used to create the mesh
  67543. * @param scene defines the hosting scene
  67544. * @returns the plane mesh
  67545. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  67546. */
  67547. MeshBuilder.CreatePlane = function (name, options, scene) {
  67548. var plane = new BABYLON.Mesh(name, scene);
  67549. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67550. plane._originalBuilderSideOrientation = options.sideOrientation;
  67551. var vertexData = BABYLON.VertexData.CreatePlane(options);
  67552. vertexData.applyToMesh(plane, options.updatable);
  67553. if (options.sourcePlane) {
  67554. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  67555. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  67556. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  67557. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  67558. plane.rotate(vectorProduct, product);
  67559. }
  67560. }
  67561. return plane;
  67562. };
  67563. /**
  67564. * Creates a ground mesh
  67565. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  67566. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  67567. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67568. * @param name defines the name of the mesh
  67569. * @param options defines the options used to create the mesh
  67570. * @param scene defines the hosting scene
  67571. * @returns the ground mesh
  67572. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  67573. */
  67574. MeshBuilder.CreateGround = function (name, options, scene) {
  67575. var ground = new BABYLON.GroundMesh(name, scene);
  67576. ground._setReady(false);
  67577. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  67578. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  67579. ground._width = options.width || 1;
  67580. ground._height = options.height || 1;
  67581. ground._maxX = ground._width / 2;
  67582. ground._maxZ = ground._height / 2;
  67583. ground._minX = -ground._maxX;
  67584. ground._minZ = -ground._maxZ;
  67585. var vertexData = BABYLON.VertexData.CreateGround(options);
  67586. vertexData.applyToMesh(ground, options.updatable);
  67587. ground._setReady(true);
  67588. return ground;
  67589. };
  67590. /**
  67591. * Creates a tiled ground mesh
  67592. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  67593. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  67594. * * 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
  67595. * * 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
  67596. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67597. * @param name defines the name of the mesh
  67598. * @param options defines the options used to create the mesh
  67599. * @param scene defines the hosting scene
  67600. * @returns the tiled ground mesh
  67601. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  67602. */
  67603. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  67604. var tiledGround = new BABYLON.Mesh(name, scene);
  67605. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  67606. vertexData.applyToMesh(tiledGround, options.updatable);
  67607. return tiledGround;
  67608. };
  67609. /**
  67610. * Creates a ground mesh from a height map
  67611. * * The parameter `url` sets the URL of the height map image resource.
  67612. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  67613. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  67614. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  67615. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  67616. * * 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.
  67617. * * 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).
  67618. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  67619. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67620. * @param name defines the name of the mesh
  67621. * @param url defines the url to the height map
  67622. * @param options defines the options used to create the mesh
  67623. * @param scene defines the hosting scene
  67624. * @returns the ground mesh
  67625. * @see http://doc.babylonjs.com/babylon101/height_map
  67626. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  67627. */
  67628. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  67629. var width = options.width || 10.0;
  67630. var height = options.height || 10.0;
  67631. var subdivisions = options.subdivisions || 1 | 0;
  67632. var minHeight = options.minHeight || 0.0;
  67633. var maxHeight = options.maxHeight || 1.0;
  67634. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  67635. var alphaFilter = options.alphaFilter || 0.0;
  67636. var updatable = options.updatable;
  67637. var onReady = options.onReady;
  67638. var ground = new BABYLON.GroundMesh(name, scene);
  67639. ground._subdivisionsX = subdivisions;
  67640. ground._subdivisionsY = subdivisions;
  67641. ground._width = width;
  67642. ground._height = height;
  67643. ground._maxX = ground._width / 2.0;
  67644. ground._maxZ = ground._height / 2.0;
  67645. ground._minX = -ground._maxX;
  67646. ground._minZ = -ground._maxZ;
  67647. ground._setReady(false);
  67648. var onload = function (img) {
  67649. // Getting height map data
  67650. var canvas = document.createElement("canvas");
  67651. var context = canvas.getContext("2d");
  67652. if (!context) {
  67653. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  67654. }
  67655. if (scene.isDisposed) {
  67656. return;
  67657. }
  67658. var bufferWidth = img.width;
  67659. var bufferHeight = img.height;
  67660. canvas.width = bufferWidth;
  67661. canvas.height = bufferHeight;
  67662. context.drawImage(img, 0, 0);
  67663. // Create VertexData from map data
  67664. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  67665. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  67666. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  67667. width: width, height: height,
  67668. subdivisions: subdivisions,
  67669. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  67670. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  67671. alphaFilter: alphaFilter
  67672. });
  67673. vertexData.applyToMesh(ground, updatable);
  67674. //execute ready callback, if set
  67675. if (onReady) {
  67676. onReady(ground);
  67677. }
  67678. ground._setReady(true);
  67679. };
  67680. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  67681. return ground;
  67682. };
  67683. /**
  67684. * Creates a polygon mesh
  67685. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  67686. * * 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
  67687. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67688. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67689. * * 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)
  67690. * * Remember you can only change the shape positions, not their number when updating a polygon
  67691. * @param name defines the name of the mesh
  67692. * @param options defines the options used to create the mesh
  67693. * @param scene defines the hosting scene
  67694. * @returns the polygon mesh
  67695. */
  67696. MeshBuilder.CreatePolygon = function (name, options, scene) {
  67697. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67698. var shape = options.shape;
  67699. var holes = options.holes || [];
  67700. var depth = options.depth || 0;
  67701. var contours = [];
  67702. var hole = [];
  67703. for (var i = 0; i < shape.length; i++) {
  67704. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  67705. }
  67706. var epsilon = 0.00000001;
  67707. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  67708. contours.pop();
  67709. }
  67710. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  67711. for (var hNb = 0; hNb < holes.length; hNb++) {
  67712. hole = [];
  67713. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  67714. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  67715. }
  67716. polygonTriangulation.addHole(hole);
  67717. }
  67718. var polygon = polygonTriangulation.build(options.updatable, depth);
  67719. polygon._originalBuilderSideOrientation = options.sideOrientation;
  67720. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  67721. vertexData.applyToMesh(polygon, options.updatable);
  67722. return polygon;
  67723. };
  67724. ;
  67725. /**
  67726. * Creates an extruded polygon mesh, with depth in the Y direction.
  67727. * * 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)
  67728. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  67729. * @param name defines the name of the mesh
  67730. * @param options defines the options used to create the mesh
  67731. * @param scene defines the hosting scene
  67732. * @returns the polygon mesh
  67733. */
  67734. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  67735. return MeshBuilder.CreatePolygon(name, options, scene);
  67736. };
  67737. ;
  67738. /**
  67739. * Creates a tube mesh.
  67740. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  67741. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  67742. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  67743. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  67744. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  67745. * * 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)
  67746. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  67747. * * 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
  67748. * * 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
  67749. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67750. * * 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
  67751. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67752. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67753. * @param name defines the name of the mesh
  67754. * @param options defines the options used to create the mesh
  67755. * @param scene defines the hosting scene
  67756. * @returns the tube mesh
  67757. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67758. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  67759. */
  67760. MeshBuilder.CreateTube = function (name, options, scene) {
  67761. var path = options.path;
  67762. var instance = options.instance;
  67763. var radius = 1.0;
  67764. if (options.radius !== undefined) {
  67765. radius = options.radius;
  67766. }
  67767. else if (instance) {
  67768. radius = instance._creationDataStorage.radius;
  67769. }
  67770. var tessellation = options.tessellation || 64 | 0;
  67771. var radiusFunction = options.radiusFunction || null;
  67772. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  67773. var invertUV = options.invertUV || false;
  67774. var updatable = options.updatable;
  67775. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67776. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  67777. // tube geometry
  67778. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  67779. var tangents = path3D.getTangents();
  67780. var normals = path3D.getNormals();
  67781. var distances = path3D.getDistances();
  67782. var pi2 = Math.PI * 2;
  67783. var step = pi2 / tessellation * arc;
  67784. var returnRadius = function () { return radius; };
  67785. var radiusFunctionFinal = radiusFunction || returnRadius;
  67786. var circlePath;
  67787. var rad;
  67788. var normal;
  67789. var rotated;
  67790. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  67791. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  67792. for (var i = 0; i < path.length; i++) {
  67793. rad = radiusFunctionFinal(i, distances[i]); // current radius
  67794. circlePath = Array(); // current circle array
  67795. normal = normals[i]; // current normal
  67796. for (var t = 0; t < tessellation; t++) {
  67797. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  67798. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  67799. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  67800. rotated.scaleInPlace(rad).addInPlace(path[i]);
  67801. circlePath[t] = rotated;
  67802. }
  67803. circlePaths[index] = circlePath;
  67804. index++;
  67805. }
  67806. // cap
  67807. var capPath = function (nbPoints, pathIndex) {
  67808. var pointCap = Array();
  67809. for (var i = 0; i < nbPoints; i++) {
  67810. pointCap.push(path[pathIndex]);
  67811. }
  67812. return pointCap;
  67813. };
  67814. switch (cap) {
  67815. case BABYLON.Mesh.NO_CAP:
  67816. break;
  67817. case BABYLON.Mesh.CAP_START:
  67818. circlePaths[0] = capPath(tessellation, 0);
  67819. circlePaths[1] = circlePaths[2].slice(0);
  67820. break;
  67821. case BABYLON.Mesh.CAP_END:
  67822. circlePaths[index] = circlePaths[index - 1].slice(0);
  67823. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  67824. break;
  67825. case BABYLON.Mesh.CAP_ALL:
  67826. circlePaths[0] = capPath(tessellation, 0);
  67827. circlePaths[1] = circlePaths[2].slice(0);
  67828. circlePaths[index] = circlePaths[index - 1].slice(0);
  67829. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  67830. break;
  67831. default:
  67832. break;
  67833. }
  67834. return circlePaths;
  67835. };
  67836. var path3D;
  67837. var pathArray;
  67838. if (instance) { // tube update
  67839. var storage = instance._creationDataStorage;
  67840. var arc = options.arc || storage.arc;
  67841. path3D = storage.path3D.update(path);
  67842. pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);
  67843. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  67844. // Update mode, no need to recreate the storage.
  67845. storage.path3D = path3D;
  67846. storage.pathArray = pathArray;
  67847. storage.arc = arc;
  67848. storage.radius = radius;
  67849. return instance;
  67850. }
  67851. // tube creation
  67852. path3D = new BABYLON.Path3D(path);
  67853. var newPathArray = new Array();
  67854. cap = (cap < 0 || cap > 3) ? 0 : cap;
  67855. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  67856. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  67857. tube._creationDataStorage.pathArray = pathArray;
  67858. tube._creationDataStorage.path3D = path3D;
  67859. tube._creationDataStorage.tessellation = tessellation;
  67860. tube._creationDataStorage.cap = cap;
  67861. tube._creationDataStorage.arc = options.arc;
  67862. tube._creationDataStorage.radius = radius;
  67863. return tube;
  67864. };
  67865. /**
  67866. * Creates a polyhedron mesh
  67867. * * 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
  67868. * * The parameter `size` (positive float, default 1) sets the polygon size
  67869. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  67870. * * 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`
  67871. * * 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
  67872. * * 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)`)
  67873. * * 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
  67874. * * 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
  67875. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67876. * * 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
  67877. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67878. * @param name defines the name of the mesh
  67879. * @param options defines the options used to create the mesh
  67880. * @param scene defines the hosting scene
  67881. * @returns the polyhedron mesh
  67882. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  67883. */
  67884. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  67885. var polyhedron = new BABYLON.Mesh(name, scene);
  67886. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67887. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  67888. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  67889. vertexData.applyToMesh(polyhedron, options.updatable);
  67890. return polyhedron;
  67891. };
  67892. /**
  67893. * Creates a decal mesh.
  67894. * 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
  67895. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  67896. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  67897. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  67898. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  67899. * @param name defines the name of the mesh
  67900. * @param sourceMesh defines the mesh where the decal must be applied
  67901. * @param options defines the options used to create the mesh
  67902. * @param scene defines the hosting scene
  67903. * @returns the decal mesh
  67904. * @see http://doc.babylonjs.com/how_to/decals
  67905. */
  67906. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  67907. var indices = sourceMesh.getIndices();
  67908. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67909. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67910. var position = options.position || BABYLON.Vector3.Zero();
  67911. var normal = options.normal || BABYLON.Vector3.Up();
  67912. var size = options.size || BABYLON.Vector3.One();
  67913. var angle = options.angle || 0;
  67914. // Getting correct rotation
  67915. if (!normal) {
  67916. var target = new BABYLON.Vector3(0, 0, 1);
  67917. var camera = sourceMesh.getScene().activeCamera;
  67918. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  67919. normal = camera.globalPosition.subtract(cameraWorldTarget);
  67920. }
  67921. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  67922. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  67923. var pitch = Math.atan2(normal.y, len);
  67924. // Matrix
  67925. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  67926. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  67927. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  67928. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  67929. var vertexData = new BABYLON.VertexData();
  67930. vertexData.indices = [];
  67931. vertexData.positions = [];
  67932. vertexData.normals = [];
  67933. vertexData.uvs = [];
  67934. var currentVertexDataIndex = 0;
  67935. var extractDecalVector3 = function (indexId) {
  67936. var result = new BABYLON.PositionNormalVertex();
  67937. if (!indices || !positions || !normals) {
  67938. return result;
  67939. }
  67940. var vertexId = indices[indexId];
  67941. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  67942. // Send vector to decal local world
  67943. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  67944. // Get normal
  67945. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  67946. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  67947. return result;
  67948. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  67949. var clip = function (vertices, axis) {
  67950. if (vertices.length === 0) {
  67951. return vertices;
  67952. }
  67953. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  67954. var clipVertices = function (v0, v1) {
  67955. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  67956. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  67957. };
  67958. var result = new Array();
  67959. for (var index = 0; index < vertices.length; index += 3) {
  67960. var v1Out;
  67961. var v2Out;
  67962. var v3Out;
  67963. var total = 0;
  67964. var nV1 = null;
  67965. var nV2 = null;
  67966. var nV3 = null;
  67967. var nV4 = null;
  67968. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  67969. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  67970. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  67971. v1Out = d1 > 0;
  67972. v2Out = d2 > 0;
  67973. v3Out = d3 > 0;
  67974. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  67975. switch (total) {
  67976. case 0:
  67977. result.push(vertices[index]);
  67978. result.push(vertices[index + 1]);
  67979. result.push(vertices[index + 2]);
  67980. break;
  67981. case 1:
  67982. if (v1Out) {
  67983. nV1 = vertices[index + 1];
  67984. nV2 = vertices[index + 2];
  67985. nV3 = clipVertices(vertices[index], nV1);
  67986. nV4 = clipVertices(vertices[index], nV2);
  67987. }
  67988. if (v2Out) {
  67989. nV1 = vertices[index];
  67990. nV2 = vertices[index + 2];
  67991. nV3 = clipVertices(vertices[index + 1], nV1);
  67992. nV4 = clipVertices(vertices[index + 1], nV2);
  67993. result.push(nV3);
  67994. result.push(nV2.clone());
  67995. result.push(nV1.clone());
  67996. result.push(nV2.clone());
  67997. result.push(nV3.clone());
  67998. result.push(nV4);
  67999. break;
  68000. }
  68001. if (v3Out) {
  68002. nV1 = vertices[index];
  68003. nV2 = vertices[index + 1];
  68004. nV3 = clipVertices(vertices[index + 2], nV1);
  68005. nV4 = clipVertices(vertices[index + 2], nV2);
  68006. }
  68007. if (nV1 && nV2 && nV3 && nV4) {
  68008. result.push(nV1.clone());
  68009. result.push(nV2.clone());
  68010. result.push(nV3);
  68011. result.push(nV4);
  68012. result.push(nV3.clone());
  68013. result.push(nV2.clone());
  68014. }
  68015. break;
  68016. case 2:
  68017. if (!v1Out) {
  68018. nV1 = vertices[index].clone();
  68019. nV2 = clipVertices(nV1, vertices[index + 1]);
  68020. nV3 = clipVertices(nV1, vertices[index + 2]);
  68021. result.push(nV1);
  68022. result.push(nV2);
  68023. result.push(nV3);
  68024. }
  68025. if (!v2Out) {
  68026. nV1 = vertices[index + 1].clone();
  68027. nV2 = clipVertices(nV1, vertices[index + 2]);
  68028. nV3 = clipVertices(nV1, vertices[index]);
  68029. result.push(nV1);
  68030. result.push(nV2);
  68031. result.push(nV3);
  68032. }
  68033. if (!v3Out) {
  68034. nV1 = vertices[index + 2].clone();
  68035. nV2 = clipVertices(nV1, vertices[index]);
  68036. nV3 = clipVertices(nV1, vertices[index + 1]);
  68037. result.push(nV1);
  68038. result.push(nV2);
  68039. result.push(nV3);
  68040. }
  68041. break;
  68042. case 3:
  68043. break;
  68044. }
  68045. }
  68046. return result;
  68047. };
  68048. for (var index = 0; index < indices.length; index += 3) {
  68049. var faceVertices = new Array();
  68050. faceVertices.push(extractDecalVector3(index));
  68051. faceVertices.push(extractDecalVector3(index + 1));
  68052. faceVertices.push(extractDecalVector3(index + 2));
  68053. // Clip
  68054. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  68055. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  68056. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  68057. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  68058. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  68059. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  68060. if (faceVertices.length === 0) {
  68061. continue;
  68062. }
  68063. // Add UVs and get back to world
  68064. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  68065. var vertex = faceVertices[vIndex];
  68066. //TODO check for Int32Array | Uint32Array | Uint16Array
  68067. vertexData.indices.push(currentVertexDataIndex);
  68068. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  68069. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  68070. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  68071. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  68072. currentVertexDataIndex++;
  68073. }
  68074. }
  68075. // Return mesh
  68076. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  68077. vertexData.applyToMesh(decal);
  68078. decal.position = position.clone();
  68079. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  68080. return decal;
  68081. };
  68082. // Privates
  68083. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  68084. // extrusion geometry
  68085. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  68086. var tangents = path3D.getTangents();
  68087. var normals = path3D.getNormals();
  68088. var binormals = path3D.getBinormals();
  68089. var distances = path3D.getDistances();
  68090. var angle = 0;
  68091. var returnScale = function () { return scale !== null ? scale : 1; };
  68092. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  68093. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  68094. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  68095. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  68096. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  68097. for (var i = 0; i < curve.length; i++) {
  68098. var shapePath = new Array();
  68099. var angleStep = rotate(i, distances[i]);
  68100. var scaleRatio = scl(i, distances[i]);
  68101. for (var p = 0; p < shape.length; p++) {
  68102. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  68103. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  68104. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  68105. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  68106. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  68107. shapePath[p] = rotated;
  68108. }
  68109. shapePaths[index] = shapePath;
  68110. angle += angleStep;
  68111. index++;
  68112. }
  68113. // cap
  68114. var capPath = function (shapePath) {
  68115. var pointCap = Array();
  68116. var barycenter = BABYLON.Vector3.Zero();
  68117. var i;
  68118. for (i = 0; i < shapePath.length; i++) {
  68119. barycenter.addInPlace(shapePath[i]);
  68120. }
  68121. barycenter.scaleInPlace(1.0 / shapePath.length);
  68122. for (i = 0; i < shapePath.length; i++) {
  68123. pointCap.push(barycenter);
  68124. }
  68125. return pointCap;
  68126. };
  68127. switch (cap) {
  68128. case BABYLON.Mesh.NO_CAP:
  68129. break;
  68130. case BABYLON.Mesh.CAP_START:
  68131. shapePaths[0] = capPath(shapePaths[2]);
  68132. shapePaths[1] = shapePaths[2];
  68133. break;
  68134. case BABYLON.Mesh.CAP_END:
  68135. shapePaths[index] = shapePaths[index - 1];
  68136. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  68137. break;
  68138. case BABYLON.Mesh.CAP_ALL:
  68139. shapePaths[0] = capPath(shapePaths[2]);
  68140. shapePaths[1] = shapePaths[2];
  68141. shapePaths[index] = shapePaths[index - 1];
  68142. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  68143. break;
  68144. default:
  68145. break;
  68146. }
  68147. return shapePaths;
  68148. };
  68149. var path3D;
  68150. var pathArray;
  68151. if (instance) { // instance update
  68152. var storage = instance._creationDataStorage;
  68153. path3D = storage.path3D.update(curve);
  68154. pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom);
  68155. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  68156. return instance;
  68157. }
  68158. // extruded shape creation
  68159. path3D = new BABYLON.Path3D(curve);
  68160. var newShapePaths = new Array();
  68161. cap = (cap < 0 || cap > 3) ? 0 : cap;
  68162. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  68163. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  68164. extrudedGeneric._creationDataStorage.pathArray = pathArray;
  68165. extrudedGeneric._creationDataStorage.path3D = path3D;
  68166. extrudedGeneric._creationDataStorage.cap = cap;
  68167. return extrudedGeneric;
  68168. };
  68169. return MeshBuilder;
  68170. }());
  68171. BABYLON.MeshBuilder = MeshBuilder;
  68172. })(BABYLON || (BABYLON = {}));
  68173. //# sourceMappingURL=babylon.meshBuilder.js.map
  68174. var BABYLON;
  68175. (function (BABYLON) {
  68176. /**
  68177. * Draco compression (https://google.github.io/draco/)
  68178. *
  68179. * This class wraps the Draco module.
  68180. *
  68181. * **Encoder**
  68182. *
  68183. * The encoder is not currently implemented.
  68184. *
  68185. * **Decoder**
  68186. *
  68187. * By default, the configuration points to a copy of the Draco decoder files for glTF from the babylon.js preview cdn https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js.
  68188. *
  68189. * To update the configuration, use the following code:
  68190. * ```javascript
  68191. * BABYLON.DracoCompression.Configuration = {
  68192. * decoder: {
  68193. * wasmUrl: "<url to the WebAssembly library>",
  68194. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  68195. * fallbackUrl: "<url to the fallback JavaScript library>",
  68196. * }
  68197. * };
  68198. * ```
  68199. *
  68200. * 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.
  68201. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  68202. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  68203. *
  68204. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  68205. * ```javascript
  68206. * var dracoCompression = new BABYLON.DracoCompression();
  68207. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  68208. * [BABYLON.VertexBuffer.PositionKind]: 0
  68209. * });
  68210. * ```
  68211. *
  68212. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  68213. */
  68214. var DracoCompression = /** @class */ (function () {
  68215. /**
  68216. * Constructor
  68217. */
  68218. function DracoCompression() {
  68219. }
  68220. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  68221. /**
  68222. * Returns true if the decoder is available.
  68223. */
  68224. get: function () {
  68225. if (typeof DracoDecoderModule !== "undefined") {
  68226. return true;
  68227. }
  68228. var decoder = DracoCompression.Configuration.decoder;
  68229. if (decoder) {
  68230. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  68231. return true;
  68232. }
  68233. if (decoder.fallbackUrl) {
  68234. return true;
  68235. }
  68236. }
  68237. return false;
  68238. },
  68239. enumerable: true,
  68240. configurable: true
  68241. });
  68242. /**
  68243. * Stop all async operations and release resources.
  68244. */
  68245. DracoCompression.prototype.dispose = function () {
  68246. };
  68247. /**
  68248. * Decode Draco compressed mesh data to vertex data.
  68249. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  68250. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  68251. * @returns A promise that resolves with the decoded vertex data
  68252. */
  68253. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  68254. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  68255. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  68256. var module = wrappedModule.module;
  68257. var vertexData = new BABYLON.VertexData();
  68258. var buffer = new module.DecoderBuffer();
  68259. buffer.Init(dataView, dataView.byteLength);
  68260. var decoder = new module.Decoder();
  68261. var geometry;
  68262. var status;
  68263. try {
  68264. var type = decoder.GetEncodedGeometryType(buffer);
  68265. switch (type) {
  68266. case module.TRIANGULAR_MESH:
  68267. geometry = new module.Mesh();
  68268. status = decoder.DecodeBufferToMesh(buffer, geometry);
  68269. break;
  68270. case module.POINT_CLOUD:
  68271. geometry = new module.PointCloud();
  68272. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  68273. break;
  68274. default:
  68275. throw new Error("Invalid geometry type " + type);
  68276. }
  68277. if (!status.ok() || !geometry.ptr) {
  68278. throw new Error(status.error_msg());
  68279. }
  68280. var numPoints = geometry.num_points();
  68281. if (type === module.TRIANGULAR_MESH) {
  68282. var numFaces = geometry.num_faces();
  68283. var faceIndices = new module.DracoInt32Array();
  68284. try {
  68285. var indices = new Uint32Array(numFaces * 3);
  68286. for (var i = 0; i < numFaces; i++) {
  68287. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  68288. var offset = i * 3;
  68289. indices[offset + 0] = faceIndices.GetValue(0);
  68290. indices[offset + 1] = faceIndices.GetValue(1);
  68291. indices[offset + 2] = faceIndices.GetValue(2);
  68292. }
  68293. vertexData.indices = indices;
  68294. }
  68295. finally {
  68296. module.destroy(faceIndices);
  68297. }
  68298. }
  68299. for (var kind in attributes) {
  68300. var uniqueId = attributes[kind];
  68301. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  68302. var dracoData = new module.DracoFloat32Array();
  68303. try {
  68304. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  68305. var babylonData = new Float32Array(numPoints * attribute.num_components());
  68306. for (var i = 0; i < babylonData.length; i++) {
  68307. babylonData[i] = dracoData.GetValue(i);
  68308. }
  68309. vertexData.set(babylonData, kind);
  68310. }
  68311. finally {
  68312. module.destroy(dracoData);
  68313. }
  68314. }
  68315. }
  68316. finally {
  68317. if (geometry) {
  68318. module.destroy(geometry);
  68319. }
  68320. module.destroy(decoder);
  68321. module.destroy(buffer);
  68322. }
  68323. return vertexData;
  68324. });
  68325. };
  68326. DracoCompression._GetDecoderModule = function () {
  68327. if (!DracoCompression._DecoderModulePromise) {
  68328. var promise = null;
  68329. var config_1 = {};
  68330. if (typeof DracoDecoderModule !== "undefined") {
  68331. promise = Promise.resolve();
  68332. }
  68333. else {
  68334. var decoder = DracoCompression.Configuration.decoder;
  68335. if (decoder) {
  68336. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  68337. promise = Promise.all([
  68338. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  68339. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  68340. config_1.wasmBinary = data;
  68341. })
  68342. ]);
  68343. }
  68344. else if (decoder.fallbackUrl) {
  68345. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  68346. }
  68347. }
  68348. }
  68349. if (!promise) {
  68350. throw new Error("Draco decoder module is not available");
  68351. }
  68352. DracoCompression._DecoderModulePromise = promise.then(function () {
  68353. return new Promise(function (resolve) {
  68354. config_1.onModuleLoaded = function (decoderModule) {
  68355. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  68356. resolve({ module: decoderModule });
  68357. };
  68358. DracoDecoderModule(config_1);
  68359. });
  68360. });
  68361. }
  68362. return DracoCompression._DecoderModulePromise;
  68363. };
  68364. DracoCompression._LoadScriptAsync = function (url) {
  68365. return new Promise(function (resolve, reject) {
  68366. BABYLON.Tools.LoadScript(url, function () {
  68367. resolve();
  68368. }, function (message) {
  68369. reject(new Error(message));
  68370. });
  68371. });
  68372. };
  68373. DracoCompression._LoadFileAsync = function (url) {
  68374. return new Promise(function (resolve, reject) {
  68375. BABYLON.Tools.LoadFile(url, function (data) {
  68376. resolve(data);
  68377. }, undefined, undefined, true, function (request, exception) {
  68378. reject(exception);
  68379. });
  68380. });
  68381. };
  68382. /**
  68383. * The configuration. Defaults to the following urls:
  68384. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  68385. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  68386. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  68387. */
  68388. DracoCompression.Configuration = {
  68389. decoder: {
  68390. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  68391. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  68392. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  68393. }
  68394. };
  68395. return DracoCompression;
  68396. }());
  68397. BABYLON.DracoCompression = DracoCompression;
  68398. })(BABYLON || (BABYLON = {}));
  68399. //# sourceMappingURL=babylon.dracoCompression.js.map
  68400. var BABYLON;
  68401. (function (BABYLON) {
  68402. // Sets the default audio engine to Babylon JS.
  68403. BABYLON.Engine.AudioEngineFactory = function (engine) { return new AudioEngine(engine); };
  68404. /**
  68405. * This represents the default audio engine used in babylon.
  68406. * It is responsible to play, synchronize and analyse sounds throughout the application.
  68407. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  68408. */
  68409. var AudioEngine = /** @class */ (function () {
  68410. /**
  68411. * Instantiates a new audio engine.
  68412. *
  68413. * There should be only one per page as some browsers restrict the number
  68414. * of audio contexts you can create.
  68415. * @param engine defines the hosting engine
  68416. */
  68417. function AudioEngine(engine) {
  68418. if (engine === void 0) { engine = BABYLON.Engine.LastCreatedEngine; }
  68419. var _this = this;
  68420. this._audioContext = null;
  68421. this._audioContextInitialized = false;
  68422. this._muteButton = null;
  68423. /**
  68424. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  68425. */
  68426. this.canUseWebAudio = false;
  68427. /**
  68428. * Defines if Babylon should emit a warning if WebAudio is not supported.
  68429. * @ignoreNaming
  68430. */
  68431. this.WarnedWebAudioUnsupported = false;
  68432. /**
  68433. * Gets whether or not mp3 are supported by your browser.
  68434. */
  68435. this.isMP3supported = false;
  68436. /**
  68437. * Gets whether or not ogg are supported by your browser.
  68438. */
  68439. this.isOGGsupported = false;
  68440. /**
  68441. * Gets whether audio has been unlocked on the device.
  68442. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  68443. * a user interaction has happened.
  68444. */
  68445. this.unlocked = true;
  68446. /**
  68447. * Defines if the audio engine relies on a custom unlocked button.
  68448. * In this case, the embedded button will not be displayed.
  68449. */
  68450. this.useCustomUnlockedButton = false;
  68451. /**
  68452. * Event raised when audio has been unlocked on the browser.
  68453. */
  68454. this.onAudioUnlockedObservable = new BABYLON.Observable();
  68455. /**
  68456. * Event raised when audio has been locked on the browser.
  68457. */
  68458. this.onAudioLockedObservable = new BABYLON.Observable();
  68459. this._tryToRun = false;
  68460. this._onResize = function () {
  68461. _this._moveButtonToTopLeft();
  68462. };
  68463. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  68464. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  68465. this.canUseWebAudio = true;
  68466. }
  68467. var audioElem = document.createElement('audio');
  68468. this._engine = engine;
  68469. try {
  68470. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  68471. this.isMP3supported = true;
  68472. }
  68473. }
  68474. catch (e) {
  68475. // protect error during capability check.
  68476. }
  68477. try {
  68478. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  68479. this.isOGGsupported = true;
  68480. }
  68481. }
  68482. catch (e) {
  68483. // protect error during capability check.
  68484. }
  68485. }
  68486. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  68487. /**
  68488. * Gets the current AudioContext if available.
  68489. */
  68490. get: function () {
  68491. if (!this._audioContextInitialized) {
  68492. this._initializeAudioContext();
  68493. }
  68494. else {
  68495. if (!this.unlocked && !this._muteButton) {
  68496. this._displayMuteButton();
  68497. }
  68498. }
  68499. return this._audioContext;
  68500. },
  68501. enumerable: true,
  68502. configurable: true
  68503. });
  68504. /**
  68505. * Flags the audio engine in Locked state.
  68506. * This happens due to new browser policies preventing audio to autoplay.
  68507. */
  68508. AudioEngine.prototype.lock = function () {
  68509. this._triggerSuspendedState();
  68510. };
  68511. /**
  68512. * Unlocks the audio engine once a user action has been done on the dom.
  68513. * This is helpful to resume play once browser policies have been satisfied.
  68514. */
  68515. AudioEngine.prototype.unlock = function () {
  68516. this._triggerRunningState();
  68517. };
  68518. AudioEngine.prototype._resumeAudioContext = function () {
  68519. var result;
  68520. if (this._audioContext.resume) {
  68521. result = this._audioContext.resume();
  68522. }
  68523. return result || Promise.resolve();
  68524. };
  68525. AudioEngine.prototype._initializeAudioContext = function () {
  68526. var _this = this;
  68527. try {
  68528. if (this.canUseWebAudio) {
  68529. this._audioContext = new AudioContext();
  68530. // create a global volume gain node
  68531. this.masterGain = this._audioContext.createGain();
  68532. this.masterGain.gain.value = 1;
  68533. this.masterGain.connect(this._audioContext.destination);
  68534. this._audioContextInitialized = true;
  68535. if (this._audioContext.state === "running") {
  68536. // Do not wait for the promise to unlock.
  68537. this._triggerRunningState();
  68538. }
  68539. else {
  68540. if (this._audioContext && this._audioContext.resume) {
  68541. this._resumeAudioContext().then(function () {
  68542. _this._triggerRunningState();
  68543. }).catch(function () {
  68544. // Can not resume automatically
  68545. // Needs user action
  68546. _this.lock();
  68547. });
  68548. }
  68549. }
  68550. }
  68551. }
  68552. catch (e) {
  68553. this.canUseWebAudio = false;
  68554. BABYLON.Tools.Error("Web Audio: " + e.message);
  68555. }
  68556. };
  68557. AudioEngine.prototype._triggerRunningState = function () {
  68558. var _this = this;
  68559. if (this._tryToRun) {
  68560. return;
  68561. }
  68562. this._tryToRun = true;
  68563. this._resumeAudioContext()
  68564. .then(function () {
  68565. _this._tryToRun = false;
  68566. _this.unlocked = true;
  68567. if (_this._muteButton) {
  68568. _this._hideMuteButton();
  68569. }
  68570. // Notify users that the audio stack is unlocked/unmuted
  68571. _this.onAudioUnlockedObservable.notifyObservers(_this);
  68572. }).catch(function () {
  68573. _this._tryToRun = false;
  68574. _this.unlocked = false;
  68575. });
  68576. };
  68577. AudioEngine.prototype._triggerSuspendedState = function () {
  68578. this.unlocked = false;
  68579. this.onAudioLockedObservable.notifyObservers(this);
  68580. this._displayMuteButton();
  68581. };
  68582. AudioEngine.prototype._displayMuteButton = function () {
  68583. var _this = this;
  68584. if (this.useCustomUnlockedButton) {
  68585. return;
  68586. }
  68587. this._canvas = this._engine.getRenderingCanvas();
  68588. this._muteButton = document.createElement("BUTTON");
  68589. this._muteButton.className = "babylonUnmuteIcon";
  68590. this._muteButton.id = "babylonUnmuteIconBtn";
  68591. this._muteButton.title = "Unmute";
  68592. var css = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }";
  68593. var style = document.createElement('style');
  68594. style.appendChild(document.createTextNode(css));
  68595. document.getElementsByTagName('head')[0].appendChild(style);
  68596. document.body.appendChild(this._muteButton);
  68597. this._moveButtonToTopLeft();
  68598. this._muteButton.addEventListener('mousedown', function () {
  68599. _this._triggerRunningState();
  68600. }, true);
  68601. this._muteButton.addEventListener('touchend', function () {
  68602. _this._triggerRunningState();
  68603. }, true);
  68604. this._muteButton.addEventListener('click', function () {
  68605. _this._triggerRunningState();
  68606. }, true);
  68607. window.addEventListener("resize", this._onResize);
  68608. };
  68609. AudioEngine.prototype._moveButtonToTopLeft = function () {
  68610. if (this._canvas && this._muteButton) {
  68611. this._muteButton.style.top = this._canvas.offsetTop + 20 + "px";
  68612. this._muteButton.style.left = this._canvas.offsetLeft + 20 + "px";
  68613. }
  68614. };
  68615. AudioEngine.prototype._hideMuteButton = function () {
  68616. if (this._muteButton) {
  68617. document.body.removeChild(this._muteButton);
  68618. this._muteButton = null;
  68619. }
  68620. };
  68621. /**
  68622. * Destroy and release the resources associated with the audio ccontext.
  68623. */
  68624. AudioEngine.prototype.dispose = function () {
  68625. if (this.canUseWebAudio && this._audioContextInitialized) {
  68626. if (this._connectedAnalyser && this._audioContext) {
  68627. this._connectedAnalyser.stopDebugCanvas();
  68628. this._connectedAnalyser.dispose();
  68629. this.masterGain.disconnect();
  68630. this.masterGain.connect(this._audioContext.destination);
  68631. this._connectedAnalyser = null;
  68632. }
  68633. this.masterGain.gain.value = 1;
  68634. }
  68635. this.WarnedWebAudioUnsupported = false;
  68636. this._hideMuteButton();
  68637. window.removeEventListener("resize", this._onResize);
  68638. this.onAudioUnlockedObservable.clear();
  68639. this.onAudioLockedObservable.clear();
  68640. };
  68641. /**
  68642. * Gets the global volume sets on the master gain.
  68643. * @returns the global volume if set or -1 otherwise
  68644. */
  68645. AudioEngine.prototype.getGlobalVolume = function () {
  68646. if (this.canUseWebAudio && this._audioContextInitialized) {
  68647. return this.masterGain.gain.value;
  68648. }
  68649. else {
  68650. return -1;
  68651. }
  68652. };
  68653. /**
  68654. * Sets the global volume of your experience (sets on the master gain).
  68655. * @param newVolume Defines the new global volume of the application
  68656. */
  68657. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  68658. if (this.canUseWebAudio && this._audioContextInitialized) {
  68659. this.masterGain.gain.value = newVolume;
  68660. }
  68661. };
  68662. /**
  68663. * Connect the audio engine to an audio analyser allowing some amazing
  68664. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  68665. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  68666. * @param analyser The analyser to connect to the engine
  68667. */
  68668. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  68669. if (this._connectedAnalyser) {
  68670. this._connectedAnalyser.stopDebugCanvas();
  68671. }
  68672. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  68673. this._connectedAnalyser = analyser;
  68674. this.masterGain.disconnect();
  68675. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  68676. }
  68677. };
  68678. return AudioEngine;
  68679. }());
  68680. BABYLON.AudioEngine = AudioEngine;
  68681. })(BABYLON || (BABYLON = {}));
  68682. //# sourceMappingURL=babylon.audioEngine.js.map
  68683. var BABYLON;
  68684. (function (BABYLON) {
  68685. /**
  68686. * Defines a sound that can be played in the application.
  68687. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  68688. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  68689. */
  68690. var Sound = /** @class */ (function () {
  68691. /**
  68692. * Create a sound and attach it to a scene
  68693. * @param name Name of your sound
  68694. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  68695. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  68696. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  68697. */
  68698. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  68699. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  68700. var _this = this;
  68701. /**
  68702. * Does the sound autoplay once loaded.
  68703. */
  68704. this.autoplay = false;
  68705. /**
  68706. * Does the sound loop after it finishes playing once.
  68707. */
  68708. this.loop = false;
  68709. /**
  68710. * Does the sound use a custom attenuation curve to simulate the falloff
  68711. * happening when the source gets further away from the camera.
  68712. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  68713. */
  68714. this.useCustomAttenuation = false;
  68715. /**
  68716. * Is this sound currently played.
  68717. */
  68718. this.isPlaying = false;
  68719. /**
  68720. * Is this sound currently paused.
  68721. */
  68722. this.isPaused = false;
  68723. /**
  68724. * Does this sound enables spatial sound.
  68725. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68726. */
  68727. this.spatialSound = false;
  68728. /**
  68729. * Define the reference distance the sound should be heard perfectly.
  68730. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68731. */
  68732. this.refDistance = 1;
  68733. /**
  68734. * Define the roll off factor of spatial sounds.
  68735. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68736. */
  68737. this.rolloffFactor = 1;
  68738. /**
  68739. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  68740. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68741. */
  68742. this.maxDistance = 100;
  68743. /**
  68744. * Define the distance attenuation model the sound will follow.
  68745. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  68746. */
  68747. this.distanceModel = "linear";
  68748. /**
  68749. * Observable event when the current playing sound finishes.
  68750. */
  68751. this.onEndedObservable = new BABYLON.Observable();
  68752. this._panningModel = "equalpower";
  68753. this._playbackRate = 1;
  68754. this._streaming = false;
  68755. this._startTime = 0;
  68756. this._startOffset = 0;
  68757. this._position = BABYLON.Vector3.Zero();
  68758. /** @hidden */
  68759. this._positionInEmitterSpace = false;
  68760. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  68761. this._volume = 1;
  68762. this._isReadyToPlay = false;
  68763. this._isDirectional = false;
  68764. // Used if you'd like to create a directional sound.
  68765. // If not set, the sound will be omnidirectional
  68766. this._coneInnerAngle = 360;
  68767. this._coneOuterAngle = 360;
  68768. this._coneOuterGain = 0;
  68769. this._isOutputConnected = false;
  68770. this._urlType = "Unknown";
  68771. this.name = name;
  68772. this._scene = scene;
  68773. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68774. if (!compo) {
  68775. compo = new BABYLON.AudioSceneComponent(scene);
  68776. scene._addComponent(compo);
  68777. }
  68778. this._readyToPlayCallback = readyToPlayCallback;
  68779. // Default custom attenuation function is a linear attenuation
  68780. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  68781. if (currentDistance < maxDistance) {
  68782. return currentVolume * (1 - currentDistance / maxDistance);
  68783. }
  68784. else {
  68785. return 0;
  68786. }
  68787. };
  68788. if (options) {
  68789. this.autoplay = options.autoplay || false;
  68790. this.loop = options.loop || false;
  68791. // if volume === 0, we need another way to check this option
  68792. if (options.volume !== undefined) {
  68793. this._volume = options.volume;
  68794. }
  68795. this.spatialSound = options.spatialSound || false;
  68796. this.maxDistance = options.maxDistance || 100;
  68797. this.useCustomAttenuation = options.useCustomAttenuation || false;
  68798. this.rolloffFactor = options.rolloffFactor || 1;
  68799. this.refDistance = options.refDistance || 1;
  68800. this.distanceModel = options.distanceModel || "linear";
  68801. this._playbackRate = options.playbackRate || 1;
  68802. this._streaming = options.streaming || false;
  68803. }
  68804. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  68805. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  68806. this._soundGain.gain.value = this._volume;
  68807. this._inputAudioNode = this._soundGain;
  68808. this._outputAudioNode = this._soundGain;
  68809. if (this.spatialSound) {
  68810. this._createSpatialParameters();
  68811. }
  68812. this._scene.mainSoundTrack.AddSound(this);
  68813. var validParameter = true;
  68814. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  68815. if (urlOrArrayBuffer) {
  68816. try {
  68817. if (typeof (urlOrArrayBuffer) === "string") {
  68818. this._urlType = "String";
  68819. }
  68820. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  68821. this._urlType = "ArrayBuffer";
  68822. }
  68823. else if (urlOrArrayBuffer instanceof MediaStream) {
  68824. this._urlType = "MediaStream";
  68825. }
  68826. else if (Array.isArray(urlOrArrayBuffer)) {
  68827. this._urlType = "Array";
  68828. }
  68829. var urls = [];
  68830. var codecSupportedFound = false;
  68831. switch (this._urlType) {
  68832. case "MediaStream":
  68833. this._streaming = true;
  68834. this._isReadyToPlay = true;
  68835. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  68836. if (this.autoplay) {
  68837. this.play();
  68838. }
  68839. if (this._readyToPlayCallback) {
  68840. this._readyToPlayCallback();
  68841. }
  68842. break;
  68843. case "ArrayBuffer":
  68844. if (urlOrArrayBuffer.byteLength > 0) {
  68845. codecSupportedFound = true;
  68846. this._soundLoaded(urlOrArrayBuffer);
  68847. }
  68848. break;
  68849. case "String":
  68850. urls.push(urlOrArrayBuffer);
  68851. case "Array":
  68852. if (urls.length === 0)
  68853. urls = urlOrArrayBuffer;
  68854. // If we found a supported format, we load it immediately and stop the loop
  68855. for (var i = 0; i < urls.length; i++) {
  68856. var url = urls[i];
  68857. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  68858. codecSupportedFound = true;
  68859. }
  68860. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  68861. codecSupportedFound = true;
  68862. }
  68863. if (url.indexOf(".wav", url.length - 4) !== -1) {
  68864. codecSupportedFound = true;
  68865. }
  68866. if (url.indexOf("blob:") !== -1) {
  68867. codecSupportedFound = true;
  68868. }
  68869. if (codecSupportedFound) {
  68870. // Loading sound using XHR2
  68871. if (!this._streaming) {
  68872. this._scene._loadFile(url, function (data) {
  68873. _this._soundLoaded(data);
  68874. }, undefined, true, true, function (exception) {
  68875. if (exception) {
  68876. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  68877. }
  68878. BABYLON.Tools.Error("Sound creation aborted.");
  68879. _this._scene.mainSoundTrack.RemoveSound(_this);
  68880. });
  68881. }
  68882. // Streaming sound using HTML5 Audio tag
  68883. else {
  68884. this._htmlAudioElement = new Audio(url);
  68885. this._htmlAudioElement.controls = false;
  68886. this._htmlAudioElement.loop = this.loop;
  68887. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  68888. this._htmlAudioElement.preload = "auto";
  68889. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  68890. _this._isReadyToPlay = true;
  68891. if (_this.autoplay) {
  68892. _this.play();
  68893. }
  68894. if (_this._readyToPlayCallback) {
  68895. _this._readyToPlayCallback();
  68896. }
  68897. });
  68898. document.body.appendChild(this._htmlAudioElement);
  68899. this._htmlAudioElement.load();
  68900. }
  68901. break;
  68902. }
  68903. }
  68904. break;
  68905. default:
  68906. validParameter = false;
  68907. break;
  68908. }
  68909. if (!validParameter) {
  68910. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  68911. }
  68912. else {
  68913. if (!codecSupportedFound) {
  68914. this._isReadyToPlay = true;
  68915. // Simulating a ready to play event to avoid breaking code path
  68916. if (this._readyToPlayCallback) {
  68917. window.setTimeout(function () {
  68918. if (_this._readyToPlayCallback) {
  68919. _this._readyToPlayCallback();
  68920. }
  68921. }, 1000);
  68922. }
  68923. }
  68924. }
  68925. }
  68926. catch (ex) {
  68927. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  68928. this._scene.mainSoundTrack.RemoveSound(this);
  68929. }
  68930. }
  68931. }
  68932. else {
  68933. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  68934. this._scene.mainSoundTrack.AddSound(this);
  68935. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  68936. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  68937. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  68938. }
  68939. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  68940. if (this._readyToPlayCallback) {
  68941. window.setTimeout(function () {
  68942. if (_this._readyToPlayCallback) {
  68943. _this._readyToPlayCallback();
  68944. }
  68945. }, 1000);
  68946. }
  68947. }
  68948. }
  68949. /**
  68950. * Release the sound and its associated resources
  68951. */
  68952. Sound.prototype.dispose = function () {
  68953. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68954. if (this.isPlaying) {
  68955. this.stop();
  68956. }
  68957. this._isReadyToPlay = false;
  68958. if (this.soundTrackId === -1) {
  68959. this._scene.mainSoundTrack.RemoveSound(this);
  68960. }
  68961. else if (this._scene.soundTracks) {
  68962. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  68963. }
  68964. if (this._soundGain) {
  68965. this._soundGain.disconnect();
  68966. this._soundGain = null;
  68967. }
  68968. if (this._soundPanner) {
  68969. this._soundPanner.disconnect();
  68970. this._soundPanner = null;
  68971. }
  68972. if (this._soundSource) {
  68973. this._soundSource.disconnect();
  68974. this._soundSource = null;
  68975. }
  68976. this._audioBuffer = null;
  68977. if (this._htmlAudioElement) {
  68978. this._htmlAudioElement.pause();
  68979. this._htmlAudioElement.src = "";
  68980. document.body.removeChild(this._htmlAudioElement);
  68981. }
  68982. if (this._streamingSource) {
  68983. this._streamingSource.disconnect();
  68984. }
  68985. if (this._connectedMesh && this._registerFunc) {
  68986. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  68987. this._connectedMesh = null;
  68988. }
  68989. }
  68990. };
  68991. /**
  68992. * Gets if the sounds is ready to be played or not.
  68993. * @returns true if ready, otherwise false
  68994. */
  68995. Sound.prototype.isReady = function () {
  68996. return this._isReadyToPlay;
  68997. };
  68998. Sound.prototype._soundLoaded = function (audioData) {
  68999. var _this = this;
  69000. if (!BABYLON.Engine.audioEngine.audioContext) {
  69001. return;
  69002. }
  69003. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  69004. _this._audioBuffer = buffer;
  69005. _this._isReadyToPlay = true;
  69006. if (_this.autoplay) {
  69007. _this.play();
  69008. }
  69009. if (_this._readyToPlayCallback) {
  69010. _this._readyToPlayCallback();
  69011. }
  69012. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  69013. };
  69014. /**
  69015. * Sets the data of the sound from an audiobuffer
  69016. * @param audioBuffer The audioBuffer containing the data
  69017. */
  69018. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  69019. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69020. this._audioBuffer = audioBuffer;
  69021. this._isReadyToPlay = true;
  69022. }
  69023. };
  69024. /**
  69025. * Updates the current sounds options such as maxdistance, loop...
  69026. * @param options A JSON object containing values named as the object properties
  69027. */
  69028. Sound.prototype.updateOptions = function (options) {
  69029. if (options) {
  69030. this.loop = options.loop || this.loop;
  69031. this.maxDistance = options.maxDistance || this.maxDistance;
  69032. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  69033. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  69034. this.refDistance = options.refDistance || this.refDistance;
  69035. this.distanceModel = options.distanceModel || this.distanceModel;
  69036. this._playbackRate = options.playbackRate || this._playbackRate;
  69037. this._updateSpatialParameters();
  69038. if (this.isPlaying) {
  69039. if (this._streaming && this._htmlAudioElement) {
  69040. this._htmlAudioElement.playbackRate = this._playbackRate;
  69041. }
  69042. else {
  69043. if (this._soundSource) {
  69044. this._soundSource.playbackRate.value = this._playbackRate;
  69045. }
  69046. }
  69047. }
  69048. }
  69049. };
  69050. Sound.prototype._createSpatialParameters = function () {
  69051. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  69052. if (this._scene.headphone) {
  69053. this._panningModel = "HRTF";
  69054. }
  69055. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  69056. this._updateSpatialParameters();
  69057. this._soundPanner.connect(this._outputAudioNode);
  69058. this._inputAudioNode = this._soundPanner;
  69059. }
  69060. };
  69061. Sound.prototype._updateSpatialParameters = function () {
  69062. if (this.spatialSound && this._soundPanner) {
  69063. if (this.useCustomAttenuation) {
  69064. // Tricks to disable in a way embedded Web Audio attenuation
  69065. this._soundPanner.distanceModel = "linear";
  69066. this._soundPanner.maxDistance = Number.MAX_VALUE;
  69067. this._soundPanner.refDistance = 1;
  69068. this._soundPanner.rolloffFactor = 1;
  69069. this._soundPanner.panningModel = this._panningModel;
  69070. }
  69071. else {
  69072. this._soundPanner.distanceModel = this.distanceModel;
  69073. this._soundPanner.maxDistance = this.maxDistance;
  69074. this._soundPanner.refDistance = this.refDistance;
  69075. this._soundPanner.rolloffFactor = this.rolloffFactor;
  69076. this._soundPanner.panningModel = this._panningModel;
  69077. }
  69078. }
  69079. };
  69080. /**
  69081. * Switch the panning model to HRTF:
  69082. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  69083. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69084. */
  69085. Sound.prototype.switchPanningModelToHRTF = function () {
  69086. this._panningModel = "HRTF";
  69087. this._switchPanningModel();
  69088. };
  69089. /**
  69090. * Switch the panning model to Equal Power:
  69091. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  69092. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69093. */
  69094. Sound.prototype.switchPanningModelToEqualPower = function () {
  69095. this._panningModel = "equalpower";
  69096. this._switchPanningModel();
  69097. };
  69098. Sound.prototype._switchPanningModel = function () {
  69099. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  69100. this._soundPanner.panningModel = this._panningModel;
  69101. }
  69102. };
  69103. /**
  69104. * Connect this sound to a sound track audio node like gain...
  69105. * @param soundTrackAudioNode the sound track audio node to connect to
  69106. */
  69107. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  69108. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69109. if (this._isOutputConnected) {
  69110. this._outputAudioNode.disconnect();
  69111. }
  69112. this._outputAudioNode.connect(soundTrackAudioNode);
  69113. this._isOutputConnected = true;
  69114. }
  69115. };
  69116. /**
  69117. * Transform this sound into a directional source
  69118. * @param coneInnerAngle Size of the inner cone in degree
  69119. * @param coneOuterAngle Size of the outer cone in degree
  69120. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  69121. */
  69122. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  69123. if (coneOuterAngle < coneInnerAngle) {
  69124. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  69125. return;
  69126. }
  69127. this._coneInnerAngle = coneInnerAngle;
  69128. this._coneOuterAngle = coneOuterAngle;
  69129. this._coneOuterGain = coneOuterGain;
  69130. this._isDirectional = true;
  69131. if (this.isPlaying && this.loop) {
  69132. this.stop();
  69133. this.play();
  69134. }
  69135. };
  69136. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  69137. /**
  69138. * Gets or sets the inner angle for the directional cone.
  69139. */
  69140. get: function () {
  69141. return this._coneInnerAngle;
  69142. },
  69143. /**
  69144. * Gets or sets the inner angle for the directional cone.
  69145. */
  69146. set: function (value) {
  69147. if (value != this._coneInnerAngle) {
  69148. if (this._coneOuterAngle < value) {
  69149. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69150. return;
  69151. }
  69152. this._coneInnerAngle = value;
  69153. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  69154. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  69155. }
  69156. }
  69157. },
  69158. enumerable: true,
  69159. configurable: true
  69160. });
  69161. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  69162. /**
  69163. * Gets or sets the outer angle for the directional cone.
  69164. */
  69165. get: function () {
  69166. return this._coneOuterAngle;
  69167. },
  69168. /**
  69169. * Gets or sets the outer angle for the directional cone.
  69170. */
  69171. set: function (value) {
  69172. if (value != this._coneOuterAngle) {
  69173. if (value < this._coneInnerAngle) {
  69174. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69175. return;
  69176. }
  69177. this._coneOuterAngle = value;
  69178. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  69179. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  69180. }
  69181. }
  69182. },
  69183. enumerable: true,
  69184. configurable: true
  69185. });
  69186. /**
  69187. * Sets the position of the emitter if spatial sound is enabled
  69188. * @param newPosition Defines the new posisiton
  69189. */
  69190. Sound.prototype.setPosition = function (newPosition) {
  69191. this._position = newPosition;
  69192. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  69193. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  69194. }
  69195. };
  69196. /**
  69197. * Sets the local direction of the emitter if spatial sound is enabled
  69198. * @param newLocalDirection Defines the new local direction
  69199. */
  69200. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  69201. this._localDirection = newLocalDirection;
  69202. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  69203. this._updateDirection();
  69204. }
  69205. };
  69206. Sound.prototype._updateDirection = function () {
  69207. if (!this._connectedMesh || !this._soundPanner) {
  69208. return;
  69209. }
  69210. var mat = this._connectedMesh.getWorldMatrix();
  69211. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  69212. direction.normalize();
  69213. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  69214. };
  69215. /** @hidden */
  69216. Sound.prototype.updateDistanceFromListener = function () {
  69217. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  69218. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  69219. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  69220. }
  69221. };
  69222. /**
  69223. * Sets a new custom attenuation function for the sound.
  69224. * @param callback Defines the function used for the attenuation
  69225. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  69226. */
  69227. Sound.prototype.setAttenuationFunction = function (callback) {
  69228. this._customAttenuationFunction = callback;
  69229. };
  69230. /**
  69231. * Play the sound
  69232. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  69233. * @param offset (optional) Start the sound setting it at a specific time
  69234. */
  69235. Sound.prototype.play = function (time, offset) {
  69236. var _this = this;
  69237. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  69238. try {
  69239. if (this._startOffset < 0) {
  69240. time = -this._startOffset;
  69241. this._startOffset = 0;
  69242. }
  69243. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  69244. if (!this._soundSource || !this._streamingSource) {
  69245. if (this.spatialSound && this._soundPanner) {
  69246. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  69247. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  69248. }
  69249. if (this._isDirectional) {
  69250. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  69251. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  69252. this._soundPanner.coneOuterGain = this._coneOuterGain;
  69253. if (this._connectedMesh) {
  69254. this._updateDirection();
  69255. }
  69256. else {
  69257. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  69258. }
  69259. }
  69260. }
  69261. }
  69262. if (this._streaming) {
  69263. if (!this._streamingSource) {
  69264. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  69265. this._htmlAudioElement.onended = function () { _this._onended(); };
  69266. this._htmlAudioElement.playbackRate = this._playbackRate;
  69267. }
  69268. this._streamingSource.disconnect();
  69269. this._streamingSource.connect(this._inputAudioNode);
  69270. if (this._htmlAudioElement) {
  69271. // required to manage properly the new suspended default state of Chrome
  69272. // When the option 'streaming: true' is used, we need first to wait for
  69273. // the audio engine to be unlocked by a user gesture before trying to play
  69274. // an HTML Audio elememt
  69275. var tryToPlay = function () {
  69276. if (BABYLON.Engine.audioEngine.unlocked) {
  69277. var playPromise = _this._htmlAudioElement.play();
  69278. // In browsers that don’t yet support this functionality,
  69279. // playPromise won’t be defined.
  69280. if (playPromise !== undefined) {
  69281. playPromise.catch(function (error) {
  69282. // Automatic playback failed.
  69283. // Waiting for the audio engine to be unlocked by user click on unmute
  69284. BABYLON.Engine.audioEngine.lock();
  69285. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  69286. });
  69287. }
  69288. }
  69289. else {
  69290. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  69291. }
  69292. };
  69293. tryToPlay();
  69294. }
  69295. }
  69296. else {
  69297. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  69298. this._soundSource.buffer = this._audioBuffer;
  69299. this._soundSource.connect(this._inputAudioNode);
  69300. this._soundSource.loop = this.loop;
  69301. this._soundSource.playbackRate.value = this._playbackRate;
  69302. this._soundSource.onended = function () { _this._onended(); };
  69303. if (this._soundSource.buffer) {
  69304. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  69305. }
  69306. }
  69307. this._startTime = startTime;
  69308. this.isPlaying = true;
  69309. this.isPaused = false;
  69310. }
  69311. catch (ex) {
  69312. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  69313. }
  69314. }
  69315. };
  69316. Sound.prototype._onended = function () {
  69317. this.isPlaying = false;
  69318. if (this.onended) {
  69319. this.onended();
  69320. }
  69321. this.onEndedObservable.notifyObservers(this);
  69322. };
  69323. /**
  69324. * Stop the sound
  69325. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  69326. */
  69327. Sound.prototype.stop = function (time) {
  69328. if (this.isPlaying) {
  69329. if (this._streaming) {
  69330. if (this._htmlAudioElement) {
  69331. this._htmlAudioElement.pause();
  69332. // Test needed for Firefox or it will generate an Invalid State Error
  69333. if (this._htmlAudioElement.currentTime > 0) {
  69334. this._htmlAudioElement.currentTime = 0;
  69335. }
  69336. }
  69337. else {
  69338. this._streamingSource.disconnect();
  69339. }
  69340. }
  69341. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  69342. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  69343. this._soundSource.stop(stopTime);
  69344. this._soundSource.onended = function () { };
  69345. if (!this.isPaused) {
  69346. this._startOffset = 0;
  69347. }
  69348. }
  69349. this.isPlaying = false;
  69350. }
  69351. };
  69352. /**
  69353. * Put the sound in pause
  69354. */
  69355. Sound.prototype.pause = function () {
  69356. if (this.isPlaying) {
  69357. this.isPaused = true;
  69358. if (this._streaming) {
  69359. if (this._htmlAudioElement) {
  69360. this._htmlAudioElement.pause();
  69361. }
  69362. else {
  69363. this._streamingSource.disconnect();
  69364. }
  69365. }
  69366. else if (BABYLON.Engine.audioEngine.audioContext) {
  69367. this.stop(0);
  69368. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  69369. }
  69370. }
  69371. };
  69372. /**
  69373. * Sets a dedicated volume for this sounds
  69374. * @param newVolume Define the new volume of the sound
  69375. * @param time Define in how long the sound should be at this value
  69376. */
  69377. Sound.prototype.setVolume = function (newVolume, time) {
  69378. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  69379. if (time && BABYLON.Engine.audioEngine.audioContext) {
  69380. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  69381. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  69382. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  69383. }
  69384. else {
  69385. this._soundGain.gain.value = newVolume;
  69386. }
  69387. }
  69388. this._volume = newVolume;
  69389. };
  69390. /**
  69391. * Set the sound play back rate
  69392. * @param newPlaybackRate Define the playback rate the sound should be played at
  69393. */
  69394. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  69395. this._playbackRate = newPlaybackRate;
  69396. if (this.isPlaying) {
  69397. if (this._streaming && this._htmlAudioElement) {
  69398. this._htmlAudioElement.playbackRate = this._playbackRate;
  69399. }
  69400. else if (this._soundSource) {
  69401. this._soundSource.playbackRate.value = this._playbackRate;
  69402. }
  69403. }
  69404. };
  69405. /**
  69406. * Gets the volume of the sound.
  69407. * @returns the volume of the sound
  69408. */
  69409. Sound.prototype.getVolume = function () {
  69410. return this._volume;
  69411. };
  69412. /**
  69413. * Attach the sound to a dedicated mesh
  69414. * @param meshToConnectTo The mesh to connect the sound with
  69415. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  69416. */
  69417. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  69418. var _this = this;
  69419. if (this._connectedMesh && this._registerFunc) {
  69420. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  69421. this._registerFunc = null;
  69422. }
  69423. this._connectedMesh = meshToConnectTo;
  69424. if (!this.spatialSound) {
  69425. this.spatialSound = true;
  69426. this._createSpatialParameters();
  69427. if (this.isPlaying && this.loop) {
  69428. this.stop();
  69429. this.play();
  69430. }
  69431. }
  69432. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  69433. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  69434. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  69435. };
  69436. /**
  69437. * Detach the sound from the previously attached mesh
  69438. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  69439. */
  69440. Sound.prototype.detachFromMesh = function () {
  69441. if (this._connectedMesh && this._registerFunc) {
  69442. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  69443. this._registerFunc = null;
  69444. this._connectedMesh = null;
  69445. }
  69446. };
  69447. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  69448. if (!node.getBoundingInfo) {
  69449. return;
  69450. }
  69451. var mesh = node;
  69452. if (this._positionInEmitterSpace) {
  69453. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  69454. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  69455. }
  69456. else {
  69457. var boundingInfo = mesh.getBoundingInfo();
  69458. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  69459. }
  69460. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  69461. this._updateDirection();
  69462. }
  69463. };
  69464. /**
  69465. * Clone the current sound in the scene.
  69466. * @returns the new sound clone
  69467. */
  69468. Sound.prototype.clone = function () {
  69469. var _this = this;
  69470. if (!this._streaming) {
  69471. var setBufferAndRun = function () {
  69472. if (_this._isReadyToPlay) {
  69473. clonedSound._audioBuffer = _this.getAudioBuffer();
  69474. clonedSound._isReadyToPlay = true;
  69475. if (clonedSound.autoplay) {
  69476. clonedSound.play();
  69477. }
  69478. }
  69479. else {
  69480. window.setTimeout(setBufferAndRun, 300);
  69481. }
  69482. };
  69483. var currentOptions = {
  69484. autoplay: this.autoplay, loop: this.loop,
  69485. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  69486. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  69487. refDistance: this.refDistance, distanceModel: this.distanceModel
  69488. };
  69489. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  69490. if (this.useCustomAttenuation) {
  69491. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  69492. }
  69493. clonedSound.setPosition(this._position);
  69494. clonedSound.setPlaybackRate(this._playbackRate);
  69495. setBufferAndRun();
  69496. return clonedSound;
  69497. }
  69498. // Can't clone a streaming sound
  69499. else {
  69500. return null;
  69501. }
  69502. };
  69503. /**
  69504. * Gets the current underlying audio buffer containing the data
  69505. * @returns the audio buffer
  69506. */
  69507. Sound.prototype.getAudioBuffer = function () {
  69508. return this._audioBuffer;
  69509. };
  69510. /**
  69511. * Serializes the Sound in a JSON representation
  69512. * @returns the JSON representation of the sound
  69513. */
  69514. Sound.prototype.serialize = function () {
  69515. var serializationObject = {
  69516. name: this.name,
  69517. url: this.name,
  69518. autoplay: this.autoplay,
  69519. loop: this.loop,
  69520. volume: this._volume,
  69521. spatialSound: this.spatialSound,
  69522. maxDistance: this.maxDistance,
  69523. rolloffFactor: this.rolloffFactor,
  69524. refDistance: this.refDistance,
  69525. distanceModel: this.distanceModel,
  69526. playbackRate: this._playbackRate,
  69527. panningModel: this._panningModel,
  69528. soundTrackId: this.soundTrackId
  69529. };
  69530. if (this.spatialSound) {
  69531. if (this._connectedMesh)
  69532. serializationObject.connectedMeshId = this._connectedMesh.id;
  69533. serializationObject.position = this._position.asArray();
  69534. serializationObject.refDistance = this.refDistance;
  69535. serializationObject.distanceModel = this.distanceModel;
  69536. serializationObject.isDirectional = this._isDirectional;
  69537. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  69538. serializationObject.coneInnerAngle = this._coneInnerAngle;
  69539. serializationObject.coneOuterAngle = this._coneOuterAngle;
  69540. serializationObject.coneOuterGain = this._coneOuterGain;
  69541. }
  69542. return serializationObject;
  69543. };
  69544. /**
  69545. * Parse a JSON representation of a sound to innstantiate in a given scene
  69546. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  69547. * @param scene Define the scene the new parsed sound should be created in
  69548. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  69549. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  69550. * @returns the newly parsed sound
  69551. */
  69552. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  69553. var soundName = parsedSound.name;
  69554. var soundUrl;
  69555. if (parsedSound.url) {
  69556. soundUrl = rootUrl + parsedSound.url;
  69557. }
  69558. else {
  69559. soundUrl = rootUrl + soundName;
  69560. }
  69561. var options = {
  69562. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  69563. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  69564. rolloffFactor: parsedSound.rolloffFactor,
  69565. refDistance: parsedSound.refDistance,
  69566. distanceModel: parsedSound.distanceModel,
  69567. playbackRate: parsedSound.playbackRate
  69568. };
  69569. var newSound;
  69570. if (!sourceSound) {
  69571. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  69572. scene._addPendingData(newSound);
  69573. }
  69574. else {
  69575. var setBufferAndRun = function () {
  69576. if (sourceSound._isReadyToPlay) {
  69577. newSound._audioBuffer = sourceSound.getAudioBuffer();
  69578. newSound._isReadyToPlay = true;
  69579. if (newSound.autoplay) {
  69580. newSound.play();
  69581. }
  69582. }
  69583. else {
  69584. window.setTimeout(setBufferAndRun, 300);
  69585. }
  69586. };
  69587. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  69588. setBufferAndRun();
  69589. }
  69590. if (parsedSound.position) {
  69591. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  69592. newSound.setPosition(soundPosition);
  69593. }
  69594. if (parsedSound.isDirectional) {
  69595. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  69596. if (parsedSound.localDirectionToMesh) {
  69597. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  69598. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  69599. }
  69600. }
  69601. if (parsedSound.connectedMeshId) {
  69602. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  69603. if (connectedMesh) {
  69604. newSound.attachToMesh(connectedMesh);
  69605. }
  69606. }
  69607. return newSound;
  69608. };
  69609. return Sound;
  69610. }());
  69611. BABYLON.Sound = Sound;
  69612. })(BABYLON || (BABYLON = {}));
  69613. //# sourceMappingURL=babylon.sound.js.map
  69614. var BABYLON;
  69615. (function (BABYLON) {
  69616. /**
  69617. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  69618. * It will be also used in a future release to apply effects on a specific track.
  69619. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  69620. */
  69621. var SoundTrack = /** @class */ (function () {
  69622. /**
  69623. * Creates a new sound track.
  69624. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  69625. * @param scene Define the scene the sound track belongs to
  69626. * @param options
  69627. */
  69628. function SoundTrack(scene, options) {
  69629. if (options === void 0) { options = {}; }
  69630. /**
  69631. * The unique identifier of the sound track in the scene.
  69632. */
  69633. this.id = -1;
  69634. this._isMainTrack = false;
  69635. this._isInitialized = false;
  69636. this._scene = scene;
  69637. this.soundCollection = new Array();
  69638. this._options = options;
  69639. if (!this._isMainTrack && this._scene.soundTracks) {
  69640. this._scene.soundTracks.push(this);
  69641. this.id = this._scene.soundTracks.length - 1;
  69642. }
  69643. }
  69644. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  69645. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  69646. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  69647. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  69648. if (this._options) {
  69649. if (this._options.volume) {
  69650. this._outputAudioNode.gain.value = this._options.volume;
  69651. }
  69652. if (this._options.mainTrack) {
  69653. this._isMainTrack = this._options.mainTrack;
  69654. }
  69655. }
  69656. this._isInitialized = true;
  69657. }
  69658. };
  69659. /**
  69660. * Release the sound track and its associated resources
  69661. */
  69662. SoundTrack.prototype.dispose = function () {
  69663. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  69664. if (this._connectedAnalyser) {
  69665. this._connectedAnalyser.stopDebugCanvas();
  69666. }
  69667. while (this.soundCollection.length) {
  69668. this.soundCollection[0].dispose();
  69669. }
  69670. if (this._outputAudioNode) {
  69671. this._outputAudioNode.disconnect();
  69672. }
  69673. this._outputAudioNode = null;
  69674. }
  69675. };
  69676. /**
  69677. * Adds a sound to this sound track
  69678. * @param sound define the cound to add
  69679. * @ignoreNaming
  69680. */
  69681. SoundTrack.prototype.AddSound = function (sound) {
  69682. if (!this._isInitialized) {
  69683. this._initializeSoundTrackAudioGraph();
  69684. }
  69685. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  69686. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  69687. }
  69688. if (sound.soundTrackId) {
  69689. if (sound.soundTrackId === -1) {
  69690. this._scene.mainSoundTrack.RemoveSound(sound);
  69691. }
  69692. else if (this._scene.soundTracks) {
  69693. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  69694. }
  69695. }
  69696. this.soundCollection.push(sound);
  69697. sound.soundTrackId = this.id;
  69698. };
  69699. /**
  69700. * Removes a sound to this sound track
  69701. * @param sound define the cound to remove
  69702. * @ignoreNaming
  69703. */
  69704. SoundTrack.prototype.RemoveSound = function (sound) {
  69705. var index = this.soundCollection.indexOf(sound);
  69706. if (index !== -1) {
  69707. this.soundCollection.splice(index, 1);
  69708. }
  69709. };
  69710. /**
  69711. * Set a global volume for the full sound track.
  69712. * @param newVolume Define the new volume of the sound track
  69713. */
  69714. SoundTrack.prototype.setVolume = function (newVolume) {
  69715. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  69716. this._outputAudioNode.gain.value = newVolume;
  69717. }
  69718. };
  69719. /**
  69720. * Switch the panning model to HRTF:
  69721. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  69722. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69723. */
  69724. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  69725. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69726. for (var i = 0; i < this.soundCollection.length; i++) {
  69727. this.soundCollection[i].switchPanningModelToHRTF();
  69728. }
  69729. }
  69730. };
  69731. /**
  69732. * Switch the panning model to Equal Power:
  69733. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  69734. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69735. */
  69736. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  69737. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69738. for (var i = 0; i < this.soundCollection.length; i++) {
  69739. this.soundCollection[i].switchPanningModelToEqualPower();
  69740. }
  69741. }
  69742. };
  69743. /**
  69744. * Connect the sound track to an audio analyser allowing some amazing
  69745. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  69746. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  69747. * @param analyser The analyser to connect to the engine
  69748. */
  69749. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  69750. if (this._connectedAnalyser) {
  69751. this._connectedAnalyser.stopDebugCanvas();
  69752. }
  69753. this._connectedAnalyser = analyser;
  69754. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  69755. this._outputAudioNode.disconnect();
  69756. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  69757. }
  69758. };
  69759. return SoundTrack;
  69760. }());
  69761. BABYLON.SoundTrack = SoundTrack;
  69762. })(BABYLON || (BABYLON = {}));
  69763. //# sourceMappingURL=babylon.soundtrack.js.map
  69764. var BABYLON;
  69765. (function (BABYLON) {
  69766. /**
  69767. * Class used to work with sound analyzer using fast fourier transform (FFT)
  69768. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  69769. */
  69770. var Analyser = /** @class */ (function () {
  69771. /**
  69772. * Creates a new analyser
  69773. * @param scene defines hosting scene
  69774. */
  69775. function Analyser(scene) {
  69776. /**
  69777. * Gets or sets the smoothing
  69778. * @ignorenaming
  69779. */
  69780. this.SMOOTHING = 0.75;
  69781. /**
  69782. * Gets or sets the FFT table size
  69783. * @ignorenaming
  69784. */
  69785. this.FFT_SIZE = 512;
  69786. /**
  69787. * Gets or sets the bar graph amplitude
  69788. * @ignorenaming
  69789. */
  69790. this.BARGRAPHAMPLITUDE = 256;
  69791. /**
  69792. * Gets or sets the position of the debug canvas
  69793. * @ignorenaming
  69794. */
  69795. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  69796. /**
  69797. * Gets or sets the debug canvas size
  69798. * @ignorenaming
  69799. */
  69800. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  69801. this._scene = scene;
  69802. this._audioEngine = BABYLON.Engine.audioEngine;
  69803. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  69804. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  69805. this._webAudioAnalyser.minDecibels = -140;
  69806. this._webAudioAnalyser.maxDecibels = 0;
  69807. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  69808. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  69809. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  69810. }
  69811. }
  69812. /**
  69813. * Get the number of data values you will have to play with for the visualization
  69814. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  69815. * @returns a number
  69816. */
  69817. Analyser.prototype.getFrequencyBinCount = function () {
  69818. if (this._audioEngine.canUseWebAudio) {
  69819. return this._webAudioAnalyser.frequencyBinCount;
  69820. }
  69821. else {
  69822. return 0;
  69823. }
  69824. };
  69825. /**
  69826. * Gets the current frequency data as a byte array
  69827. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  69828. * @returns a Uint8Array
  69829. */
  69830. Analyser.prototype.getByteFrequencyData = function () {
  69831. if (this._audioEngine.canUseWebAudio) {
  69832. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  69833. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  69834. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  69835. }
  69836. return this._byteFreqs;
  69837. };
  69838. /**
  69839. * Gets the current waveform as a byte array
  69840. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  69841. * @returns a Uint8Array
  69842. */
  69843. Analyser.prototype.getByteTimeDomainData = function () {
  69844. if (this._audioEngine.canUseWebAudio) {
  69845. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  69846. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  69847. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  69848. }
  69849. return this._byteTime;
  69850. };
  69851. /**
  69852. * Gets the current frequency data as a float array
  69853. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  69854. * @returns a Float32Array
  69855. */
  69856. Analyser.prototype.getFloatFrequencyData = function () {
  69857. if (this._audioEngine.canUseWebAudio) {
  69858. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  69859. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  69860. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  69861. }
  69862. return this._floatFreqs;
  69863. };
  69864. /**
  69865. * Renders the debug canvas
  69866. */
  69867. Analyser.prototype.drawDebugCanvas = function () {
  69868. var _this = this;
  69869. if (this._audioEngine.canUseWebAudio) {
  69870. if (!this._debugCanvas) {
  69871. this._debugCanvas = document.createElement("canvas");
  69872. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  69873. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  69874. this._debugCanvas.style.position = "absolute";
  69875. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  69876. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  69877. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  69878. document.body.appendChild(this._debugCanvas);
  69879. this._registerFunc = function () {
  69880. _this.drawDebugCanvas();
  69881. };
  69882. this._scene.registerBeforeRender(this._registerFunc);
  69883. }
  69884. if (this._registerFunc && this._debugCanvasContext) {
  69885. var workingArray = this.getByteFrequencyData();
  69886. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  69887. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  69888. // Draw the frequency domain chart.
  69889. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  69890. var value = workingArray[i];
  69891. var percent = value / this.BARGRAPHAMPLITUDE;
  69892. var height = this.DEBUGCANVASSIZE.height * percent;
  69893. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  69894. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  69895. var hue = i / this.getFrequencyBinCount() * 360;
  69896. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  69897. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  69898. }
  69899. }
  69900. }
  69901. };
  69902. /**
  69903. * Stops rendering the debug canvas and removes it
  69904. */
  69905. Analyser.prototype.stopDebugCanvas = function () {
  69906. if (this._debugCanvas) {
  69907. if (this._registerFunc) {
  69908. this._scene.unregisterBeforeRender(this._registerFunc);
  69909. this._registerFunc = null;
  69910. }
  69911. document.body.removeChild(this._debugCanvas);
  69912. this._debugCanvas = null;
  69913. this._debugCanvasContext = null;
  69914. }
  69915. };
  69916. /**
  69917. * Connects two audio nodes
  69918. * @param inputAudioNode defines first node to connect
  69919. * @param outputAudioNode defines second node to connect
  69920. */
  69921. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  69922. if (this._audioEngine.canUseWebAudio) {
  69923. inputAudioNode.connect(this._webAudioAnalyser);
  69924. this._webAudioAnalyser.connect(outputAudioNode);
  69925. }
  69926. };
  69927. /**
  69928. * Releases all associated resources
  69929. */
  69930. Analyser.prototype.dispose = function () {
  69931. if (this._audioEngine.canUseWebAudio) {
  69932. this._webAudioAnalyser.disconnect();
  69933. }
  69934. };
  69935. return Analyser;
  69936. }());
  69937. BABYLON.Analyser = Analyser;
  69938. })(BABYLON || (BABYLON = {}));
  69939. //# sourceMappingURL=babylon.analyser.js.map
  69940. var BABYLON;
  69941. (function (BABYLON) {
  69942. /**
  69943. * Wraps one or more Sound objects and selects one with random weight for playback.
  69944. */
  69945. var WeightedSound = /** @class */ (function () {
  69946. /**
  69947. * Creates a new WeightedSound from the list of sounds given.
  69948. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  69949. * @param sounds Array of Sounds that will be selected from.
  69950. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  69951. */
  69952. function WeightedSound(loop, sounds, weights) {
  69953. var _this = this;
  69954. /** When true a Sound will be selected and played when the current playing Sound completes. */
  69955. this.loop = false;
  69956. this._coneInnerAngle = 360;
  69957. this._coneOuterAngle = 360;
  69958. this._volume = 1;
  69959. /** A Sound is currently playing. */
  69960. this.isPlaying = false;
  69961. /** A Sound is currently paused. */
  69962. this.isPaused = false;
  69963. this._sounds = [];
  69964. this._weights = [];
  69965. if (sounds.length !== weights.length) {
  69966. throw new Error('Sounds length does not equal weights length');
  69967. }
  69968. this.loop = loop;
  69969. this._weights = weights;
  69970. // Normalize the weights
  69971. var weightSum = 0;
  69972. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  69973. var weight = weights_1[_i];
  69974. weightSum += weight;
  69975. }
  69976. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  69977. for (var i = 0; i < this._weights.length; i++) {
  69978. this._weights[i] *= invWeightSum;
  69979. }
  69980. this._sounds = sounds;
  69981. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  69982. var sound = _b[_a];
  69983. sound.onEndedObservable.add(function () { _this._onended(); });
  69984. }
  69985. }
  69986. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  69987. /**
  69988. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  69989. */
  69990. get: function () {
  69991. return this._coneInnerAngle;
  69992. },
  69993. /**
  69994. * The size of cone in degress for a directional sound in which there will be no attenuation.
  69995. */
  69996. set: function (value) {
  69997. if (value !== this._coneInnerAngle) {
  69998. if (this._coneOuterAngle < value) {
  69999. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70000. return;
  70001. }
  70002. this._coneInnerAngle = value;
  70003. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70004. var sound = _a[_i];
  70005. sound.directionalConeInnerAngle = value;
  70006. }
  70007. }
  70008. },
  70009. enumerable: true,
  70010. configurable: true
  70011. });
  70012. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  70013. /**
  70014. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  70015. * Listener angles between innerAngle and outerAngle will falloff linearly.
  70016. */
  70017. get: function () {
  70018. return this._coneOuterAngle;
  70019. },
  70020. /**
  70021. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  70022. * Listener angles between innerAngle and outerAngle will falloff linearly.
  70023. */
  70024. set: function (value) {
  70025. if (value !== this._coneOuterAngle) {
  70026. if (value < this._coneInnerAngle) {
  70027. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70028. return;
  70029. }
  70030. this._coneOuterAngle = value;
  70031. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70032. var sound = _a[_i];
  70033. sound.directionalConeOuterAngle = value;
  70034. }
  70035. }
  70036. },
  70037. enumerable: true,
  70038. configurable: true
  70039. });
  70040. Object.defineProperty(WeightedSound.prototype, "volume", {
  70041. /**
  70042. * Playback volume.
  70043. */
  70044. get: function () {
  70045. return this._volume;
  70046. },
  70047. /**
  70048. * Playback volume.
  70049. */
  70050. set: function (value) {
  70051. if (value !== this._volume) {
  70052. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70053. var sound = _a[_i];
  70054. sound.setVolume(value);
  70055. }
  70056. }
  70057. },
  70058. enumerable: true,
  70059. configurable: true
  70060. });
  70061. WeightedSound.prototype._onended = function () {
  70062. if (this._currentIndex !== undefined) {
  70063. this._sounds[this._currentIndex].autoplay = false;
  70064. }
  70065. if (this.loop && this.isPlaying) {
  70066. this.play();
  70067. }
  70068. else {
  70069. this.isPlaying = false;
  70070. }
  70071. };
  70072. /**
  70073. * Suspend playback
  70074. */
  70075. WeightedSound.prototype.pause = function () {
  70076. this.isPaused = true;
  70077. if (this._currentIndex !== undefined) {
  70078. this._sounds[this._currentIndex].pause();
  70079. }
  70080. };
  70081. /**
  70082. * Stop playback
  70083. */
  70084. WeightedSound.prototype.stop = function () {
  70085. this.isPlaying = false;
  70086. if (this._currentIndex !== undefined) {
  70087. this._sounds[this._currentIndex].stop();
  70088. }
  70089. };
  70090. /**
  70091. * Start playback.
  70092. * @param startOffset Position the clip head at a specific time in seconds.
  70093. */
  70094. WeightedSound.prototype.play = function (startOffset) {
  70095. if (!this.isPaused) {
  70096. this.stop();
  70097. var randomValue = Math.random();
  70098. var total = 0;
  70099. for (var i = 0; i < this._weights.length; i++) {
  70100. total += this._weights[i];
  70101. if (randomValue <= total) {
  70102. this._currentIndex = i;
  70103. break;
  70104. }
  70105. }
  70106. }
  70107. var sound = this._sounds[this._currentIndex];
  70108. if (sound.isReady()) {
  70109. sound.play(0, this.isPaused ? undefined : startOffset);
  70110. }
  70111. else {
  70112. sound.autoplay = true;
  70113. }
  70114. this.isPlaying = true;
  70115. this.isPaused = false;
  70116. };
  70117. return WeightedSound;
  70118. }());
  70119. BABYLON.WeightedSound = WeightedSound;
  70120. })(BABYLON || (BABYLON = {}));
  70121. //# sourceMappingURL=babylon.weightedsound.js.map
  70122. var BABYLON;
  70123. (function (BABYLON) {
  70124. // Adds the parser to the scene parsers.
  70125. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  70126. // TODO: add sound
  70127. var loadedSounds = [];
  70128. var loadedSound;
  70129. container.sounds = container.sounds || [];
  70130. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  70131. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  70132. var parsedSound = parsedData.sounds[index];
  70133. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70134. if (!parsedSound.url)
  70135. parsedSound.url = parsedSound.name;
  70136. if (!loadedSounds[parsedSound.url]) {
  70137. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  70138. loadedSounds[parsedSound.url] = loadedSound;
  70139. container.sounds.push(loadedSound);
  70140. }
  70141. else {
  70142. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  70143. }
  70144. }
  70145. else {
  70146. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  70147. }
  70148. }
  70149. }
  70150. loadedSounds = [];
  70151. });
  70152. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  70153. get: function () {
  70154. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70155. if (!compo) {
  70156. compo = new AudioSceneComponent(this);
  70157. this._addComponent(compo);
  70158. }
  70159. if (!this._mainSoundTrack) {
  70160. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  70161. }
  70162. return this._mainSoundTrack;
  70163. },
  70164. enumerable: true,
  70165. configurable: true
  70166. });
  70167. BABYLON.Scene.prototype.getSoundByName = function (name) {
  70168. var index;
  70169. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  70170. if (this.mainSoundTrack.soundCollection[index].name === name) {
  70171. return this.mainSoundTrack.soundCollection[index];
  70172. }
  70173. }
  70174. if (this.soundTracks) {
  70175. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  70176. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  70177. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  70178. return this.soundTracks[sdIndex].soundCollection[index];
  70179. }
  70180. }
  70181. }
  70182. }
  70183. return null;
  70184. };
  70185. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  70186. get: function () {
  70187. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70188. if (!compo) {
  70189. compo = new AudioSceneComponent(this);
  70190. this._addComponent(compo);
  70191. }
  70192. return compo.audioEnabled;
  70193. },
  70194. set: function (value) {
  70195. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70196. if (!compo) {
  70197. compo = new AudioSceneComponent(this);
  70198. this._addComponent(compo);
  70199. }
  70200. if (value) {
  70201. compo.enableAudio();
  70202. }
  70203. else {
  70204. compo.disableAudio();
  70205. }
  70206. },
  70207. enumerable: true,
  70208. configurable: true
  70209. });
  70210. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  70211. get: function () {
  70212. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70213. if (!compo) {
  70214. compo = new AudioSceneComponent(this);
  70215. this._addComponent(compo);
  70216. }
  70217. return compo.headphone;
  70218. },
  70219. set: function (value) {
  70220. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70221. if (!compo) {
  70222. compo = new AudioSceneComponent(this);
  70223. this._addComponent(compo);
  70224. }
  70225. if (value) {
  70226. compo.switchAudioModeForHeadphones();
  70227. }
  70228. else {
  70229. compo.switchAudioModeForNormalSpeakers();
  70230. }
  70231. },
  70232. enumerable: true,
  70233. configurable: true
  70234. });
  70235. /**
  70236. * Defines the sound scene component responsible to manage any sounds
  70237. * in a given scene.
  70238. */
  70239. var AudioSceneComponent = /** @class */ (function () {
  70240. /**
  70241. * Creates a new instance of the component for the given scene
  70242. * @param scene Defines the scene to register the component in
  70243. */
  70244. function AudioSceneComponent(scene) {
  70245. /**
  70246. * The component name helpfull to identify the component in the list of scene components.
  70247. */
  70248. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  70249. this._audioEnabled = true;
  70250. this._headphone = false;
  70251. this.scene = scene;
  70252. scene.soundTracks = new Array();
  70253. scene.sounds = new Array();
  70254. }
  70255. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  70256. /**
  70257. * Gets whether audio is enabled or not.
  70258. * Please use related enable/disable method to switch state.
  70259. */
  70260. get: function () {
  70261. return this._audioEnabled;
  70262. },
  70263. enumerable: true,
  70264. configurable: true
  70265. });
  70266. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  70267. /**
  70268. * Gets whether audio is outputing to headphone or not.
  70269. * Please use the according Switch methods to change output.
  70270. */
  70271. get: function () {
  70272. return this._headphone;
  70273. },
  70274. enumerable: true,
  70275. configurable: true
  70276. });
  70277. /**
  70278. * Registers the component in a given scene
  70279. */
  70280. AudioSceneComponent.prototype.register = function () {
  70281. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  70282. };
  70283. /**
  70284. * Rebuilds the elements related to this component in case of
  70285. * context lost for instance.
  70286. */
  70287. AudioSceneComponent.prototype.rebuild = function () {
  70288. // Nothing to do here. (Not rendering related)
  70289. };
  70290. /**
  70291. * Serializes the component data to the specified json object
  70292. * @param serializationObject The object to serialize to
  70293. */
  70294. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  70295. serializationObject.sounds = [];
  70296. if (this.scene.soundTracks) {
  70297. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  70298. var soundtrack = this.scene.soundTracks[index];
  70299. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  70300. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  70301. }
  70302. }
  70303. }
  70304. };
  70305. /**
  70306. * Adds all the element from the container to the scene
  70307. * @param container the container holding the elements
  70308. */
  70309. AudioSceneComponent.prototype.addFromContainer = function (container) {
  70310. var _this = this;
  70311. if (!container.sounds) {
  70312. return;
  70313. }
  70314. container.sounds.forEach(function (sound) {
  70315. sound.play();
  70316. sound.autoplay = true;
  70317. _this.scene.mainSoundTrack.AddSound(sound);
  70318. });
  70319. };
  70320. /**
  70321. * Removes all the elements in the container from the scene
  70322. * @param container contains the elements to remove
  70323. */
  70324. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  70325. var _this = this;
  70326. if (!container.sounds) {
  70327. return;
  70328. }
  70329. container.sounds.forEach(function (sound) {
  70330. sound.stop();
  70331. sound.autoplay = false;
  70332. _this.scene.mainSoundTrack.RemoveSound(sound);
  70333. });
  70334. };
  70335. /**
  70336. * Disposes the component and the associated ressources.
  70337. */
  70338. AudioSceneComponent.prototype.dispose = function () {
  70339. var scene = this.scene;
  70340. if (scene._mainSoundTrack) {
  70341. scene.mainSoundTrack.dispose();
  70342. }
  70343. if (scene.soundTracks) {
  70344. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  70345. scene.soundTracks[scIndex].dispose();
  70346. }
  70347. }
  70348. };
  70349. /**
  70350. * Disables audio in the associated scene.
  70351. */
  70352. AudioSceneComponent.prototype.disableAudio = function () {
  70353. var scene = this.scene;
  70354. this._audioEnabled = false;
  70355. var i;
  70356. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  70357. scene.mainSoundTrack.soundCollection[i].pause();
  70358. }
  70359. if (scene.soundTracks) {
  70360. for (i = 0; i < scene.soundTracks.length; i++) {
  70361. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  70362. scene.soundTracks[i].soundCollection[j].pause();
  70363. }
  70364. }
  70365. }
  70366. };
  70367. /**
  70368. * Enables audio in the associated scene.
  70369. */
  70370. AudioSceneComponent.prototype.enableAudio = function () {
  70371. var scene = this.scene;
  70372. this._audioEnabled = true;
  70373. var i;
  70374. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  70375. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  70376. scene.mainSoundTrack.soundCollection[i].play();
  70377. }
  70378. }
  70379. if (scene.soundTracks) {
  70380. for (i = 0; i < scene.soundTracks.length; i++) {
  70381. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  70382. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  70383. scene.soundTracks[i].soundCollection[j].play();
  70384. }
  70385. }
  70386. }
  70387. }
  70388. };
  70389. /**
  70390. * Switch audio to headphone output.
  70391. */
  70392. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  70393. var scene = this.scene;
  70394. this._headphone = true;
  70395. scene.mainSoundTrack.switchPanningModelToHRTF();
  70396. if (scene.soundTracks) {
  70397. for (var i = 0; i < scene.soundTracks.length; i++) {
  70398. scene.soundTracks[i].switchPanningModelToHRTF();
  70399. }
  70400. }
  70401. };
  70402. /**
  70403. * Switch audio to normal speakers.
  70404. */
  70405. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  70406. var scene = this.scene;
  70407. this._headphone = false;
  70408. scene.mainSoundTrack.switchPanningModelToEqualPower();
  70409. if (scene.soundTracks) {
  70410. for (var i = 0; i < scene.soundTracks.length; i++) {
  70411. scene.soundTracks[i].switchPanningModelToEqualPower();
  70412. }
  70413. }
  70414. };
  70415. AudioSceneComponent.prototype._afterRender = function () {
  70416. var scene = this.scene;
  70417. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  70418. return;
  70419. }
  70420. var listeningCamera;
  70421. var audioEngine = BABYLON.Engine.audioEngine;
  70422. if (scene.activeCameras.length > 0) {
  70423. listeningCamera = scene.activeCameras[0];
  70424. }
  70425. else {
  70426. listeningCamera = scene.activeCamera;
  70427. }
  70428. if (listeningCamera && audioEngine.audioContext) {
  70429. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  70430. // for VR cameras
  70431. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  70432. listeningCamera = listeningCamera.rigCameras[0];
  70433. }
  70434. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  70435. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  70436. cameraDirection.normalize();
  70437. // To avoid some errors on GearVR
  70438. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  70439. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  70440. }
  70441. var i;
  70442. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  70443. var sound = scene.mainSoundTrack.soundCollection[i];
  70444. if (sound.useCustomAttenuation) {
  70445. sound.updateDistanceFromListener();
  70446. }
  70447. }
  70448. if (scene.soundTracks) {
  70449. for (i = 0; i < scene.soundTracks.length; i++) {
  70450. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  70451. sound = scene.soundTracks[i].soundCollection[j];
  70452. if (sound.useCustomAttenuation) {
  70453. sound.updateDistanceFromListener();
  70454. }
  70455. }
  70456. }
  70457. }
  70458. }
  70459. };
  70460. return AudioSceneComponent;
  70461. }());
  70462. BABYLON.AudioSceneComponent = AudioSceneComponent;
  70463. })(BABYLON || (BABYLON = {}));
  70464. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  70465. var BABYLON;
  70466. (function (BABYLON) {
  70467. /**
  70468. * This defines an action helpful to play a defined sound on a triggered action.
  70469. */
  70470. var PlaySoundAction = /** @class */ (function (_super) {
  70471. __extends(PlaySoundAction, _super);
  70472. /**
  70473. * Instantiate the action
  70474. * @param triggerOptions defines the trigger options
  70475. * @param sound defines the sound to play
  70476. * @param condition defines the trigger related conditions
  70477. */
  70478. function PlaySoundAction(triggerOptions, sound, condition) {
  70479. var _this = _super.call(this, triggerOptions, condition) || this;
  70480. _this._sound = sound;
  70481. return _this;
  70482. }
  70483. /** @hidden */
  70484. PlaySoundAction.prototype._prepare = function () {
  70485. };
  70486. /**
  70487. * Execute the action and play the sound.
  70488. */
  70489. PlaySoundAction.prototype.execute = function () {
  70490. if (this._sound !== undefined)
  70491. this._sound.play();
  70492. };
  70493. /**
  70494. * Serializes the actions and its related information.
  70495. * @param parent defines the object to serialize in
  70496. * @returns the serialized object
  70497. */
  70498. PlaySoundAction.prototype.serialize = function (parent) {
  70499. return _super.prototype._serialize.call(this, {
  70500. name: "PlaySoundAction",
  70501. properties: [{ name: "sound", value: this._sound.name }]
  70502. }, parent);
  70503. };
  70504. return PlaySoundAction;
  70505. }(BABYLON.Action));
  70506. BABYLON.PlaySoundAction = PlaySoundAction;
  70507. /**
  70508. * This defines an action helpful to stop a defined sound on a triggered action.
  70509. */
  70510. var StopSoundAction = /** @class */ (function (_super) {
  70511. __extends(StopSoundAction, _super);
  70512. /**
  70513. * Instantiate the action
  70514. * @param triggerOptions defines the trigger options
  70515. * @param sound defines the sound to stop
  70516. * @param condition defines the trigger related conditions
  70517. */
  70518. function StopSoundAction(triggerOptions, sound, condition) {
  70519. var _this = _super.call(this, triggerOptions, condition) || this;
  70520. _this._sound = sound;
  70521. return _this;
  70522. }
  70523. /** @hidden */
  70524. StopSoundAction.prototype._prepare = function () {
  70525. };
  70526. /**
  70527. * Execute the action and stop the sound.
  70528. */
  70529. StopSoundAction.prototype.execute = function () {
  70530. if (this._sound !== undefined)
  70531. this._sound.stop();
  70532. };
  70533. /**
  70534. * Serializes the actions and its related information.
  70535. * @param parent defines the object to serialize in
  70536. * @returns the serialized object
  70537. */
  70538. StopSoundAction.prototype.serialize = function (parent) {
  70539. return _super.prototype._serialize.call(this, {
  70540. name: "StopSoundAction",
  70541. properties: [{ name: "sound", value: this._sound.name }]
  70542. }, parent);
  70543. };
  70544. return StopSoundAction;
  70545. }(BABYLON.Action));
  70546. BABYLON.StopSoundAction = StopSoundAction;
  70547. })(BABYLON || (BABYLON = {}));
  70548. //# sourceMappingURL=babylon.directAudioActions.js.map
  70549. var BABYLON;
  70550. (function (BABYLON) {
  70551. /**
  70552. * Class for creating a cube texture
  70553. */
  70554. var CubeTexture = /** @class */ (function (_super) {
  70555. __extends(CubeTexture, _super);
  70556. /**
  70557. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  70558. * as prefiltered data.
  70559. * @param rootUrl defines the url of the texture or the root name of the six images
  70560. * @param scene defines the scene the texture is attached to
  70561. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  70562. * @param noMipmap defines if mipmaps should be created or not
  70563. * @param files defines the six files to load for the different faces
  70564. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  70565. * @param onError defines a callback triggered in case of error during load
  70566. * @param format defines the internal format to use for the texture once loaded
  70567. * @param prefiltered defines whether or not the texture is created from prefiltered data
  70568. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  70569. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  70570. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  70571. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  70572. * @return the cube texture
  70573. */
  70574. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  70575. if (extensions === void 0) { extensions = null; }
  70576. if (noMipmap === void 0) { noMipmap = false; }
  70577. if (files === void 0) { files = null; }
  70578. if (onLoad === void 0) { onLoad = null; }
  70579. if (onError === void 0) { onError = null; }
  70580. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70581. if (prefiltered === void 0) { prefiltered = false; }
  70582. if (forcedExtension === void 0) { forcedExtension = null; }
  70583. if (createPolynomials === void 0) { createPolynomials = false; }
  70584. if (lodScale === void 0) { lodScale = 0.8; }
  70585. if (lodOffset === void 0) { lodOffset = 0; }
  70586. var _this = _super.call(this, scene) || this;
  70587. /**
  70588. * Gets or sets the center of the bounding box associated with the cube texture.
  70589. * It must define where the camera used to render the texture was set
  70590. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  70591. */
  70592. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  70593. _this._rotationY = 0;
  70594. /** @hidden */
  70595. _this._prefiltered = false;
  70596. _this.name = rootUrl;
  70597. _this.url = rootUrl;
  70598. _this._noMipmap = noMipmap;
  70599. _this.hasAlpha = false;
  70600. _this._format = format;
  70601. _this.isCube = true;
  70602. _this._textureMatrix = BABYLON.Matrix.Identity();
  70603. _this._createPolynomials = createPolynomials;
  70604. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  70605. if (!rootUrl && !files) {
  70606. return _this;
  70607. }
  70608. var lastDot = rootUrl.lastIndexOf(".");
  70609. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  70610. var isDDS = (extension === ".dds");
  70611. var isEnv = (extension === ".env");
  70612. if (isEnv) {
  70613. _this.gammaSpace = false;
  70614. _this._prefiltered = false;
  70615. }
  70616. else {
  70617. _this._prefiltered = prefiltered;
  70618. if (prefiltered) {
  70619. _this.gammaSpace = false;
  70620. }
  70621. }
  70622. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  70623. if (!files) {
  70624. if (!isEnv && !isDDS && !extensions) {
  70625. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  70626. }
  70627. files = [];
  70628. if (extensions) {
  70629. for (var index = 0; index < extensions.length; index++) {
  70630. files.push(rootUrl + extensions[index]);
  70631. }
  70632. }
  70633. }
  70634. _this._files = files;
  70635. if (!_this._texture) {
  70636. if (!scene.useDelayedTextureLoading) {
  70637. if (prefiltered) {
  70638. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  70639. }
  70640. else {
  70641. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  70642. }
  70643. }
  70644. else {
  70645. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  70646. }
  70647. }
  70648. else if (onLoad) {
  70649. if (_this._texture.isReady) {
  70650. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  70651. }
  70652. else {
  70653. _this._texture.onLoadedObservable.add(onLoad);
  70654. }
  70655. }
  70656. return _this;
  70657. }
  70658. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  70659. /**
  70660. * Returns the bounding box size
  70661. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  70662. */
  70663. get: function () {
  70664. return this._boundingBoxSize;
  70665. },
  70666. /**
  70667. * Gets or sets the size of the bounding box associated with the cube texture
  70668. * When defined, the cubemap will switch to local mode
  70669. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  70670. * @example https://www.babylonjs-playground.com/#RNASML
  70671. */
  70672. set: function (value) {
  70673. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  70674. return;
  70675. }
  70676. this._boundingBoxSize = value;
  70677. var scene = this.getScene();
  70678. if (scene) {
  70679. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  70680. }
  70681. },
  70682. enumerable: true,
  70683. configurable: true
  70684. });
  70685. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  70686. /**
  70687. * Gets texture matrix rotation angle around Y axis radians.
  70688. */
  70689. get: function () {
  70690. return this._rotationY;
  70691. },
  70692. /**
  70693. * Sets texture matrix rotation angle around Y axis in radians.
  70694. */
  70695. set: function (value) {
  70696. this._rotationY = value;
  70697. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  70698. },
  70699. enumerable: true,
  70700. configurable: true
  70701. });
  70702. /**
  70703. * Creates a cube texture from an array of image urls
  70704. * @param files defines an array of image urls
  70705. * @param scene defines the hosting scene
  70706. * @param noMipmap specifies if mip maps are not used
  70707. * @returns a cube texture
  70708. */
  70709. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  70710. var rootUrlKey = "";
  70711. files.forEach(function (url) { return rootUrlKey += url; });
  70712. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  70713. };
  70714. /**
  70715. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  70716. * @param url defines the url of the prefiltered texture
  70717. * @param scene defines the scene the texture is attached to
  70718. * @param forcedExtension defines the extension of the file if different from the url
  70719. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  70720. * @return the prefiltered texture
  70721. */
  70722. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  70723. if (forcedExtension === void 0) { forcedExtension = null; }
  70724. if (createPolynomials === void 0) { createPolynomials = true; }
  70725. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  70726. };
  70727. /**
  70728. * Delays loading of the cube texture
  70729. */
  70730. CubeTexture.prototype.delayLoad = function () {
  70731. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  70732. return;
  70733. }
  70734. var scene = this.getScene();
  70735. if (!scene) {
  70736. return;
  70737. }
  70738. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  70739. this._texture = this._getFromCache(this.url, this._noMipmap);
  70740. if (!this._texture) {
  70741. if (this._prefiltered) {
  70742. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  70743. }
  70744. else {
  70745. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  70746. }
  70747. }
  70748. };
  70749. /**
  70750. * Returns the reflection texture matrix
  70751. * @returns the reflection texture matrix
  70752. */
  70753. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  70754. return this._textureMatrix;
  70755. };
  70756. /**
  70757. * Sets the reflection texture matrix
  70758. * @param value Reflection texture matrix
  70759. */
  70760. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  70761. this._textureMatrix = value;
  70762. };
  70763. /**
  70764. * Parses text to create a cube texture
  70765. * @param parsedTexture define the serialized text to read from
  70766. * @param scene defines the hosting scene
  70767. * @param rootUrl defines the root url of the cube texture
  70768. * @returns a cube texture
  70769. */
  70770. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  70771. var texture = BABYLON.SerializationHelper.Parse(function () {
  70772. var prefiltered = false;
  70773. if (parsedTexture.prefiltered) {
  70774. prefiltered = parsedTexture.prefiltered;
  70775. }
  70776. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  70777. }, parsedTexture, scene);
  70778. // Local Cubemaps
  70779. if (parsedTexture.boundingBoxPosition) {
  70780. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  70781. }
  70782. if (parsedTexture.boundingBoxSize) {
  70783. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  70784. }
  70785. // Animations
  70786. if (parsedTexture.animations) {
  70787. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  70788. var parsedAnimation = parsedTexture.animations[animationIndex];
  70789. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  70790. }
  70791. }
  70792. return texture;
  70793. };
  70794. /**
  70795. * Makes a clone, or deep copy, of the cube texture
  70796. * @returns a new cube texture
  70797. */
  70798. CubeTexture.prototype.clone = function () {
  70799. var _this = this;
  70800. return BABYLON.SerializationHelper.Clone(function () {
  70801. var scene = _this.getScene();
  70802. if (!scene) {
  70803. return _this;
  70804. }
  70805. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  70806. }, this);
  70807. };
  70808. __decorate([
  70809. BABYLON.serialize("rotationY")
  70810. ], CubeTexture.prototype, "rotationY", null);
  70811. return CubeTexture;
  70812. }(BABYLON.BaseTexture));
  70813. BABYLON.CubeTexture = CubeTexture;
  70814. })(BABYLON || (BABYLON = {}));
  70815. //# sourceMappingURL=babylon.cubeTexture.js.map
  70816. var BABYLON;
  70817. (function (BABYLON) {
  70818. /**
  70819. * Raw cube texture where the raw buffers are passed in
  70820. */
  70821. var RawCubeTexture = /** @class */ (function (_super) {
  70822. __extends(RawCubeTexture, _super);
  70823. /**
  70824. * Creates a cube texture where the raw buffers are passed in.
  70825. * @param scene defines the scene the texture is attached to
  70826. * @param data defines the array of data to use to create each face
  70827. * @param size defines the size of the textures
  70828. * @param format defines the format of the data
  70829. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  70830. * @param generateMipMaps defines if the engine should generate the mip levels
  70831. * @param invertY defines if data must be stored with Y axis inverted
  70832. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  70833. * @param compression defines the compression used (null by default)
  70834. */
  70835. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  70836. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70837. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70838. if (generateMipMaps === void 0) { generateMipMaps = false; }
  70839. if (invertY === void 0) { invertY = false; }
  70840. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70841. if (compression === void 0) { compression = null; }
  70842. var _this = _super.call(this, "", scene) || this;
  70843. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  70844. return _this;
  70845. }
  70846. /**
  70847. * Updates the raw cube texture.
  70848. * @param data defines the data to store
  70849. * @param format defines the data format
  70850. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  70851. * @param invertY defines if data must be stored with Y axis inverted
  70852. * @param compression defines the compression used (null by default)
  70853. * @param level defines which level of the texture to update
  70854. */
  70855. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  70856. if (compression === void 0) { compression = null; }
  70857. if (level === void 0) { level = 0; }
  70858. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  70859. };
  70860. /**
  70861. * Updates a raw cube texture with RGBD encoded data.
  70862. * @param data defines the array of data [mipmap][face] to use to create each face
  70863. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  70864. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  70865. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  70866. * @returns a promsie that resolves when the operation is complete
  70867. */
  70868. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  70869. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  70870. if (lodScale === void 0) { lodScale = 0.8; }
  70871. if (lodOffset === void 0) { lodOffset = 0; }
  70872. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  70873. };
  70874. /**
  70875. * Clones the raw cube texture.
  70876. * @return a new cube texture
  70877. */
  70878. RawCubeTexture.prototype.clone = function () {
  70879. var _this = this;
  70880. return BABYLON.SerializationHelper.Clone(function () {
  70881. var scene = _this.getScene();
  70882. var internalTexture = _this._texture;
  70883. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  70884. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  70885. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  70886. }
  70887. return texture;
  70888. }, this);
  70889. };
  70890. /** @hidden */
  70891. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  70892. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  70893. internalTexture._bufferViewArrayArray = data;
  70894. internalTexture._lodGenerationScale = lodScale;
  70895. internalTexture._lodGenerationOffset = lodOffset;
  70896. internalTexture._sphericalPolynomial = sphericalPolynomial;
  70897. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  70898. internalTexture.isReady = true;
  70899. });
  70900. };
  70901. return RawCubeTexture;
  70902. }(BABYLON.CubeTexture));
  70903. BABYLON.RawCubeTexture = RawCubeTexture;
  70904. })(BABYLON || (BABYLON = {}));
  70905. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  70906. var BABYLON;
  70907. (function (BABYLON) {
  70908. var RenderTargetTexture = /** @class */ (function (_super) {
  70909. __extends(RenderTargetTexture, _super);
  70910. /**
  70911. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  70912. * or used a shadow, depth texture...
  70913. * @param name The friendly name of the texture
  70914. * @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)
  70915. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  70916. * @param generateMipMaps True if mip maps need to be generated after render.
  70917. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  70918. * @param type The type of the buffer in the RTT (int, half float, float...)
  70919. * @param isCube True if a cube texture needs to be created
  70920. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  70921. * @param generateDepthBuffer True to generate a depth buffer
  70922. * @param generateStencilBuffer True to generate a stencil buffer
  70923. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  70924. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  70925. */
  70926. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  70927. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  70928. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70929. if (isCube === void 0) { isCube = false; }
  70930. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70931. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  70932. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  70933. if (isMulti === void 0) { isMulti = false; }
  70934. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70935. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70936. _this.isCube = isCube;
  70937. _this.renderParticles = true;
  70938. _this.renderSprites = false;
  70939. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  70940. _this.ignoreCameraViewport = false;
  70941. // Events
  70942. /**
  70943. * An event triggered when the texture is unbind.
  70944. */
  70945. _this.onBeforeBindObservable = new BABYLON.Observable();
  70946. /**
  70947. * An event triggered when the texture is unbind.
  70948. */
  70949. _this.onAfterUnbindObservable = new BABYLON.Observable();
  70950. /**
  70951. * An event triggered before rendering the texture
  70952. */
  70953. _this.onBeforeRenderObservable = new BABYLON.Observable();
  70954. /**
  70955. * An event triggered after rendering the texture
  70956. */
  70957. _this.onAfterRenderObservable = new BABYLON.Observable();
  70958. /**
  70959. * An event triggered after the texture clear
  70960. */
  70961. _this.onClearObservable = new BABYLON.Observable();
  70962. _this._currentRefreshId = -1;
  70963. _this._refreshRate = 1;
  70964. _this._samples = 1;
  70965. /**
  70966. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  70967. * It must define where the camera used to render the texture is set
  70968. */
  70969. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  70970. scene = _this.getScene();
  70971. if (!scene) {
  70972. return _this;
  70973. }
  70974. _this.renderList = new Array();
  70975. _this._engine = scene.getEngine();
  70976. _this.name = name;
  70977. _this.isRenderTarget = true;
  70978. _this._initialSizeParameter = size;
  70979. _this._processSizeParameter(size);
  70980. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  70981. });
  70982. _this._generateMipMaps = generateMipMaps ? true : false;
  70983. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  70984. // Rendering groups
  70985. _this._renderingManager = new BABYLON.RenderingManager(scene);
  70986. _this._renderingManager._useSceneAutoClearSetup = true;
  70987. if (isMulti) {
  70988. return _this;
  70989. }
  70990. _this._renderTargetOptions = {
  70991. generateMipMaps: generateMipMaps,
  70992. type: type,
  70993. format: format,
  70994. samplingMode: samplingMode,
  70995. generateDepthBuffer: generateDepthBuffer,
  70996. generateStencilBuffer: generateStencilBuffer
  70997. };
  70998. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  70999. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71000. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71001. }
  71002. if (isCube) {
  71003. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  71004. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  71005. _this._textureMatrix = BABYLON.Matrix.Identity();
  71006. }
  71007. else {
  71008. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  71009. }
  71010. return _this;
  71011. }
  71012. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  71013. get: function () {
  71014. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  71015. },
  71016. enumerable: true,
  71017. configurable: true
  71018. });
  71019. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  71020. get: function () {
  71021. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  71022. },
  71023. enumerable: true,
  71024. configurable: true
  71025. });
  71026. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  71027. get: function () {
  71028. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  71029. },
  71030. enumerable: true,
  71031. configurable: true
  71032. });
  71033. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  71034. /**
  71035. * Use this list to define the list of mesh you want to render.
  71036. */
  71037. get: function () {
  71038. return this._renderList;
  71039. },
  71040. set: function (value) {
  71041. this._renderList = value;
  71042. if (this._renderList) {
  71043. this._hookArray(this._renderList);
  71044. }
  71045. },
  71046. enumerable: true,
  71047. configurable: true
  71048. });
  71049. RenderTargetTexture.prototype._hookArray = function (array) {
  71050. var _this = this;
  71051. var oldPush = array.push;
  71052. array.push = function () {
  71053. var items = [];
  71054. for (var _i = 0; _i < arguments.length; _i++) {
  71055. items[_i] = arguments[_i];
  71056. }
  71057. var wasEmpty = array.length === 0;
  71058. var result = oldPush.apply(array, items);
  71059. if (wasEmpty) {
  71060. _this.getScene().meshes.forEach(function (mesh) {
  71061. mesh._markSubMeshesAsLightDirty();
  71062. });
  71063. }
  71064. return result;
  71065. };
  71066. var oldSplice = array.splice;
  71067. array.splice = function (index, deleteCount) {
  71068. var deleted = oldSplice.apply(array, [index, deleteCount]);
  71069. if (array.length === 0) {
  71070. _this.getScene().meshes.forEach(function (mesh) {
  71071. mesh._markSubMeshesAsLightDirty();
  71072. });
  71073. }
  71074. return deleted;
  71075. };
  71076. };
  71077. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  71078. set: function (callback) {
  71079. if (this._onAfterUnbindObserver) {
  71080. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  71081. }
  71082. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  71083. },
  71084. enumerable: true,
  71085. configurable: true
  71086. });
  71087. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  71088. set: function (callback) {
  71089. if (this._onBeforeRenderObserver) {
  71090. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  71091. }
  71092. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  71093. },
  71094. enumerable: true,
  71095. configurable: true
  71096. });
  71097. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  71098. set: function (callback) {
  71099. if (this._onAfterRenderObserver) {
  71100. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  71101. }
  71102. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  71103. },
  71104. enumerable: true,
  71105. configurable: true
  71106. });
  71107. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  71108. set: function (callback) {
  71109. if (this._onClearObserver) {
  71110. this.onClearObservable.remove(this._onClearObserver);
  71111. }
  71112. this._onClearObserver = this.onClearObservable.add(callback);
  71113. },
  71114. enumerable: true,
  71115. configurable: true
  71116. });
  71117. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  71118. get: function () {
  71119. return this._renderTargetOptions;
  71120. },
  71121. enumerable: true,
  71122. configurable: true
  71123. });
  71124. RenderTargetTexture.prototype._onRatioRescale = function () {
  71125. if (this._sizeRatio) {
  71126. this.resize(this._initialSizeParameter);
  71127. }
  71128. };
  71129. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  71130. get: function () {
  71131. return this._boundingBoxSize;
  71132. },
  71133. /**
  71134. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  71135. * When defined, the cubemap will switch to local mode
  71136. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  71137. * @example https://www.babylonjs-playground.com/#RNASML
  71138. */
  71139. set: function (value) {
  71140. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  71141. return;
  71142. }
  71143. this._boundingBoxSize = value;
  71144. var scene = this.getScene();
  71145. if (scene) {
  71146. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  71147. }
  71148. },
  71149. enumerable: true,
  71150. configurable: true
  71151. });
  71152. /**
  71153. * Creates a depth stencil texture.
  71154. * This is only available in WebGL 2 or with the depth texture extension available.
  71155. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  71156. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  71157. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  71158. */
  71159. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  71160. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  71161. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  71162. if (generateStencil === void 0) { generateStencil = false; }
  71163. if (!this.getScene()) {
  71164. return;
  71165. }
  71166. var engine = this.getScene().getEngine();
  71167. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  71168. bilinearFiltering: bilinearFiltering,
  71169. comparisonFunction: comparisonFunction,
  71170. generateStencil: generateStencil,
  71171. isCube: this.isCube
  71172. });
  71173. engine.setFrameBufferDepthStencilTexture(this);
  71174. };
  71175. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  71176. if (size.ratio) {
  71177. this._sizeRatio = size.ratio;
  71178. this._size = {
  71179. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  71180. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  71181. };
  71182. }
  71183. else {
  71184. this._size = size;
  71185. }
  71186. };
  71187. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  71188. get: function () {
  71189. return this._samples;
  71190. },
  71191. set: function (value) {
  71192. if (this._samples === value) {
  71193. return;
  71194. }
  71195. var scene = this.getScene();
  71196. if (!scene) {
  71197. return;
  71198. }
  71199. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  71200. },
  71201. enumerable: true,
  71202. configurable: true
  71203. });
  71204. /**
  71205. * Resets the refresh counter of the texture and start bak from scratch.
  71206. * Could be usefull to regenerate the texture if it is setup to render only once.
  71207. */
  71208. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  71209. this._currentRefreshId = -1;
  71210. };
  71211. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  71212. /**
  71213. * Define the refresh rate of the texture or the rendering frequency.
  71214. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  71215. */
  71216. get: function () {
  71217. return this._refreshRate;
  71218. },
  71219. set: function (value) {
  71220. this._refreshRate = value;
  71221. this.resetRefreshCounter();
  71222. },
  71223. enumerable: true,
  71224. configurable: true
  71225. });
  71226. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  71227. if (!this._postProcessManager) {
  71228. var scene = this.getScene();
  71229. if (!scene) {
  71230. return;
  71231. }
  71232. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  71233. this._postProcesses = new Array();
  71234. }
  71235. this._postProcesses.push(postProcess);
  71236. this._postProcesses[0].autoClear = false;
  71237. };
  71238. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  71239. if (!this._postProcesses) {
  71240. return;
  71241. }
  71242. if (dispose) {
  71243. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  71244. var postProcess = _a[_i];
  71245. postProcess.dispose();
  71246. }
  71247. }
  71248. this._postProcesses = [];
  71249. };
  71250. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  71251. if (!this._postProcesses) {
  71252. return;
  71253. }
  71254. var index = this._postProcesses.indexOf(postProcess);
  71255. if (index === -1) {
  71256. return;
  71257. }
  71258. this._postProcesses.splice(index, 1);
  71259. if (this._postProcesses.length > 0) {
  71260. this._postProcesses[0].autoClear = false;
  71261. }
  71262. };
  71263. /** @hidden */
  71264. RenderTargetTexture.prototype._shouldRender = function () {
  71265. if (this._currentRefreshId === -1) { // At least render once
  71266. this._currentRefreshId = 1;
  71267. return true;
  71268. }
  71269. if (this.refreshRate === this._currentRefreshId) {
  71270. this._currentRefreshId = 1;
  71271. return true;
  71272. }
  71273. this._currentRefreshId++;
  71274. return false;
  71275. };
  71276. RenderTargetTexture.prototype.getRenderSize = function () {
  71277. if (this._size.width) {
  71278. return this._size.width;
  71279. }
  71280. return this._size;
  71281. };
  71282. RenderTargetTexture.prototype.getRenderWidth = function () {
  71283. if (this._size.width) {
  71284. return this._size.width;
  71285. }
  71286. return this._size;
  71287. };
  71288. RenderTargetTexture.prototype.getRenderHeight = function () {
  71289. if (this._size.width) {
  71290. return this._size.height;
  71291. }
  71292. return this._size;
  71293. };
  71294. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  71295. get: function () {
  71296. return true;
  71297. },
  71298. enumerable: true,
  71299. configurable: true
  71300. });
  71301. RenderTargetTexture.prototype.scale = function (ratio) {
  71302. var newSize = this.getRenderSize() * ratio;
  71303. this.resize(newSize);
  71304. };
  71305. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  71306. if (this.isCube) {
  71307. return this._textureMatrix;
  71308. }
  71309. return _super.prototype.getReflectionTextureMatrix.call(this);
  71310. };
  71311. RenderTargetTexture.prototype.resize = function (size) {
  71312. this.releaseInternalTexture();
  71313. var scene = this.getScene();
  71314. if (!scene) {
  71315. return;
  71316. }
  71317. this._processSizeParameter(size);
  71318. if (this.isCube) {
  71319. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  71320. }
  71321. else {
  71322. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  71323. }
  71324. };
  71325. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  71326. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  71327. if (dumpForDebug === void 0) { dumpForDebug = false; }
  71328. var scene = this.getScene();
  71329. if (!scene) {
  71330. return;
  71331. }
  71332. var engine = scene.getEngine();
  71333. if (this.useCameraPostProcesses !== undefined) {
  71334. useCameraPostProcess = this.useCameraPostProcesses;
  71335. }
  71336. if (this._waitingRenderList) {
  71337. this.renderList = [];
  71338. for (var index = 0; index < this._waitingRenderList.length; index++) {
  71339. var id = this._waitingRenderList[index];
  71340. var mesh_1 = scene.getMeshByID(id);
  71341. if (mesh_1) {
  71342. this.renderList.push(mesh_1);
  71343. }
  71344. }
  71345. delete this._waitingRenderList;
  71346. }
  71347. // Is predicate defined?
  71348. if (this.renderListPredicate) {
  71349. if (this.renderList) {
  71350. this.renderList.splice(0); // Clear previous renderList
  71351. }
  71352. else {
  71353. this.renderList = [];
  71354. }
  71355. var scene = this.getScene();
  71356. if (!scene) {
  71357. return;
  71358. }
  71359. var sceneMeshes = scene.meshes;
  71360. for (var index = 0; index < sceneMeshes.length; index++) {
  71361. var mesh = sceneMeshes[index];
  71362. if (this.renderListPredicate(mesh)) {
  71363. this.renderList.push(mesh);
  71364. }
  71365. }
  71366. }
  71367. this.onBeforeBindObservable.notifyObservers(this);
  71368. // Set custom projection.
  71369. // Needs to be before binding to prevent changing the aspect ratio.
  71370. var camera;
  71371. if (this.activeCamera) {
  71372. camera = this.activeCamera;
  71373. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  71374. if (this.activeCamera !== scene.activeCamera) {
  71375. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  71376. }
  71377. }
  71378. else {
  71379. camera = scene.activeCamera;
  71380. if (camera) {
  71381. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  71382. }
  71383. }
  71384. // Prepare renderingManager
  71385. this._renderingManager.reset();
  71386. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  71387. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  71388. var sceneRenderId = scene.getRenderId();
  71389. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  71390. var mesh = currentRenderList[meshIndex];
  71391. if (mesh) {
  71392. if (!mesh.isReady(this.refreshRate === 0)) {
  71393. this.resetRefreshCounter();
  71394. continue;
  71395. }
  71396. mesh._preActivateForIntermediateRendering(sceneRenderId);
  71397. var isMasked = void 0;
  71398. if (!this.renderList && camera) {
  71399. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  71400. }
  71401. else {
  71402. isMasked = false;
  71403. }
  71404. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  71405. mesh._activate(sceneRenderId);
  71406. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  71407. var subMesh = mesh.subMeshes[subIndex];
  71408. scene._activeIndices.addCount(subMesh.indexCount, false);
  71409. this._renderingManager.dispatch(subMesh, mesh);
  71410. }
  71411. }
  71412. }
  71413. }
  71414. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  71415. var particleSystem = scene.particleSystems[particleIndex];
  71416. var emitter = particleSystem.emitter;
  71417. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  71418. continue;
  71419. }
  71420. if (currentRenderList.indexOf(emitter) >= 0) {
  71421. this._renderingManager.dispatchParticles(particleSystem);
  71422. }
  71423. }
  71424. if (this.isCube) {
  71425. for (var face = 0; face < 6; face++) {
  71426. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  71427. scene.incrementRenderId();
  71428. scene.resetCachedMaterial();
  71429. }
  71430. }
  71431. else {
  71432. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  71433. }
  71434. this.onAfterUnbindObservable.notifyObservers(this);
  71435. if (scene.activeCamera) {
  71436. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  71437. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  71438. }
  71439. engine.setViewport(scene.activeCamera.viewport);
  71440. }
  71441. scene.resetCachedMaterial();
  71442. };
  71443. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  71444. var minimum = 128;
  71445. var x = renderDimension * scale;
  71446. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  71447. // Ensure we don't exceed the render dimension (while staying POT)
  71448. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  71449. };
  71450. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  71451. var _this = this;
  71452. if (!this._texture) {
  71453. return;
  71454. }
  71455. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  71456. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  71457. });
  71458. };
  71459. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  71460. var scene = this.getScene();
  71461. if (!scene) {
  71462. return;
  71463. }
  71464. var engine = scene.getEngine();
  71465. if (!this._texture) {
  71466. return;
  71467. }
  71468. // Bind
  71469. if (this._postProcessManager) {
  71470. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  71471. }
  71472. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  71473. if (this._texture) {
  71474. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  71475. }
  71476. }
  71477. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  71478. // Clear
  71479. if (this.onClearObservable.hasObservers()) {
  71480. this.onClearObservable.notifyObservers(engine);
  71481. }
  71482. else {
  71483. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  71484. }
  71485. if (!this._doNotChangeAspectRatio) {
  71486. scene.updateTransformMatrix(true);
  71487. }
  71488. // Render
  71489. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  71490. if (this._postProcessManager) {
  71491. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  71492. }
  71493. else if (useCameraPostProcess) {
  71494. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  71495. }
  71496. if (!this._doNotChangeAspectRatio) {
  71497. scene.updateTransformMatrix(true);
  71498. }
  71499. // Dump ?
  71500. if (dumpForDebug) {
  71501. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  71502. }
  71503. // Unbind
  71504. if (!this.isCube || faceIndex === 5) {
  71505. if (this.isCube) {
  71506. if (faceIndex === 5) {
  71507. engine.generateMipMapsForCubemap(this._texture);
  71508. }
  71509. }
  71510. this.unbindFrameBuffer(engine, faceIndex);
  71511. }
  71512. else {
  71513. this.onAfterRenderObservable.notifyObservers(faceIndex);
  71514. }
  71515. };
  71516. /**
  71517. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  71518. * This allowed control for front to back rendering or reversly depending of the special needs.
  71519. *
  71520. * @param renderingGroupId The rendering group id corresponding to its index
  71521. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  71522. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  71523. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  71524. */
  71525. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  71526. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  71527. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  71528. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  71529. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  71530. };
  71531. /**
  71532. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  71533. *
  71534. * @param renderingGroupId The rendering group id corresponding to its index
  71535. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  71536. */
  71537. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  71538. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  71539. this._renderingManager._useSceneAutoClearSetup = false;
  71540. };
  71541. RenderTargetTexture.prototype.clone = function () {
  71542. var textureSize = this.getSize();
  71543. 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);
  71544. // Base texture
  71545. newTexture.hasAlpha = this.hasAlpha;
  71546. newTexture.level = this.level;
  71547. // RenderTarget Texture
  71548. newTexture.coordinatesMode = this.coordinatesMode;
  71549. if (this.renderList) {
  71550. newTexture.renderList = this.renderList.slice(0);
  71551. }
  71552. return newTexture;
  71553. };
  71554. RenderTargetTexture.prototype.serialize = function () {
  71555. if (!this.name) {
  71556. return null;
  71557. }
  71558. var serializationObject = _super.prototype.serialize.call(this);
  71559. serializationObject.renderTargetSize = this.getRenderSize();
  71560. serializationObject.renderList = [];
  71561. if (this.renderList) {
  71562. for (var index = 0; index < this.renderList.length; index++) {
  71563. serializationObject.renderList.push(this.renderList[index].id);
  71564. }
  71565. }
  71566. return serializationObject;
  71567. };
  71568. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  71569. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  71570. var objBuffer = this.getInternalTexture();
  71571. var scene = this.getScene();
  71572. if (objBuffer && scene) {
  71573. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  71574. }
  71575. };
  71576. RenderTargetTexture.prototype.dispose = function () {
  71577. if (this._postProcessManager) {
  71578. this._postProcessManager.dispose();
  71579. this._postProcessManager = null;
  71580. }
  71581. this.clearPostProcesses(true);
  71582. if (this._resizeObserver) {
  71583. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  71584. this._resizeObserver = null;
  71585. }
  71586. this.renderList = null;
  71587. // Remove from custom render targets
  71588. var scene = this.getScene();
  71589. if (!scene) {
  71590. return;
  71591. }
  71592. var index = scene.customRenderTargets.indexOf(this);
  71593. if (index >= 0) {
  71594. scene.customRenderTargets.splice(index, 1);
  71595. }
  71596. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  71597. var camera = _a[_i];
  71598. index = camera.customRenderTargets.indexOf(this);
  71599. if (index >= 0) {
  71600. camera.customRenderTargets.splice(index, 1);
  71601. }
  71602. }
  71603. _super.prototype.dispose.call(this);
  71604. };
  71605. /** @hidden */
  71606. RenderTargetTexture.prototype._rebuild = function () {
  71607. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  71608. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  71609. }
  71610. if (this._postProcessManager) {
  71611. this._postProcessManager._rebuild();
  71612. }
  71613. };
  71614. /**
  71615. * Clear the info related to rendering groups preventing retention point in material dispose.
  71616. */
  71617. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  71618. if (this._renderingManager) {
  71619. this._renderingManager.freeRenderingGroups();
  71620. }
  71621. };
  71622. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  71623. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  71624. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  71625. return RenderTargetTexture;
  71626. }(BABYLON.Texture));
  71627. BABYLON.RenderTargetTexture = RenderTargetTexture;
  71628. })(BABYLON || (BABYLON = {}));
  71629. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  71630. var BABYLON;
  71631. (function (BABYLON) {
  71632. ;
  71633. /**
  71634. * A multi render target, like a render target provides the ability to render to a texture.
  71635. * Unlike the render target, it can render to several draw buffers in one draw.
  71636. * This is specially interesting in deferred rendering or for any effects requiring more than
  71637. * just one color from a single pass.
  71638. */
  71639. var MultiRenderTarget = /** @class */ (function (_super) {
  71640. __extends(MultiRenderTarget, _super);
  71641. /**
  71642. * Instantiate a new multi render target texture.
  71643. * A multi render target, like a render target provides the ability to render to a texture.
  71644. * Unlike the render target, it can render to several draw buffers in one draw.
  71645. * This is specially interesting in deferred rendering or for any effects requiring more than
  71646. * just one color from a single pass.
  71647. * @param name Define the name of the texture
  71648. * @param size Define the size of the buffers to render to
  71649. * @param count Define the number of target we are rendering into
  71650. * @param scene Define the scene the texture belongs to
  71651. * @param options Define the options used to create the multi render target
  71652. */
  71653. function MultiRenderTarget(name, size, count, scene, options) {
  71654. var _this = this;
  71655. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  71656. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  71657. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  71658. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  71659. _this._engine = scene.getEngine();
  71660. if (!_this.isSupported) {
  71661. _this.dispose();
  71662. return;
  71663. }
  71664. var types = [];
  71665. var samplingModes = [];
  71666. for (var i = 0; i < count; i++) {
  71667. if (options && options.types && options.types[i] !== undefined) {
  71668. types.push(options.types[i]);
  71669. }
  71670. else {
  71671. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71672. }
  71673. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  71674. samplingModes.push(options.samplingModes[i]);
  71675. }
  71676. else {
  71677. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  71678. }
  71679. }
  71680. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  71681. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  71682. _this._size = size;
  71683. _this._multiRenderTargetOptions = {
  71684. samplingModes: samplingModes,
  71685. generateMipMaps: generateMipMaps,
  71686. generateDepthBuffer: generateDepthBuffer,
  71687. generateStencilBuffer: generateStencilBuffer,
  71688. generateDepthTexture: generateDepthTexture,
  71689. types: types,
  71690. textureCount: count
  71691. };
  71692. _this._createInternalTextures();
  71693. _this._createTextures();
  71694. return _this;
  71695. }
  71696. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  71697. /**
  71698. * Get if draw buffers are currently supported by the used hardware and browser.
  71699. */
  71700. get: function () {
  71701. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  71702. },
  71703. enumerable: true,
  71704. configurable: true
  71705. });
  71706. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  71707. /**
  71708. * Get the list of textures generated by the multi render target.
  71709. */
  71710. get: function () {
  71711. return this._textures;
  71712. },
  71713. enumerable: true,
  71714. configurable: true
  71715. });
  71716. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  71717. /**
  71718. * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set
  71719. */
  71720. get: function () {
  71721. return this._textures[this._textures.length - 1];
  71722. },
  71723. enumerable: true,
  71724. configurable: true
  71725. });
  71726. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  71727. /**
  71728. * Set the wrapping mode on U of all the textures we are rendering to.
  71729. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  71730. */
  71731. set: function (wrap) {
  71732. if (this._textures) {
  71733. for (var i = 0; i < this._textures.length; i++) {
  71734. this._textures[i].wrapU = wrap;
  71735. }
  71736. }
  71737. },
  71738. enumerable: true,
  71739. configurable: true
  71740. });
  71741. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  71742. /**
  71743. * Set the wrapping mode on V of all the textures we are rendering to.
  71744. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  71745. */
  71746. set: function (wrap) {
  71747. if (this._textures) {
  71748. for (var i = 0; i < this._textures.length; i++) {
  71749. this._textures[i].wrapV = wrap;
  71750. }
  71751. }
  71752. },
  71753. enumerable: true,
  71754. configurable: true
  71755. });
  71756. /** @hidden */
  71757. MultiRenderTarget.prototype._rebuild = function () {
  71758. this.releaseInternalTextures();
  71759. this._createInternalTextures();
  71760. for (var i = 0; i < this._internalTextures.length; i++) {
  71761. var texture = this._textures[i];
  71762. texture._texture = this._internalTextures[i];
  71763. }
  71764. // Keeps references to frame buffer and stencil/depth buffer
  71765. this._texture = this._internalTextures[0];
  71766. };
  71767. MultiRenderTarget.prototype._createInternalTextures = function () {
  71768. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  71769. };
  71770. MultiRenderTarget.prototype._createTextures = function () {
  71771. this._textures = [];
  71772. for (var i = 0; i < this._internalTextures.length; i++) {
  71773. var texture = new BABYLON.Texture(null, this.getScene());
  71774. texture._texture = this._internalTextures[i];
  71775. this._textures.push(texture);
  71776. }
  71777. // Keeps references to frame buffer and stencil/depth buffer
  71778. this._texture = this._internalTextures[0];
  71779. };
  71780. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  71781. /**
  71782. * Define the number of samples used if MSAA is enabled.
  71783. */
  71784. get: function () {
  71785. return this._samples;
  71786. },
  71787. set: function (value) {
  71788. if (this._samples === value) {
  71789. return;
  71790. }
  71791. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  71792. },
  71793. enumerable: true,
  71794. configurable: true
  71795. });
  71796. /**
  71797. * Resize all the textures in the multi render target.
  71798. * Be carrefull as it will recreate all the data in the new texture.
  71799. * @param size Define the new size
  71800. */
  71801. MultiRenderTarget.prototype.resize = function (size) {
  71802. this.releaseInternalTextures();
  71803. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  71804. this._createInternalTextures();
  71805. };
  71806. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  71807. var _this = this;
  71808. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  71809. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  71810. });
  71811. };
  71812. /**
  71813. * Dispose the render targets and their associated resources
  71814. */
  71815. MultiRenderTarget.prototype.dispose = function () {
  71816. this.releaseInternalTextures();
  71817. _super.prototype.dispose.call(this);
  71818. };
  71819. /**
  71820. * Release all the underlying texture used as draw buffers.
  71821. */
  71822. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  71823. if (!this._internalTextures) {
  71824. return;
  71825. }
  71826. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  71827. if (this._internalTextures[i] !== undefined) {
  71828. this._internalTextures[i].dispose();
  71829. this._internalTextures.splice(i, 1);
  71830. }
  71831. }
  71832. };
  71833. return MultiRenderTarget;
  71834. }(BABYLON.RenderTargetTexture));
  71835. BABYLON.MultiRenderTarget = MultiRenderTarget;
  71836. })(BABYLON || (BABYLON = {}));
  71837. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  71838. var BABYLON;
  71839. (function (BABYLON) {
  71840. /**
  71841. * Mirror texture can be used to simulate the view from a mirror in a scene.
  71842. * It will dynamically be rendered every frame to adapt to the camera point of view.
  71843. * You can then easily use it as a reflectionTexture on a flat surface.
  71844. * In case the surface is not a plane, please consider relying on reflection probes.
  71845. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  71846. */
  71847. var MirrorTexture = /** @class */ (function (_super) {
  71848. __extends(MirrorTexture, _super);
  71849. /**
  71850. * Instantiates a Mirror Texture.
  71851. * Mirror texture can be used to simulate the view from a mirror in a scene.
  71852. * It will dynamically be rendered every frame to adapt to the camera point of view.
  71853. * You can then easily use it as a reflectionTexture on a flat surface.
  71854. * In case the surface is not a plane, please consider relying on reflection probes.
  71855. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  71856. * @param name
  71857. * @param size
  71858. * @param scene
  71859. * @param generateMipMaps
  71860. * @param type
  71861. * @param samplingMode
  71862. * @param generateDepthBuffer
  71863. */
  71864. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  71865. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71866. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71867. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  71868. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  71869. _this.scene = scene;
  71870. /**
  71871. * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector.
  71872. * It is possible to directly set the mirrorPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the mirrorPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the reflector as stated in the doc.
  71873. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  71874. */
  71875. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  71876. _this._transformMatrix = BABYLON.Matrix.Zero();
  71877. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  71878. _this._adaptiveBlurKernel = 0;
  71879. _this._blurKernelX = 0;
  71880. _this._blurKernelY = 0;
  71881. _this._blurRatio = 1.0;
  71882. _this.ignoreCameraViewport = true;
  71883. _this._updateGammaSpace();
  71884. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  71885. _this._updateGammaSpace;
  71886. });
  71887. _this.onBeforeRenderObservable.add(function () {
  71888. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  71889. _this._savedViewMatrix = scene.getViewMatrix();
  71890. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  71891. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  71892. scene.clipPlane = _this.mirrorPlane;
  71893. scene.getEngine().cullBackFaces = false;
  71894. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  71895. });
  71896. _this.onAfterRenderObservable.add(function () {
  71897. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  71898. scene.getEngine().cullBackFaces = true;
  71899. scene._mirroredCameraPosition = null;
  71900. delete scene.clipPlane;
  71901. });
  71902. return _this;
  71903. }
  71904. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  71905. get: function () {
  71906. return this._blurRatio;
  71907. },
  71908. /**
  71909. * Define the blur ratio used to blur the reflection if needed.
  71910. */
  71911. set: function (value) {
  71912. if (this._blurRatio === value) {
  71913. return;
  71914. }
  71915. this._blurRatio = value;
  71916. this._preparePostProcesses();
  71917. },
  71918. enumerable: true,
  71919. configurable: true
  71920. });
  71921. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  71922. /**
  71923. * Define the adaptive blur kernel used to blur the reflection if needed.
  71924. * This will autocompute the closest best match for the `blurKernel`
  71925. */
  71926. set: function (value) {
  71927. this._adaptiveBlurKernel = value;
  71928. this._autoComputeBlurKernel();
  71929. },
  71930. enumerable: true,
  71931. configurable: true
  71932. });
  71933. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  71934. /**
  71935. * Define the blur kernel used to blur the reflection if needed.
  71936. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  71937. */
  71938. set: function (value) {
  71939. this.blurKernelX = value;
  71940. this.blurKernelY = value;
  71941. },
  71942. enumerable: true,
  71943. configurable: true
  71944. });
  71945. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  71946. get: function () {
  71947. return this._blurKernelX;
  71948. },
  71949. /**
  71950. * Define the blur kernel on the X Axis used to blur the reflection if needed.
  71951. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  71952. */
  71953. set: function (value) {
  71954. if (this._blurKernelX === value) {
  71955. return;
  71956. }
  71957. this._blurKernelX = value;
  71958. this._preparePostProcesses();
  71959. },
  71960. enumerable: true,
  71961. configurable: true
  71962. });
  71963. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  71964. get: function () {
  71965. return this._blurKernelY;
  71966. },
  71967. /**
  71968. * Define the blur kernel on the Y Axis used to blur the reflection if needed.
  71969. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  71970. */
  71971. set: function (value) {
  71972. if (this._blurKernelY === value) {
  71973. return;
  71974. }
  71975. this._blurKernelY = value;
  71976. this._preparePostProcesses();
  71977. },
  71978. enumerable: true,
  71979. configurable: true
  71980. });
  71981. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  71982. var engine = this.getScene().getEngine();
  71983. var dw = this.getRenderWidth() / engine.getRenderWidth();
  71984. var dh = this.getRenderHeight() / engine.getRenderHeight();
  71985. this.blurKernelX = this._adaptiveBlurKernel * dw;
  71986. this.blurKernelY = this._adaptiveBlurKernel * dh;
  71987. };
  71988. MirrorTexture.prototype._onRatioRescale = function () {
  71989. if (this._sizeRatio) {
  71990. this.resize(this._initialSizeParameter);
  71991. if (!this._adaptiveBlurKernel) {
  71992. this._preparePostProcesses();
  71993. }
  71994. }
  71995. if (this._adaptiveBlurKernel) {
  71996. this._autoComputeBlurKernel();
  71997. }
  71998. };
  71999. MirrorTexture.prototype._updateGammaSpace = function () {
  72000. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  72001. };
  72002. MirrorTexture.prototype._preparePostProcesses = function () {
  72003. this.clearPostProcesses(true);
  72004. if (this._blurKernelX && this._blurKernelY) {
  72005. var engine = this.getScene().getEngine();
  72006. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72007. 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);
  72008. this._blurX.autoClear = false;
  72009. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  72010. this._blurX.inputTexture = this._texture;
  72011. }
  72012. else {
  72013. this._blurX.alwaysForcePOT = true;
  72014. }
  72015. 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);
  72016. this._blurY.autoClear = false;
  72017. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  72018. this.addPostProcess(this._blurX);
  72019. this.addPostProcess(this._blurY);
  72020. }
  72021. else {
  72022. if (this._blurY) {
  72023. this.removePostProcess(this._blurY);
  72024. this._blurY.dispose();
  72025. this._blurY = null;
  72026. }
  72027. if (this._blurX) {
  72028. this.removePostProcess(this._blurX);
  72029. this._blurX.dispose();
  72030. this._blurX = null;
  72031. }
  72032. }
  72033. };
  72034. /**
  72035. * Clone the mirror texture.
  72036. * @returns the cloned texture
  72037. */
  72038. MirrorTexture.prototype.clone = function () {
  72039. var scene = this.getScene();
  72040. if (!scene) {
  72041. return this;
  72042. }
  72043. var textureSize = this.getSize();
  72044. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  72045. // Base texture
  72046. newTexture.hasAlpha = this.hasAlpha;
  72047. newTexture.level = this.level;
  72048. // Mirror Texture
  72049. newTexture.mirrorPlane = this.mirrorPlane.clone();
  72050. if (this.renderList) {
  72051. newTexture.renderList = this.renderList.slice(0);
  72052. }
  72053. return newTexture;
  72054. };
  72055. /**
  72056. * Serialize the texture to a JSON representation you could use in Parse later on
  72057. * @returns the serialized JSON representation
  72058. */
  72059. MirrorTexture.prototype.serialize = function () {
  72060. if (!this.name) {
  72061. return null;
  72062. }
  72063. var serializationObject = _super.prototype.serialize.call(this);
  72064. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  72065. return serializationObject;
  72066. };
  72067. /**
  72068. * Dispose the texture and release its associated resources.
  72069. */
  72070. MirrorTexture.prototype.dispose = function () {
  72071. _super.prototype.dispose.call(this);
  72072. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  72073. };
  72074. return MirrorTexture;
  72075. }(BABYLON.RenderTargetTexture));
  72076. BABYLON.MirrorTexture = MirrorTexture;
  72077. })(BABYLON || (BABYLON = {}));
  72078. //# sourceMappingURL=babylon.mirrorTexture.js.map
  72079. var BABYLON;
  72080. (function (BABYLON) {
  72081. /**
  72082. * Creates a refraction texture used by refraction channel of the standard material.
  72083. * It is like a mirror but to see through a material.
  72084. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  72085. */
  72086. var RefractionTexture = /** @class */ (function (_super) {
  72087. __extends(RefractionTexture, _super);
  72088. /**
  72089. * Creates a refraction texture used by refraction channel of the standard material.
  72090. * It is like a mirror but to see through a material.
  72091. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  72092. * @param name Define the texture name
  72093. * @param size Define the size of the underlying texture
  72094. * @param scene Define the scene the refraction belongs to
  72095. * @param generateMipMaps Define if we need to generate mips level for the refraction
  72096. */
  72097. function RefractionTexture(name, size, scene, generateMipMaps) {
  72098. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  72099. /**
  72100. * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor.
  72101. * It is possible to directly set the refractionPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the refractionPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the refractor as stated in the doc.
  72102. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  72103. */
  72104. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  72105. /**
  72106. * Define how deep under the surface we should see.
  72107. */
  72108. _this.depth = 2.0;
  72109. _this.onBeforeRenderObservable.add(function () {
  72110. scene.clipPlane = _this.refractionPlane;
  72111. });
  72112. _this.onAfterRenderObservable.add(function () {
  72113. delete scene.clipPlane;
  72114. });
  72115. return _this;
  72116. }
  72117. /**
  72118. * Clone the refraction texture.
  72119. * @returns the cloned texture
  72120. */
  72121. RefractionTexture.prototype.clone = function () {
  72122. var scene = this.getScene();
  72123. if (!scene) {
  72124. return this;
  72125. }
  72126. var textureSize = this.getSize();
  72127. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  72128. // Base texture
  72129. newTexture.hasAlpha = this.hasAlpha;
  72130. newTexture.level = this.level;
  72131. // Refraction Texture
  72132. newTexture.refractionPlane = this.refractionPlane.clone();
  72133. if (this.renderList) {
  72134. newTexture.renderList = this.renderList.slice(0);
  72135. }
  72136. newTexture.depth = this.depth;
  72137. return newTexture;
  72138. };
  72139. /**
  72140. * Serialize the texture to a JSON representation you could use in Parse later on
  72141. * @returns the serialized JSON representation
  72142. */
  72143. RefractionTexture.prototype.serialize = function () {
  72144. if (!this.name) {
  72145. return null;
  72146. }
  72147. var serializationObject = _super.prototype.serialize.call(this);
  72148. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  72149. serializationObject.depth = this.depth;
  72150. return serializationObject;
  72151. };
  72152. return RefractionTexture;
  72153. }(BABYLON.RenderTargetTexture));
  72154. BABYLON.RefractionTexture = RefractionTexture;
  72155. })(BABYLON || (BABYLON = {}));
  72156. //# sourceMappingURL=babylon.refractionTexture.js.map
  72157. var BABYLON;
  72158. (function (BABYLON) {
  72159. /**
  72160. * A class extending {BABYLON.Texture} allowing drawing on a texture
  72161. * @see http://doc.babylonjs.com/how_to/dynamictexture
  72162. */
  72163. var DynamicTexture = /** @class */ (function (_super) {
  72164. __extends(DynamicTexture, _super);
  72165. /**
  72166. * Creates a {BABYLON.DynamicTexture}
  72167. * @param name defines the name of the texture
  72168. * @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
  72169. * @param scene defines the scene where you want the texture
  72170. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  72171. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  72172. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  72173. */
  72174. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  72175. if (scene === void 0) { scene = null; }
  72176. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72177. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  72178. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  72179. _this.name = name;
  72180. _this._engine = _this.getScene().getEngine();
  72181. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72182. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72183. _this._generateMipMaps = generateMipMaps;
  72184. if (options.getContext) {
  72185. _this._canvas = options;
  72186. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  72187. }
  72188. else {
  72189. _this._canvas = document.createElement("canvas");
  72190. if (options.width || options.width === 0) {
  72191. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  72192. }
  72193. else {
  72194. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  72195. }
  72196. }
  72197. var textureSize = _this.getSize();
  72198. _this._canvas.width = textureSize.width;
  72199. _this._canvas.height = textureSize.height;
  72200. _this._context = _this._canvas.getContext("2d");
  72201. return _this;
  72202. }
  72203. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  72204. /**
  72205. * Gets the current state of canRescale
  72206. */
  72207. get: function () {
  72208. return true;
  72209. },
  72210. enumerable: true,
  72211. configurable: true
  72212. });
  72213. DynamicTexture.prototype._recreate = function (textureSize) {
  72214. this._canvas.width = textureSize.width;
  72215. this._canvas.height = textureSize.height;
  72216. this.releaseInternalTexture();
  72217. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  72218. };
  72219. /**
  72220. * Scales the texture
  72221. * @param ratio the scale factor to apply to both width and height
  72222. */
  72223. DynamicTexture.prototype.scale = function (ratio) {
  72224. var textureSize = this.getSize();
  72225. textureSize.width *= ratio;
  72226. textureSize.height *= ratio;
  72227. this._recreate(textureSize);
  72228. };
  72229. /**
  72230. * Resizes the texture
  72231. * @param width the new width
  72232. * @param height the new height
  72233. */
  72234. DynamicTexture.prototype.scaleTo = function (width, height) {
  72235. var textureSize = this.getSize();
  72236. textureSize.width = width;
  72237. textureSize.height = height;
  72238. this._recreate(textureSize);
  72239. };
  72240. /**
  72241. * Gets the context of the canvas used by the texture
  72242. * @returns the canvas context of the dynamic texture
  72243. */
  72244. DynamicTexture.prototype.getContext = function () {
  72245. return this._context;
  72246. };
  72247. /**
  72248. * Clears the texture
  72249. */
  72250. DynamicTexture.prototype.clear = function () {
  72251. var size = this.getSize();
  72252. this._context.fillRect(0, 0, size.width, size.height);
  72253. };
  72254. /**
  72255. * Updates the texture
  72256. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  72257. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  72258. */
  72259. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  72260. if (premulAlpha === void 0) { premulAlpha = false; }
  72261. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  72262. };
  72263. /**
  72264. * Draws text onto the texture
  72265. * @param text defines the text to be drawn
  72266. * @param x defines the placement of the text from the left
  72267. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  72268. * @param font defines the font to be used with font-style, font-size, font-name
  72269. * @param color defines the color used for the text
  72270. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  72271. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  72272. * @param update defines whether texture is immediately update (default is true)
  72273. */
  72274. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  72275. if (update === void 0) { update = true; }
  72276. var size = this.getSize();
  72277. if (clearColor) {
  72278. this._context.fillStyle = clearColor;
  72279. this._context.fillRect(0, 0, size.width, size.height);
  72280. }
  72281. this._context.font = font;
  72282. if (x === null || x === undefined) {
  72283. var textSize = this._context.measureText(text);
  72284. x = (size.width - textSize.width) / 2;
  72285. }
  72286. if (y === null || y === undefined) {
  72287. var fontSize = parseInt((font.replace(/\D/g, '')));
  72288. y = (size.height / 2) + (fontSize / 3.65);
  72289. }
  72290. this._context.fillStyle = color;
  72291. this._context.fillText(text, x, y);
  72292. if (update) {
  72293. this.update(invertY);
  72294. }
  72295. };
  72296. /**
  72297. * Clones the texture
  72298. * @returns the clone of the texture.
  72299. */
  72300. DynamicTexture.prototype.clone = function () {
  72301. var scene = this.getScene();
  72302. if (!scene) {
  72303. return this;
  72304. }
  72305. var textureSize = this.getSize();
  72306. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  72307. // Base texture
  72308. newTexture.hasAlpha = this.hasAlpha;
  72309. newTexture.level = this.level;
  72310. // Dynamic Texture
  72311. newTexture.wrapU = this.wrapU;
  72312. newTexture.wrapV = this.wrapV;
  72313. return newTexture;
  72314. };
  72315. /**
  72316. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  72317. * @returns a serialized dynamic texture object
  72318. */
  72319. DynamicTexture.prototype.serialize = function () {
  72320. var scene = this.getScene();
  72321. if (scene && !scene.isReady()) {
  72322. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  72323. }
  72324. var serializationObject = _super.prototype.serialize.call(this);
  72325. serializationObject.base64String = this._canvas.toDataURL();
  72326. serializationObject.invertY = this._invertY;
  72327. serializationObject.samplingMode = this.samplingMode;
  72328. return serializationObject;
  72329. };
  72330. /** @hidden */
  72331. DynamicTexture.prototype._rebuild = function () {
  72332. this.update();
  72333. };
  72334. return DynamicTexture;
  72335. }(BABYLON.Texture));
  72336. BABYLON.DynamicTexture = DynamicTexture;
  72337. })(BABYLON || (BABYLON = {}));
  72338. //# sourceMappingURL=babylon.dynamicTexture.js.map
  72339. var BABYLON;
  72340. (function (BABYLON) {
  72341. /**
  72342. * If you want to display a video in your scene, this is the special texture for that.
  72343. * This special texture works similar to other textures, with the exception of a few parameters.
  72344. * @see https://doc.babylonjs.com/how_to/video_texture
  72345. */
  72346. var VideoTexture = /** @class */ (function (_super) {
  72347. __extends(VideoTexture, _super);
  72348. /**
  72349. * Creates a video texture.
  72350. * If you want to display a video in your scene, this is the special texture for that.
  72351. * This special texture works similar to other textures, with the exception of a few parameters.
  72352. * @see https://doc.babylonjs.com/how_to/video_texture
  72353. * @param {string | null} name optional name, will detect from video source, if not defined
  72354. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  72355. * @param {BABYLON.Scene} scene is obviously the current scene.
  72356. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  72357. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  72358. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  72359. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  72360. */
  72361. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  72362. if (generateMipMaps === void 0) { generateMipMaps = false; }
  72363. if (invertY === void 0) { invertY = false; }
  72364. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72365. if (settings === void 0) { settings = {
  72366. autoPlay: true,
  72367. loop: true,
  72368. autoUpdateTexture: true,
  72369. }; }
  72370. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  72371. _this._onUserActionRequestedObservable = null;
  72372. _this._stillImageCaptured = false;
  72373. _this._poster = false;
  72374. _this._createInternalTexture = function () {
  72375. if (_this._texture != null) {
  72376. if (_this._poster) {
  72377. _this._texture.dispose();
  72378. _this._poster = false;
  72379. }
  72380. else {
  72381. return;
  72382. }
  72383. }
  72384. if (!_this._engine.needPOTTextures ||
  72385. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  72386. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72387. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72388. }
  72389. else {
  72390. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72391. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72392. _this._generateMipMaps = false;
  72393. }
  72394. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  72395. if (!_this.video.autoplay) {
  72396. var oldHandler_1 = _this.video.onplaying;
  72397. var error_1 = false;
  72398. _this.video.onplaying = function () {
  72399. _this.video.onplaying = oldHandler_1;
  72400. _this._texture.isReady = true;
  72401. _this._updateInternalTexture();
  72402. if (!error_1) {
  72403. _this.video.pause();
  72404. }
  72405. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  72406. _this.onLoadObservable.notifyObservers(_this);
  72407. }
  72408. };
  72409. var playing = _this.video.play();
  72410. if (playing) {
  72411. playing.then(function () {
  72412. // Everything is good.
  72413. })
  72414. .catch(function () {
  72415. error_1 = true;
  72416. // On Chrome for instance, new policies might prevent playing without user interaction.
  72417. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  72418. _this._onUserActionRequestedObservable.notifyObservers(_this);
  72419. }
  72420. });
  72421. }
  72422. else {
  72423. _this.video.onplaying = oldHandler_1;
  72424. _this._texture.isReady = true;
  72425. _this._updateInternalTexture();
  72426. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  72427. _this.onLoadObservable.notifyObservers(_this);
  72428. }
  72429. }
  72430. }
  72431. else {
  72432. _this._texture.isReady = true;
  72433. _this._updateInternalTexture();
  72434. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  72435. _this.onLoadObservable.notifyObservers(_this);
  72436. }
  72437. }
  72438. };
  72439. _this.reset = function () {
  72440. if (_this._texture == null) {
  72441. return;
  72442. }
  72443. if (!_this._poster) {
  72444. _this._texture.dispose();
  72445. _this._texture = null;
  72446. }
  72447. };
  72448. _this._updateInternalTexture = function (e) {
  72449. if (_this._texture == null || !_this._texture.isReady) {
  72450. return;
  72451. }
  72452. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  72453. return;
  72454. }
  72455. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  72456. };
  72457. _this._engine = _this.getScene().getEngine();
  72458. _this._generateMipMaps = generateMipMaps;
  72459. _this._samplingMode = samplingMode;
  72460. _this.autoUpdateTexture = settings.autoUpdateTexture;
  72461. _this.name = name || _this._getName(src);
  72462. _this.video = _this._getVideo(src);
  72463. if (settings.poster) {
  72464. _this.video.poster = settings.poster;
  72465. }
  72466. if (settings.autoPlay !== undefined) {
  72467. _this.video.autoplay = settings.autoPlay;
  72468. }
  72469. if (settings.loop !== undefined) {
  72470. _this.video.loop = settings.loop;
  72471. }
  72472. _this.video.setAttribute("playsinline", "");
  72473. _this.video.addEventListener("canplay", _this._createInternalTexture);
  72474. _this.video.addEventListener("paused", _this._updateInternalTexture);
  72475. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  72476. _this.video.addEventListener("emptied", _this.reset);
  72477. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  72478. _this._createInternalTexture();
  72479. }
  72480. if (settings.poster) {
  72481. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  72482. _this._poster = true;
  72483. }
  72484. return _this;
  72485. }
  72486. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  72487. /**
  72488. * Event triggerd when a dom action is required by the user to play the video.
  72489. * This happens due to recent changes in browser policies preventing video to auto start.
  72490. */
  72491. get: function () {
  72492. if (!this._onUserActionRequestedObservable) {
  72493. this._onUserActionRequestedObservable = new BABYLON.Observable();
  72494. }
  72495. return this._onUserActionRequestedObservable;
  72496. },
  72497. enumerable: true,
  72498. configurable: true
  72499. });
  72500. VideoTexture.prototype._getName = function (src) {
  72501. if (src instanceof HTMLVideoElement) {
  72502. return src.currentSrc;
  72503. }
  72504. if (typeof src === "object") {
  72505. return src.toString();
  72506. }
  72507. return src;
  72508. };
  72509. ;
  72510. VideoTexture.prototype._getVideo = function (src) {
  72511. if (src instanceof HTMLVideoElement) {
  72512. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  72513. return src;
  72514. }
  72515. var video = document.createElement("video");
  72516. if (typeof src === "string") {
  72517. BABYLON.Tools.SetCorsBehavior(src, video);
  72518. video.src = src;
  72519. }
  72520. else {
  72521. BABYLON.Tools.SetCorsBehavior(src[0], video);
  72522. src.forEach(function (url) {
  72523. var source = document.createElement("source");
  72524. source.src = url;
  72525. video.appendChild(source);
  72526. });
  72527. }
  72528. return video;
  72529. };
  72530. ;
  72531. /**
  72532. * @hidden Internal method to initiate `update`.
  72533. */
  72534. VideoTexture.prototype._rebuild = function () {
  72535. this.update();
  72536. };
  72537. /**
  72538. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  72539. */
  72540. VideoTexture.prototype.update = function () {
  72541. if (!this.autoUpdateTexture) {
  72542. // Expecting user to call `updateTexture` manually
  72543. return;
  72544. }
  72545. this.updateTexture(true);
  72546. };
  72547. /**
  72548. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  72549. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  72550. */
  72551. VideoTexture.prototype.updateTexture = function (isVisible) {
  72552. if (!isVisible) {
  72553. return;
  72554. }
  72555. if (this.video.paused && this._stillImageCaptured) {
  72556. return;
  72557. }
  72558. this._stillImageCaptured = true;
  72559. this._updateInternalTexture();
  72560. };
  72561. /**
  72562. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  72563. * @param url New url.
  72564. */
  72565. VideoTexture.prototype.updateURL = function (url) {
  72566. this.video.src = url;
  72567. };
  72568. /**
  72569. * Dispose the texture and release its associated resources.
  72570. */
  72571. VideoTexture.prototype.dispose = function () {
  72572. _super.prototype.dispose.call(this);
  72573. if (this._onUserActionRequestedObservable) {
  72574. this._onUserActionRequestedObservable.clear();
  72575. this._onUserActionRequestedObservable = null;
  72576. }
  72577. this.video.removeEventListener("canplay", this._createInternalTexture);
  72578. this.video.removeEventListener("paused", this._updateInternalTexture);
  72579. this.video.removeEventListener("seeked", this._updateInternalTexture);
  72580. this.video.removeEventListener("emptied", this.reset);
  72581. this.video.pause();
  72582. };
  72583. /**
  72584. * Creates a video texture straight from your WebCam video feed.
  72585. * @param scene Define the scene the texture should be created in
  72586. * @param onReady Define a callback to triggered once the texture will be ready
  72587. * @param constraints Define the constraints to use to create the web cam feed from WebRTC
  72588. */
  72589. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  72590. var video = document.createElement("video");
  72591. video.setAttribute('autoplay', '');
  72592. video.setAttribute('muted', '');
  72593. video.setAttribute('playsinline', '');
  72594. var constraintsDeviceId;
  72595. if (constraints && constraints.deviceId) {
  72596. constraintsDeviceId = {
  72597. exact: constraints.deviceId,
  72598. };
  72599. }
  72600. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  72601. if (navigator.mediaDevices) {
  72602. navigator.mediaDevices.getUserMedia({ video: constraints })
  72603. .then(function (stream) {
  72604. if (video.mozSrcObject !== undefined) {
  72605. // hack for Firefox < 19
  72606. video.mozSrcObject = stream;
  72607. }
  72608. else {
  72609. video.srcObject = stream;
  72610. }
  72611. var onPlaying = function () {
  72612. if (onReady) {
  72613. onReady(new VideoTexture("video", video, scene, true, true));
  72614. }
  72615. video.removeEventListener("playing", onPlaying);
  72616. };
  72617. video.addEventListener("playing", onPlaying);
  72618. video.play();
  72619. })
  72620. .catch(function (err) {
  72621. BABYLON.Tools.Error(err.name);
  72622. });
  72623. }
  72624. else {
  72625. navigator.getUserMedia =
  72626. navigator.getUserMedia ||
  72627. navigator.webkitGetUserMedia ||
  72628. navigator.mozGetUserMedia ||
  72629. navigator.msGetUserMedia;
  72630. if (navigator.getUserMedia) {
  72631. navigator.getUserMedia({
  72632. video: {
  72633. deviceId: constraintsDeviceId,
  72634. width: {
  72635. min: (constraints && constraints.minWidth) || 256,
  72636. max: (constraints && constraints.maxWidth) || 640,
  72637. },
  72638. height: {
  72639. min: (constraints && constraints.minHeight) || 256,
  72640. max: (constraints && constraints.maxHeight) || 480,
  72641. },
  72642. },
  72643. }, function (stream) {
  72644. if (video.mozSrcObject !== undefined) {
  72645. // hack for Firefox < 19
  72646. video.mozSrcObject = stream;
  72647. }
  72648. else {
  72649. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  72650. }
  72651. video.play();
  72652. if (onReady) {
  72653. onReady(new VideoTexture("video", video, scene, true, true));
  72654. }
  72655. }, function (e) {
  72656. BABYLON.Tools.Error(e.name);
  72657. });
  72658. }
  72659. }
  72660. };
  72661. return VideoTexture;
  72662. }(BABYLON.Texture));
  72663. BABYLON.VideoTexture = VideoTexture;
  72664. })(BABYLON || (BABYLON = {}));
  72665. //# sourceMappingURL=babylon.videoTexture.js.map
  72666. var BABYLON;
  72667. (function (BABYLON) {
  72668. /**
  72669. * Raw texture can help creating a texture directly from an array of data.
  72670. * This can be super useful if you either get the data from an uncompressed source or
  72671. * if you wish to create your texture pixel by pixel.
  72672. */
  72673. var RawTexture = /** @class */ (function (_super) {
  72674. __extends(RawTexture, _super);
  72675. /**
  72676. * Instantiates a new RawTexture.
  72677. * Raw texture can help creating a texture directly from an array of data.
  72678. * This can be super useful if you either get the data from an uncompressed source or
  72679. * if you wish to create your texture pixel by pixel.
  72680. * @param data define the array of data to use to create the texture
  72681. * @param width define the width of the texture
  72682. * @param height define the height of the texture
  72683. * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  72684. * @param scene define the scene the texture belongs to
  72685. * @param generateMipMaps define whether mip maps should be generated or not
  72686. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72687. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72688. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  72689. */
  72690. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  72691. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72692. if (invertY === void 0) { invertY = false; }
  72693. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72694. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72695. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  72696. _this.format = format;
  72697. _this._engine = scene.getEngine();
  72698. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  72699. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72700. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72701. return _this;
  72702. }
  72703. /**
  72704. * Updates the texture underlying data.
  72705. * @param data Define the new data of the texture
  72706. */
  72707. RawTexture.prototype.update = function (data) {
  72708. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  72709. };
  72710. /**
  72711. * Creates a luminance texture from some data.
  72712. * @param data Define the texture data
  72713. * @param width Define the width of the texture
  72714. * @param height Define the height of the texture
  72715. * @param scene Define the scene the texture belongs to
  72716. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72717. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72718. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72719. * @returns the luminance texture
  72720. */
  72721. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  72722. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72723. if (invertY === void 0) { invertY = false; }
  72724. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72725. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  72726. };
  72727. /**
  72728. * Creates a luminance alpha texture from some data.
  72729. * @param data Define the texture data
  72730. * @param width Define the width of the texture
  72731. * @param height Define the height of the texture
  72732. * @param scene Define the scene the texture belongs to
  72733. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72734. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72735. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72736. * @returns the luminance alpha texture
  72737. */
  72738. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  72739. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72740. if (invertY === void 0) { invertY = false; }
  72741. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72742. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  72743. };
  72744. /**
  72745. * Creates an alpha texture from some data.
  72746. * @param data Define the texture data
  72747. * @param width Define the width of the texture
  72748. * @param height Define the height of the texture
  72749. * @param scene Define the scene the texture belongs to
  72750. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72751. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72752. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72753. * @returns the alpha texture
  72754. */
  72755. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  72756. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72757. if (invertY === void 0) { invertY = false; }
  72758. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72759. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  72760. };
  72761. /**
  72762. * Creates a RGB texture from some data.
  72763. * @param data Define the texture data
  72764. * @param width Define the width of the texture
  72765. * @param height Define the height of the texture
  72766. * @param scene Define the scene the texture belongs to
  72767. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72768. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72769. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72770. * @returns the RGB alpha texture
  72771. */
  72772. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  72773. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72774. if (invertY === void 0) { invertY = false; }
  72775. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72776. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72777. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  72778. };
  72779. /**
  72780. * Creates a RGBA texture from some data.
  72781. * @param data Define the texture data
  72782. * @param width Define the width of the texture
  72783. * @param height Define the height of the texture
  72784. * @param scene Define the scene the texture belongs to
  72785. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72786. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72787. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72788. * @returns the RGBA texture
  72789. */
  72790. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  72791. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72792. if (invertY === void 0) { invertY = false; }
  72793. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72794. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72795. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  72796. };
  72797. /**
  72798. * Creates a R texture from some data.
  72799. * @param data Define the texture data
  72800. * @param width Define the width of the texture
  72801. * @param height Define the height of the texture
  72802. * @param scene Define the scene the texture belongs to
  72803. * @param generateMipMaps Define whether or not to create mip maps for the texture
  72804. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  72805. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  72806. * @returns the R texture
  72807. */
  72808. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  72809. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72810. if (invertY === void 0) { invertY = false; }
  72811. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72812. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72813. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  72814. };
  72815. return RawTexture;
  72816. }(BABYLON.Texture));
  72817. BABYLON.RawTexture = RawTexture;
  72818. })(BABYLON || (BABYLON = {}));
  72819. //# sourceMappingURL=babylon.rawTexture.js.map
  72820. var BABYLON;
  72821. (function (BABYLON) {
  72822. /**
  72823. * Class used to store 3D textures containing user data
  72824. */
  72825. var RawTexture3D = /** @class */ (function (_super) {
  72826. __extends(RawTexture3D, _super);
  72827. /**
  72828. * Create a new RawTexture3D
  72829. * @param data defines the data of the texture
  72830. * @param width defines the width of the texture
  72831. * @param height defines the height of the texture
  72832. * @param depth defines the depth of the texture
  72833. * @param format defines the texture format to use
  72834. * @param scene defines the hosting scene
  72835. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  72836. * @param invertY defines if texture must be stored with Y axis inverted
  72837. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  72838. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  72839. */
  72840. function RawTexture3D(data, width, height, depth,
  72841. /** Gets or sets the texture format to use */
  72842. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  72843. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72844. if (invertY === void 0) { invertY = false; }
  72845. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72846. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72847. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  72848. _this.format = format;
  72849. _this._engine = scene.getEngine();
  72850. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  72851. _this.is3D = true;
  72852. return _this;
  72853. }
  72854. /**
  72855. * Update the texture with new data
  72856. * @param data defines the data to store in the texture
  72857. */
  72858. RawTexture3D.prototype.update = function (data) {
  72859. if (!this._texture) {
  72860. return;
  72861. }
  72862. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  72863. };
  72864. return RawTexture3D;
  72865. }(BABYLON.Texture));
  72866. BABYLON.RawTexture3D = RawTexture3D;
  72867. })(BABYLON || (BABYLON = {}));
  72868. //# sourceMappingURL=babylon.rawTexture3D.js.map
  72869. var BABYLON;
  72870. (function (BABYLON) {
  72871. /**
  72872. * PostProcessManager is used to manage one or more post processes or post process pipelines
  72873. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  72874. */
  72875. var PostProcessManager = /** @class */ (function () {
  72876. /**
  72877. * Creates a new instance PostProcess
  72878. * @param scene The scene that the post process is associated with.
  72879. */
  72880. function PostProcessManager(scene) {
  72881. this._vertexBuffers = {};
  72882. this._scene = scene;
  72883. }
  72884. PostProcessManager.prototype._prepareBuffers = function () {
  72885. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  72886. return;
  72887. }
  72888. // VBO
  72889. var vertices = [];
  72890. vertices.push(1, 1);
  72891. vertices.push(-1, 1);
  72892. vertices.push(-1, -1);
  72893. vertices.push(1, -1);
  72894. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72895. this._buildIndexBuffer();
  72896. };
  72897. PostProcessManager.prototype._buildIndexBuffer = function () {
  72898. // Indices
  72899. var indices = [];
  72900. indices.push(0);
  72901. indices.push(1);
  72902. indices.push(2);
  72903. indices.push(0);
  72904. indices.push(2);
  72905. indices.push(3);
  72906. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  72907. };
  72908. /**
  72909. * Rebuilds the vertex buffers of the manager.
  72910. * @hidden
  72911. */
  72912. PostProcessManager.prototype._rebuild = function () {
  72913. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72914. if (!vb) {
  72915. return;
  72916. }
  72917. vb._rebuild();
  72918. this._buildIndexBuffer();
  72919. };
  72920. // Methods
  72921. /**
  72922. * Prepares a frame to be run through a post process.
  72923. * @param sourceTexture The input texture to the post procesess. (default: null)
  72924. * @param postProcesses An array of post processes to be run. (default: null)
  72925. * @returns True if the post processes were able to be run.
  72926. * @hidden
  72927. */
  72928. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  72929. if (sourceTexture === void 0) { sourceTexture = null; }
  72930. if (postProcesses === void 0) { postProcesses = null; }
  72931. var camera = this._scene.activeCamera;
  72932. if (!camera) {
  72933. return false;
  72934. }
  72935. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  72936. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  72937. return false;
  72938. }
  72939. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  72940. return true;
  72941. };
  72942. /**
  72943. * Manually render a set of post processes to a texture.
  72944. * @param postProcesses An array of post processes to be run.
  72945. * @param targetTexture The target texture to render to.
  72946. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  72947. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  72948. * @param lodLevel defines which lod of the texture to render to
  72949. */
  72950. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  72951. if (targetTexture === void 0) { targetTexture = null; }
  72952. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  72953. if (faceIndex === void 0) { faceIndex = 0; }
  72954. if (lodLevel === void 0) { lodLevel = 0; }
  72955. var engine = this._scene.getEngine();
  72956. for (var index = 0; index < postProcesses.length; index++) {
  72957. if (index < postProcesses.length - 1) {
  72958. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  72959. }
  72960. else {
  72961. if (targetTexture) {
  72962. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  72963. }
  72964. else {
  72965. engine.restoreDefaultFramebuffer();
  72966. }
  72967. }
  72968. var pp = postProcesses[index];
  72969. var effect = pp.apply();
  72970. if (effect) {
  72971. pp.onBeforeRenderObservable.notifyObservers(effect);
  72972. // VBOs
  72973. this._prepareBuffers();
  72974. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  72975. // Draw order
  72976. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  72977. pp.onAfterRenderObservable.notifyObservers(effect);
  72978. }
  72979. }
  72980. // Restore depth buffer
  72981. engine.setDepthBuffer(true);
  72982. engine.setDepthWrite(true);
  72983. };
  72984. /**
  72985. * Finalize the result of the output of the postprocesses.
  72986. * @param doNotPresent If true the result will not be displayed to the screen.
  72987. * @param targetTexture The target texture to render to.
  72988. * @param faceIndex The index of the face to bind the target texture to.
  72989. * @param postProcesses The array of post processes to render.
  72990. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  72991. * @hidden
  72992. */
  72993. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  72994. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  72995. var camera = this._scene.activeCamera;
  72996. if (!camera) {
  72997. return;
  72998. }
  72999. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  73000. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  73001. return;
  73002. }
  73003. var engine = this._scene.getEngine();
  73004. for (var index = 0, len = postProcesses.length; index < len; index++) {
  73005. var pp = postProcesses[index];
  73006. if (index < len - 1) {
  73007. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  73008. }
  73009. else {
  73010. if (targetTexture) {
  73011. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  73012. pp._outputTexture = targetTexture;
  73013. }
  73014. else {
  73015. engine.restoreDefaultFramebuffer();
  73016. pp._outputTexture = null;
  73017. }
  73018. }
  73019. if (doNotPresent) {
  73020. break;
  73021. }
  73022. var effect = pp.apply();
  73023. if (effect) {
  73024. pp.onBeforeRenderObservable.notifyObservers(effect);
  73025. // VBOs
  73026. this._prepareBuffers();
  73027. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  73028. // Draw order
  73029. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73030. pp.onAfterRenderObservable.notifyObservers(effect);
  73031. }
  73032. }
  73033. // Restore states
  73034. engine.setDepthBuffer(true);
  73035. engine.setDepthWrite(true);
  73036. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73037. };
  73038. /**
  73039. * Disposes of the post process manager.
  73040. */
  73041. PostProcessManager.prototype.dispose = function () {
  73042. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73043. if (buffer) {
  73044. buffer.dispose();
  73045. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73046. }
  73047. if (this._indexBuffer) {
  73048. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73049. this._indexBuffer = null;
  73050. }
  73051. };
  73052. return PostProcessManager;
  73053. }());
  73054. BABYLON.PostProcessManager = PostProcessManager;
  73055. })(BABYLON || (BABYLON = {}));
  73056. //# sourceMappingURL=babylon.postProcessManager.js.map
  73057. var BABYLON;
  73058. (function (BABYLON) {
  73059. /**
  73060. * PostProcess can be used to apply a shader to a texture after it has been rendered
  73061. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  73062. */
  73063. var PostProcess = /** @class */ (function () {
  73064. /**
  73065. * Creates a new instance PostProcess
  73066. * @param name The name of the PostProcess.
  73067. * @param fragmentUrl The url of the fragment shader to be used.
  73068. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  73069. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  73070. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  73071. * @param camera The camera to apply the render pass to.
  73072. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73073. * @param engine The engine which the post process will be applied. (default: current engine)
  73074. * @param reusable If the post process can be reused on the same frame. (default: false)
  73075. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  73076. * @param textureType Type of textures used when performing the post process. (default: 0)
  73077. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  73078. * @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
  73079. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  73080. */
  73081. function PostProcess(
  73082. /** Name of the PostProcess. */
  73083. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  73084. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  73085. if (defines === void 0) { defines = null; }
  73086. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73087. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  73088. if (blockCompilation === void 0) { blockCompilation = false; }
  73089. this.name = name;
  73090. /**
  73091. * Width of the texture to apply the post process on
  73092. */
  73093. this.width = -1;
  73094. /**
  73095. * Height of the texture to apply the post process on
  73096. */
  73097. this.height = -1;
  73098. /**
  73099. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  73100. * @hidden
  73101. */
  73102. this._outputTexture = null;
  73103. /**
  73104. * If the buffer needs to be cleared before applying the post process. (default: true)
  73105. * Should be set to false if shader will overwrite all previous pixels.
  73106. */
  73107. this.autoClear = true;
  73108. /**
  73109. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  73110. */
  73111. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  73112. /**
  73113. * Animations to be used for the post processing
  73114. */
  73115. this.animations = new Array();
  73116. /**
  73117. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  73118. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  73119. */
  73120. this.enablePixelPerfectMode = false;
  73121. /**
  73122. * Force the postprocess to be applied without taking in account viewport
  73123. */
  73124. this.forceFullscreenViewport = true;
  73125. /**
  73126. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  73127. *
  73128. * | Value | Type | Description |
  73129. * | ----- | ----------------------------------- | ----------- |
  73130. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  73131. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  73132. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  73133. *
  73134. */
  73135. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  73136. /**
  73137. * Force textures to be a power of two (default: false)
  73138. */
  73139. this.alwaysForcePOT = false;
  73140. this._samples = 1;
  73141. /**
  73142. * Modify the scale of the post process to be the same as the viewport (default: false)
  73143. */
  73144. this.adaptScaleToCurrentViewport = false;
  73145. this._reusable = false;
  73146. /**
  73147. * Smart array of input and output textures for the post process.
  73148. * @hidden
  73149. */
  73150. this._textures = new BABYLON.SmartArray(2);
  73151. /**
  73152. * The index in _textures that corresponds to the output texture.
  73153. * @hidden
  73154. */
  73155. this._currentRenderTextureInd = 0;
  73156. this._scaleRatio = new BABYLON.Vector2(1, 1);
  73157. this._texelSize = BABYLON.Vector2.Zero();
  73158. // Events
  73159. /**
  73160. * An event triggered when the postprocess is activated.
  73161. */
  73162. this.onActivateObservable = new BABYLON.Observable();
  73163. /**
  73164. * An event triggered when the postprocess changes its size.
  73165. */
  73166. this.onSizeChangedObservable = new BABYLON.Observable();
  73167. /**
  73168. * An event triggered when the postprocess applies its effect.
  73169. */
  73170. this.onApplyObservable = new BABYLON.Observable();
  73171. /**
  73172. * An event triggered before rendering the postprocess
  73173. */
  73174. this.onBeforeRenderObservable = new BABYLON.Observable();
  73175. /**
  73176. * An event triggered after rendering the postprocess
  73177. */
  73178. this.onAfterRenderObservable = new BABYLON.Observable();
  73179. if (camera != null) {
  73180. this._camera = camera;
  73181. this._scene = camera.getScene();
  73182. camera.attachPostProcess(this);
  73183. this._engine = this._scene.getEngine();
  73184. this._scene.postProcesses.push(this);
  73185. }
  73186. else if (engine) {
  73187. this._engine = engine;
  73188. this._engine.postProcesses.push(this);
  73189. }
  73190. this._options = options;
  73191. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  73192. this._reusable = reusable || false;
  73193. this._textureType = textureType;
  73194. this._samplers = samplers || [];
  73195. this._samplers.push("textureSampler");
  73196. this._fragmentUrl = fragmentUrl;
  73197. this._vertexUrl = vertexUrl;
  73198. this._parameters = parameters || [];
  73199. this._parameters.push("scale");
  73200. this._indexParameters = indexParameters;
  73201. if (!blockCompilation) {
  73202. this.updateEffect(defines);
  73203. }
  73204. }
  73205. Object.defineProperty(PostProcess.prototype, "samples", {
  73206. /**
  73207. * Number of sample textures (default: 1)
  73208. */
  73209. get: function () {
  73210. return this._samples;
  73211. },
  73212. set: function (n) {
  73213. var _this = this;
  73214. this._samples = n;
  73215. this._textures.forEach(function (texture) {
  73216. if (texture.samples !== _this._samples) {
  73217. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  73218. }
  73219. });
  73220. },
  73221. enumerable: true,
  73222. configurable: true
  73223. });
  73224. Object.defineProperty(PostProcess.prototype, "onActivate", {
  73225. /**
  73226. * A function that is added to the onActivateObservable
  73227. */
  73228. set: function (callback) {
  73229. if (this._onActivateObserver) {
  73230. this.onActivateObservable.remove(this._onActivateObserver);
  73231. }
  73232. if (callback) {
  73233. this._onActivateObserver = this.onActivateObservable.add(callback);
  73234. }
  73235. },
  73236. enumerable: true,
  73237. configurable: true
  73238. });
  73239. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  73240. /**
  73241. * A function that is added to the onSizeChangedObservable
  73242. */
  73243. set: function (callback) {
  73244. if (this._onSizeChangedObserver) {
  73245. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  73246. }
  73247. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  73248. },
  73249. enumerable: true,
  73250. configurable: true
  73251. });
  73252. Object.defineProperty(PostProcess.prototype, "onApply", {
  73253. /**
  73254. * A function that is added to the onApplyObservable
  73255. */
  73256. set: function (callback) {
  73257. if (this._onApplyObserver) {
  73258. this.onApplyObservable.remove(this._onApplyObserver);
  73259. }
  73260. this._onApplyObserver = this.onApplyObservable.add(callback);
  73261. },
  73262. enumerable: true,
  73263. configurable: true
  73264. });
  73265. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  73266. /**
  73267. * A function that is added to the onBeforeRenderObservable
  73268. */
  73269. set: function (callback) {
  73270. if (this._onBeforeRenderObserver) {
  73271. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  73272. }
  73273. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  73274. },
  73275. enumerable: true,
  73276. configurable: true
  73277. });
  73278. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  73279. /**
  73280. * A function that is added to the onAfterRenderObservable
  73281. */
  73282. set: function (callback) {
  73283. if (this._onAfterRenderObserver) {
  73284. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  73285. }
  73286. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  73287. },
  73288. enumerable: true,
  73289. configurable: true
  73290. });
  73291. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  73292. /**
  73293. * 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
  73294. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  73295. */
  73296. get: function () {
  73297. return this._textures.data[this._currentRenderTextureInd];
  73298. },
  73299. set: function (value) {
  73300. this._forcedOutputTexture = value;
  73301. },
  73302. enumerable: true,
  73303. configurable: true
  73304. });
  73305. /**
  73306. * Gets the camera which post process is applied to.
  73307. * @returns The camera the post process is applied to.
  73308. */
  73309. PostProcess.prototype.getCamera = function () {
  73310. return this._camera;
  73311. };
  73312. Object.defineProperty(PostProcess.prototype, "texelSize", {
  73313. /**
  73314. * Gets the texel size of the postprocess.
  73315. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  73316. */
  73317. get: function () {
  73318. if (this._shareOutputWithPostProcess) {
  73319. return this._shareOutputWithPostProcess.texelSize;
  73320. }
  73321. if (this._forcedOutputTexture) {
  73322. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  73323. }
  73324. return this._texelSize;
  73325. },
  73326. enumerable: true,
  73327. configurable: true
  73328. });
  73329. /**
  73330. * Gets the engine which this post process belongs to.
  73331. * @returns The engine the post process was enabled with.
  73332. */
  73333. PostProcess.prototype.getEngine = function () {
  73334. return this._engine;
  73335. };
  73336. /**
  73337. * The effect that is created when initializing the post process.
  73338. * @returns The created effect corrisponding the the postprocess.
  73339. */
  73340. PostProcess.prototype.getEffect = function () {
  73341. return this._effect;
  73342. };
  73343. /**
  73344. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  73345. * @param postProcess The post process to share the output with.
  73346. * @returns This post process.
  73347. */
  73348. PostProcess.prototype.shareOutputWith = function (postProcess) {
  73349. this._disposeTextures();
  73350. this._shareOutputWithPostProcess = postProcess;
  73351. return this;
  73352. };
  73353. /**
  73354. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  73355. * This should be called if the post process that shares output with this post process is disabled/disposed.
  73356. */
  73357. PostProcess.prototype.useOwnOutput = function () {
  73358. if (this._textures.length == 0) {
  73359. this._textures = new BABYLON.SmartArray(2);
  73360. }
  73361. this._shareOutputWithPostProcess = null;
  73362. };
  73363. /**
  73364. * Updates the effect with the current post process compile time values and recompiles the shader.
  73365. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  73366. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  73367. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  73368. * @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
  73369. * @param onCompiled Called when the shader has been compiled.
  73370. * @param onError Called if there is an error when compiling a shader.
  73371. */
  73372. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  73373. if (defines === void 0) { defines = null; }
  73374. if (uniforms === void 0) { uniforms = null; }
  73375. if (samplers === void 0) { samplers = null; }
  73376. 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);
  73377. };
  73378. /**
  73379. * The post process is reusable if it can be used multiple times within one frame.
  73380. * @returns If the post process is reusable
  73381. */
  73382. PostProcess.prototype.isReusable = function () {
  73383. return this._reusable;
  73384. };
  73385. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  73386. PostProcess.prototype.markTextureDirty = function () {
  73387. this.width = -1;
  73388. };
  73389. /**
  73390. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  73391. * 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.
  73392. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  73393. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  73394. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  73395. * @returns The target texture that was bound to be written to.
  73396. */
  73397. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  73398. var _this = this;
  73399. if (sourceTexture === void 0) { sourceTexture = null; }
  73400. camera = camera || this._camera;
  73401. var scene = camera.getScene();
  73402. var engine = scene.getEngine();
  73403. var maxSize = engine.getCaps().maxTextureSize;
  73404. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  73405. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  73406. // 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
  73407. var webVRCamera = camera.parent;
  73408. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  73409. requiredWidth /= 2;
  73410. }
  73411. var desiredWidth = (this._options.width || requiredWidth);
  73412. var desiredHeight = this._options.height || requiredHeight;
  73413. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  73414. if (this.adaptScaleToCurrentViewport) {
  73415. var currentViewport = engine.currentViewport;
  73416. if (currentViewport) {
  73417. desiredWidth *= currentViewport.width;
  73418. desiredHeight *= currentViewport.height;
  73419. }
  73420. }
  73421. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  73422. if (!this._options.width) {
  73423. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  73424. }
  73425. if (!this._options.height) {
  73426. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  73427. }
  73428. }
  73429. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  73430. if (this._textures.length > 0) {
  73431. for (var i = 0; i < this._textures.length; i++) {
  73432. this._engine._releaseTexture(this._textures.data[i]);
  73433. }
  73434. this._textures.reset();
  73435. }
  73436. this.width = desiredWidth;
  73437. this.height = desiredHeight;
  73438. var textureSize = { width: this.width, height: this.height };
  73439. var textureOptions = {
  73440. generateMipMaps: false,
  73441. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  73442. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  73443. samplingMode: this.renderTargetSamplingMode,
  73444. type: this._textureType
  73445. };
  73446. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  73447. if (this._reusable) {
  73448. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  73449. }
  73450. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  73451. this.onSizeChangedObservable.notifyObservers(this);
  73452. }
  73453. this._textures.forEach(function (texture) {
  73454. if (texture.samples !== _this.samples) {
  73455. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  73456. }
  73457. });
  73458. }
  73459. var target;
  73460. if (this._shareOutputWithPostProcess) {
  73461. target = this._shareOutputWithPostProcess.inputTexture;
  73462. }
  73463. else if (this._forcedOutputTexture) {
  73464. target = this._forcedOutputTexture;
  73465. this.width = this._forcedOutputTexture.width;
  73466. this.height = this._forcedOutputTexture.height;
  73467. }
  73468. else {
  73469. target = this.inputTexture;
  73470. }
  73471. // Bind the input of this post process to be used as the output of the previous post process.
  73472. if (this.enablePixelPerfectMode) {
  73473. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  73474. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  73475. }
  73476. else {
  73477. this._scaleRatio.copyFromFloats(1, 1);
  73478. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  73479. }
  73480. this.onActivateObservable.notifyObservers(camera);
  73481. // Clear
  73482. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  73483. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  73484. }
  73485. if (this._reusable) {
  73486. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  73487. }
  73488. return target;
  73489. };
  73490. Object.defineProperty(PostProcess.prototype, "isSupported", {
  73491. /**
  73492. * If the post process is supported.
  73493. */
  73494. get: function () {
  73495. return this._effect.isSupported;
  73496. },
  73497. enumerable: true,
  73498. configurable: true
  73499. });
  73500. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  73501. /**
  73502. * The aspect ratio of the output texture.
  73503. */
  73504. get: function () {
  73505. if (this._shareOutputWithPostProcess) {
  73506. return this._shareOutputWithPostProcess.aspectRatio;
  73507. }
  73508. if (this._forcedOutputTexture) {
  73509. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  73510. }
  73511. return this.width / this.height;
  73512. },
  73513. enumerable: true,
  73514. configurable: true
  73515. });
  73516. /**
  73517. * Get a value indicating if the post-process is ready to be used
  73518. * @returns true if the post-process is ready (shader is compiled)
  73519. */
  73520. PostProcess.prototype.isReady = function () {
  73521. return this._effect && this._effect.isReady();
  73522. };
  73523. /**
  73524. * Binds all textures and uniforms to the shader, this will be run on every pass.
  73525. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  73526. */
  73527. PostProcess.prototype.apply = function () {
  73528. // Check
  73529. if (!this._effect || !this._effect.isReady())
  73530. return null;
  73531. // States
  73532. this._engine.enableEffect(this._effect);
  73533. this._engine.setState(false);
  73534. this._engine.setDepthBuffer(false);
  73535. this._engine.setDepthWrite(false);
  73536. // Alpha
  73537. this._engine.setAlphaMode(this.alphaMode);
  73538. if (this.alphaConstants) {
  73539. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  73540. }
  73541. // Bind the output texture of the preivous post process as the input to this post process.
  73542. var source;
  73543. if (this._shareOutputWithPostProcess) {
  73544. source = this._shareOutputWithPostProcess.inputTexture;
  73545. }
  73546. else if (this._forcedOutputTexture) {
  73547. source = this._forcedOutputTexture;
  73548. }
  73549. else {
  73550. source = this.inputTexture;
  73551. }
  73552. this._effect._bindTexture("textureSampler", source);
  73553. // Parameters
  73554. this._effect.setVector2("scale", this._scaleRatio);
  73555. this.onApplyObservable.notifyObservers(this._effect);
  73556. return this._effect;
  73557. };
  73558. PostProcess.prototype._disposeTextures = function () {
  73559. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  73560. return;
  73561. }
  73562. if (this._textures.length > 0) {
  73563. for (var i = 0; i < this._textures.length; i++) {
  73564. this._engine._releaseTexture(this._textures.data[i]);
  73565. }
  73566. }
  73567. this._textures.dispose();
  73568. };
  73569. /**
  73570. * Disposes the post process.
  73571. * @param camera The camera to dispose the post process on.
  73572. */
  73573. PostProcess.prototype.dispose = function (camera) {
  73574. camera = camera || this._camera;
  73575. this._disposeTextures();
  73576. if (this._scene) {
  73577. var index_1 = this._scene.postProcesses.indexOf(this);
  73578. if (index_1 !== -1) {
  73579. this._scene.postProcesses.splice(index_1, 1);
  73580. }
  73581. }
  73582. else {
  73583. var index_2 = this._engine.postProcesses.indexOf(this);
  73584. if (index_2 !== -1) {
  73585. this._engine.postProcesses.splice(index_2, 1);
  73586. }
  73587. }
  73588. if (!camera) {
  73589. return;
  73590. }
  73591. camera.detachPostProcess(this);
  73592. var index = camera._postProcesses.indexOf(this);
  73593. if (index === 0 && camera._postProcesses.length > 0) {
  73594. var firstPostProcess = this._camera._getFirstPostProcess();
  73595. if (firstPostProcess) {
  73596. firstPostProcess.markTextureDirty();
  73597. }
  73598. }
  73599. this.onActivateObservable.clear();
  73600. this.onAfterRenderObservable.clear();
  73601. this.onApplyObservable.clear();
  73602. this.onBeforeRenderObservable.clear();
  73603. this.onSizeChangedObservable.clear();
  73604. };
  73605. return PostProcess;
  73606. }());
  73607. BABYLON.PostProcess = PostProcess;
  73608. })(BABYLON || (BABYLON = {}));
  73609. //# sourceMappingURL=babylon.postProcess.js.map
  73610. var BABYLON;
  73611. (function (BABYLON) {
  73612. var PassPostProcess = /** @class */ (function (_super) {
  73613. __extends(PassPostProcess, _super);
  73614. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73615. if (camera === void 0) { camera = null; }
  73616. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73617. if (blockCompilation === void 0) { blockCompilation = false; }
  73618. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  73619. }
  73620. return PassPostProcess;
  73621. }(BABYLON.PostProcess));
  73622. BABYLON.PassPostProcess = PassPostProcess;
  73623. })(BABYLON || (BABYLON = {}));
  73624. //# sourceMappingURL=babylon.passPostProcess.js.map
  73625. var __assign = (this && this.__assign) || function () {
  73626. __assign = Object.assign || function(t) {
  73627. for (var s, i = 1, n = arguments.length; i < n; i++) {
  73628. s = arguments[i];
  73629. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  73630. t[p] = s[p];
  73631. }
  73632. return t;
  73633. };
  73634. return __assign.apply(this, arguments);
  73635. };
  73636. var BABYLON;
  73637. (function (BABYLON) {
  73638. /**
  73639. * Default implementation IShadowGenerator.
  73640. * This is the main object responsible of generating shadows in the framework.
  73641. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  73642. */
  73643. var ShadowGenerator = /** @class */ (function () {
  73644. /**
  73645. * Creates a ShadowGenerator object.
  73646. * A ShadowGenerator is the required tool to use the shadows.
  73647. * Each light casting shadows needs to use its own ShadowGenerator.
  73648. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  73649. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  73650. * @param light The light object generating the shadows.
  73651. * @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.
  73652. */
  73653. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  73654. this._bias = 0.00005;
  73655. this._normalBias = 0;
  73656. this._blurBoxOffset = 1;
  73657. this._blurScale = 2;
  73658. this._blurKernel = 1;
  73659. this._useKernelBlur = false;
  73660. this._filter = ShadowGenerator.FILTER_NONE;
  73661. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  73662. this._contactHardeningLightSizeUVRatio = 0.1;
  73663. this._darkness = 0;
  73664. this._transparencyShadow = false;
  73665. /**
  73666. * Controls the extent to which the shadows fade out at the edge of the frustum
  73667. * Used only by directionals and spots
  73668. */
  73669. this.frustumEdgeFalloff = 0;
  73670. /**
  73671. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  73672. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  73673. * It might on the other hand introduce peter panning.
  73674. */
  73675. this.forceBackFacesOnly = false;
  73676. this._lightDirection = BABYLON.Vector3.Zero();
  73677. this._viewMatrix = BABYLON.Matrix.Zero();
  73678. this._projectionMatrix = BABYLON.Matrix.Zero();
  73679. this._transformMatrix = BABYLON.Matrix.Zero();
  73680. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  73681. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  73682. this._currentFaceIndex = 0;
  73683. this._currentFaceIndexCache = 0;
  73684. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  73685. this._mapSize = mapSize;
  73686. this._light = light;
  73687. this._scene = light.getScene();
  73688. light._shadowGenerator = this;
  73689. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  73690. if (!component) {
  73691. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  73692. this._scene._addComponent(component);
  73693. }
  73694. // Texture type fallback from float to int if not supported.
  73695. var caps = this._scene.getEngine().getCaps();
  73696. if (!useFullFloatFirst) {
  73697. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  73698. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73699. }
  73700. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  73701. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73702. }
  73703. else {
  73704. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73705. }
  73706. }
  73707. else {
  73708. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  73709. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73710. }
  73711. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  73712. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73713. }
  73714. else {
  73715. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73716. }
  73717. }
  73718. this._initializeGenerator();
  73719. this._applyFilterValues();
  73720. }
  73721. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  73722. /**
  73723. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  73724. */
  73725. get: function () {
  73726. return this._bias;
  73727. },
  73728. /**
  73729. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  73730. */
  73731. set: function (bias) {
  73732. this._bias = bias;
  73733. },
  73734. enumerable: true,
  73735. configurable: true
  73736. });
  73737. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  73738. /**
  73739. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  73740. */
  73741. get: function () {
  73742. return this._normalBias;
  73743. },
  73744. /**
  73745. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  73746. */
  73747. set: function (normalBias) {
  73748. this._normalBias = normalBias;
  73749. },
  73750. enumerable: true,
  73751. configurable: true
  73752. });
  73753. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  73754. /**
  73755. * Gets the blur box offset: offset applied during the blur pass.
  73756. * Only usefull if useKernelBlur = false
  73757. */
  73758. get: function () {
  73759. return this._blurBoxOffset;
  73760. },
  73761. /**
  73762. * Sets the blur box offset: offset applied during the blur pass.
  73763. * Only usefull if useKernelBlur = false
  73764. */
  73765. set: function (value) {
  73766. if (this._blurBoxOffset === value) {
  73767. return;
  73768. }
  73769. this._blurBoxOffset = value;
  73770. this._disposeBlurPostProcesses();
  73771. },
  73772. enumerable: true,
  73773. configurable: true
  73774. });
  73775. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  73776. /**
  73777. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  73778. * 2 means half of the size.
  73779. */
  73780. get: function () {
  73781. return this._blurScale;
  73782. },
  73783. /**
  73784. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  73785. * 2 means half of the size.
  73786. */
  73787. set: function (value) {
  73788. if (this._blurScale === value) {
  73789. return;
  73790. }
  73791. this._blurScale = value;
  73792. this._disposeBlurPostProcesses();
  73793. },
  73794. enumerable: true,
  73795. configurable: true
  73796. });
  73797. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  73798. /**
  73799. * Gets the blur kernel: kernel size of the blur pass.
  73800. * Only usefull if useKernelBlur = true
  73801. */
  73802. get: function () {
  73803. return this._blurKernel;
  73804. },
  73805. /**
  73806. * Sets the blur kernel: kernel size of the blur pass.
  73807. * Only usefull if useKernelBlur = true
  73808. */
  73809. set: function (value) {
  73810. if (this._blurKernel === value) {
  73811. return;
  73812. }
  73813. this._blurKernel = value;
  73814. this._disposeBlurPostProcesses();
  73815. },
  73816. enumerable: true,
  73817. configurable: true
  73818. });
  73819. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  73820. /**
  73821. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  73822. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  73823. */
  73824. get: function () {
  73825. return this._useKernelBlur;
  73826. },
  73827. /**
  73828. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  73829. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  73830. */
  73831. set: function (value) {
  73832. if (this._useKernelBlur === value) {
  73833. return;
  73834. }
  73835. this._useKernelBlur = value;
  73836. this._disposeBlurPostProcesses();
  73837. },
  73838. enumerable: true,
  73839. configurable: true
  73840. });
  73841. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  73842. /**
  73843. * Gets the depth scale used in ESM mode.
  73844. */
  73845. get: function () {
  73846. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  73847. },
  73848. /**
  73849. * Sets the depth scale used in ESM mode.
  73850. * This can override the scale stored on the light.
  73851. */
  73852. set: function (value) {
  73853. this._depthScale = value;
  73854. },
  73855. enumerable: true,
  73856. configurable: true
  73857. });
  73858. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  73859. /**
  73860. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  73861. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  73862. */
  73863. get: function () {
  73864. return this._filter;
  73865. },
  73866. /**
  73867. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  73868. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  73869. */
  73870. set: function (value) {
  73871. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  73872. if (this._light.needCube()) {
  73873. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  73874. this.useExponentialShadowMap = true;
  73875. return;
  73876. }
  73877. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  73878. this.useCloseExponentialShadowMap = true;
  73879. return;
  73880. }
  73881. // PCF on cubemap would also be expensive
  73882. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  73883. this.usePoissonSampling = true;
  73884. return;
  73885. }
  73886. }
  73887. // Weblg1 fallback for PCF.
  73888. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  73889. if (this._scene.getEngine().webGLVersion === 1) {
  73890. this.usePoissonSampling = true;
  73891. return;
  73892. }
  73893. }
  73894. if (this._filter === value) {
  73895. return;
  73896. }
  73897. this._filter = value;
  73898. this._disposeBlurPostProcesses();
  73899. this._applyFilterValues();
  73900. this._light._markMeshesAsLightDirty();
  73901. },
  73902. enumerable: true,
  73903. configurable: true
  73904. });
  73905. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  73906. /**
  73907. * Gets if the current filter is set to Poisson Sampling.
  73908. */
  73909. get: function () {
  73910. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  73911. },
  73912. /**
  73913. * Sets the current filter to Poisson Sampling.
  73914. */
  73915. set: function (value) {
  73916. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  73917. return;
  73918. }
  73919. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  73920. },
  73921. enumerable: true,
  73922. configurable: true
  73923. });
  73924. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  73925. /**
  73926. * Gets if the current filter is set to VSM.
  73927. * DEPRECATED. Should use useExponentialShadowMap instead.
  73928. */
  73929. get: function () {
  73930. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  73931. return this.useExponentialShadowMap;
  73932. },
  73933. /**
  73934. * Sets the current filter is to VSM.
  73935. * DEPRECATED. Should use useExponentialShadowMap instead.
  73936. */
  73937. set: function (value) {
  73938. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  73939. this.useExponentialShadowMap = value;
  73940. },
  73941. enumerable: true,
  73942. configurable: true
  73943. });
  73944. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  73945. /**
  73946. * Gets if the current filter is set to blurred VSM.
  73947. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  73948. */
  73949. get: function () {
  73950. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  73951. return this.useBlurExponentialShadowMap;
  73952. },
  73953. /**
  73954. * Sets the current filter is to blurred VSM.
  73955. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  73956. */
  73957. set: function (value) {
  73958. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  73959. this.useBlurExponentialShadowMap = value;
  73960. },
  73961. enumerable: true,
  73962. configurable: true
  73963. });
  73964. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  73965. /**
  73966. * Gets if the current filter is set to ESM.
  73967. */
  73968. get: function () {
  73969. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  73970. },
  73971. /**
  73972. * Sets the current filter is to ESM.
  73973. */
  73974. set: function (value) {
  73975. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  73976. return;
  73977. }
  73978. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  73979. },
  73980. enumerable: true,
  73981. configurable: true
  73982. });
  73983. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  73984. /**
  73985. * Gets if the current filter is set to filtered ESM.
  73986. */
  73987. get: function () {
  73988. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  73989. },
  73990. /**
  73991. * Gets if the current filter is set to filtered ESM.
  73992. */
  73993. set: function (value) {
  73994. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  73995. return;
  73996. }
  73997. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  73998. },
  73999. enumerable: true,
  74000. configurable: true
  74001. });
  74002. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  74003. /**
  74004. * Gets if the current filter is set to "close ESM" (using the inverse of the
  74005. * exponential to prevent steep falloff artifacts).
  74006. */
  74007. get: function () {
  74008. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  74009. },
  74010. /**
  74011. * Sets the current filter to "close ESM" (using the inverse of the
  74012. * exponential to prevent steep falloff artifacts).
  74013. */
  74014. set: function (value) {
  74015. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  74016. return;
  74017. }
  74018. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  74019. },
  74020. enumerable: true,
  74021. configurable: true
  74022. });
  74023. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  74024. /**
  74025. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  74026. * exponential to prevent steep falloff artifacts).
  74027. */
  74028. get: function () {
  74029. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  74030. },
  74031. /**
  74032. * Sets the current filter to filtered "close ESM" (using the inverse of the
  74033. * exponential to prevent steep falloff artifacts).
  74034. */
  74035. set: function (value) {
  74036. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  74037. return;
  74038. }
  74039. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  74040. },
  74041. enumerable: true,
  74042. configurable: true
  74043. });
  74044. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  74045. /**
  74046. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  74047. */
  74048. get: function () {
  74049. return this.filter === ShadowGenerator.FILTER_PCF;
  74050. },
  74051. /**
  74052. * Sets the current filter to "PCF" (percentage closer filtering).
  74053. */
  74054. set: function (value) {
  74055. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  74056. return;
  74057. }
  74058. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  74059. },
  74060. enumerable: true,
  74061. configurable: true
  74062. });
  74063. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  74064. /**
  74065. * Gets the PCF or PCSS Quality.
  74066. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  74067. */
  74068. get: function () {
  74069. return this._filteringQuality;
  74070. },
  74071. /**
  74072. * Sets the PCF or PCSS Quality.
  74073. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  74074. */
  74075. set: function (filteringQuality) {
  74076. this._filteringQuality = filteringQuality;
  74077. },
  74078. enumerable: true,
  74079. configurable: true
  74080. });
  74081. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  74082. /**
  74083. * Gets if the current filter is set to "PCSS" (contact hardening).
  74084. */
  74085. get: function () {
  74086. return this.filter === ShadowGenerator.FILTER_PCSS;
  74087. },
  74088. /**
  74089. * Sets the current filter to "PCSS" (contact hardening).
  74090. */
  74091. set: function (value) {
  74092. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  74093. return;
  74094. }
  74095. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  74096. },
  74097. enumerable: true,
  74098. configurable: true
  74099. });
  74100. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  74101. /**
  74102. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  74103. * Using a ratio helps keeping shape stability independently of the map size.
  74104. *
  74105. * It does not account for the light projection as it was having too much
  74106. * instability during the light setup or during light position changes.
  74107. *
  74108. * Only valid if useContactHardeningShadow is true.
  74109. */
  74110. get: function () {
  74111. return this._contactHardeningLightSizeUVRatio;
  74112. },
  74113. /**
  74114. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  74115. * Using a ratio helps keeping shape stability independently of the map size.
  74116. *
  74117. * It does not account for the light projection as it was having too much
  74118. * instability during the light setup or during light position changes.
  74119. *
  74120. * Only valid if useContactHardeningShadow is true.
  74121. */
  74122. set: function (contactHardeningLightSizeUVRatio) {
  74123. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  74124. },
  74125. enumerable: true,
  74126. configurable: true
  74127. });
  74128. /**
  74129. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  74130. * 0 means strongest and 1 would means no shadow.
  74131. * @returns the darkness.
  74132. */
  74133. ShadowGenerator.prototype.getDarkness = function () {
  74134. return this._darkness;
  74135. };
  74136. /**
  74137. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  74138. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  74139. * @returns the shadow generator allowing fluent coding.
  74140. */
  74141. ShadowGenerator.prototype.setDarkness = function (darkness) {
  74142. if (darkness >= 1.0)
  74143. this._darkness = 1.0;
  74144. else if (darkness <= 0.0)
  74145. this._darkness = 0.0;
  74146. else
  74147. this._darkness = darkness;
  74148. return this;
  74149. };
  74150. /**
  74151. * Sets the ability to have transparent shadow (boolean).
  74152. * @param transparent True if transparent else False
  74153. * @returns the shadow generator allowing fluent coding
  74154. */
  74155. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  74156. this._transparencyShadow = transparent;
  74157. return this;
  74158. };
  74159. /**
  74160. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  74161. * @returns The render target texture if present otherwise, null
  74162. */
  74163. ShadowGenerator.prototype.getShadowMap = function () {
  74164. return this._shadowMap;
  74165. };
  74166. /**
  74167. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  74168. * @returns The render target texture if the shadow map is present otherwise, null
  74169. */
  74170. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  74171. if (this._shadowMap2) {
  74172. return this._shadowMap2;
  74173. }
  74174. return this._shadowMap;
  74175. };
  74176. /**
  74177. * Helper function to add a mesh and its descendants to the list of shadow casters.
  74178. * @param mesh Mesh to add
  74179. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  74180. * @returns the Shadow Generator itself
  74181. */
  74182. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  74183. if (includeDescendants === void 0) { includeDescendants = true; }
  74184. var _a;
  74185. if (!this._shadowMap) {
  74186. return this;
  74187. }
  74188. if (!this._shadowMap.renderList) {
  74189. this._shadowMap.renderList = [];
  74190. }
  74191. this._shadowMap.renderList.push(mesh);
  74192. if (includeDescendants) {
  74193. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  74194. }
  74195. return this;
  74196. };
  74197. /**
  74198. * Helper function to remove a mesh and its descendants from the list of shadow casters
  74199. * @param mesh Mesh to remove
  74200. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  74201. * @returns the Shadow Generator itself
  74202. */
  74203. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  74204. if (includeDescendants === void 0) { includeDescendants = true; }
  74205. if (!this._shadowMap || !this._shadowMap.renderList) {
  74206. return this;
  74207. }
  74208. var index = this._shadowMap.renderList.indexOf(mesh);
  74209. if (index !== -1) {
  74210. this._shadowMap.renderList.splice(index, 1);
  74211. }
  74212. if (includeDescendants) {
  74213. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  74214. var child = _a[_i];
  74215. this.removeShadowCaster(child);
  74216. }
  74217. }
  74218. return this;
  74219. };
  74220. /**
  74221. * Returns the associated light object.
  74222. * @returns the light generating the shadow
  74223. */
  74224. ShadowGenerator.prototype.getLight = function () {
  74225. return this._light;
  74226. };
  74227. ShadowGenerator.prototype._initializeGenerator = function () {
  74228. this._light._markMeshesAsLightDirty();
  74229. this._initializeShadowMap();
  74230. };
  74231. ShadowGenerator.prototype._initializeShadowMap = function () {
  74232. var _this = this;
  74233. // Render target
  74234. var engine = this._scene.getEngine();
  74235. if (engine.webGLVersion > 1) {
  74236. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  74237. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  74238. }
  74239. else {
  74240. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  74241. }
  74242. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74243. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74244. this._shadowMap.anisotropicFilteringLevel = 1;
  74245. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74246. this._shadowMap.renderParticles = false;
  74247. this._shadowMap.ignoreCameraViewport = true;
  74248. // Record Face Index before render.
  74249. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  74250. _this._currentFaceIndex = faceIndex;
  74251. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  74252. engine.setColorWrite(false);
  74253. }
  74254. });
  74255. // Custom render function.
  74256. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  74257. // Blur if required afer render.
  74258. this._shadowMap.onAfterUnbindObservable.add(function () {
  74259. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  74260. engine.setColorWrite(true);
  74261. }
  74262. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  74263. return;
  74264. }
  74265. var shadowMap = _this.getShadowMapForRendering();
  74266. if (shadowMap) {
  74267. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  74268. }
  74269. });
  74270. // Clear according to the chosen filter.
  74271. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  74272. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  74273. this._shadowMap.onClearObservable.add(function (engine) {
  74274. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  74275. engine.clear(clearOne, false, true, false);
  74276. }
  74277. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  74278. engine.clear(clearZero, true, true, false);
  74279. }
  74280. else {
  74281. engine.clear(clearOne, true, true, false);
  74282. }
  74283. });
  74284. };
  74285. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  74286. var _this = this;
  74287. var engine = this._scene.getEngine();
  74288. var targetSize = this._mapSize / this.blurScale;
  74289. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  74290. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  74291. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74292. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74293. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74294. }
  74295. if (this.useKernelBlur) {
  74296. 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);
  74297. this._kernelBlurXPostprocess.width = targetSize;
  74298. this._kernelBlurXPostprocess.height = targetSize;
  74299. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  74300. effect.setTexture("textureSampler", _this._shadowMap);
  74301. });
  74302. 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);
  74303. this._kernelBlurXPostprocess.autoClear = false;
  74304. this._kernelBlurYPostprocess.autoClear = false;
  74305. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74306. this._kernelBlurXPostprocess.packedFloat = true;
  74307. this._kernelBlurYPostprocess.packedFloat = true;
  74308. }
  74309. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  74310. }
  74311. else {
  74312. 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);
  74313. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  74314. effect.setFloat2("screenSize", targetSize, targetSize);
  74315. effect.setTexture("textureSampler", _this._shadowMap);
  74316. });
  74317. this._boxBlurPostprocess.autoClear = false;
  74318. this._blurPostProcesses = [this._boxBlurPostprocess];
  74319. }
  74320. };
  74321. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74322. var index;
  74323. var engine = this._scene.getEngine();
  74324. if (depthOnlySubMeshes.length) {
  74325. engine.setColorWrite(false);
  74326. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74327. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  74328. }
  74329. engine.setColorWrite(true);
  74330. }
  74331. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74332. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  74333. }
  74334. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74335. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  74336. }
  74337. if (this._transparencyShadow) {
  74338. for (index = 0; index < transparentSubMeshes.length; index++) {
  74339. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  74340. }
  74341. }
  74342. };
  74343. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  74344. var _this = this;
  74345. var mesh = subMesh.getRenderingMesh();
  74346. var scene = this._scene;
  74347. var engine = scene.getEngine();
  74348. var material = subMesh.getMaterial();
  74349. if (!material) {
  74350. return;
  74351. }
  74352. // Culling
  74353. engine.setState(material.backFaceCulling);
  74354. // Managing instances
  74355. var batch = mesh._getInstancesRenderList(subMesh._id);
  74356. if (batch.mustReturn) {
  74357. return;
  74358. }
  74359. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  74360. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  74361. engine.enableEffect(this._effect);
  74362. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  74363. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  74364. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  74365. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  74366. this._effect.setVector3("lightData", this._cachedDirection);
  74367. }
  74368. else {
  74369. this._effect.setVector3("lightData", this._cachedPosition);
  74370. }
  74371. if (scene.activeCamera) {
  74372. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  74373. }
  74374. // Alpha test
  74375. if (material && material.needAlphaTesting()) {
  74376. var alphaTexture = material.getAlphaTestTexture();
  74377. if (alphaTexture) {
  74378. this._effect.setTexture("diffuseSampler", alphaTexture);
  74379. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  74380. }
  74381. }
  74382. // Bones
  74383. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74384. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  74385. }
  74386. // Morph targets
  74387. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  74388. if (this.forceBackFacesOnly) {
  74389. engine.setState(true, 0, false, true);
  74390. }
  74391. // Draw
  74392. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  74393. if (this.forceBackFacesOnly) {
  74394. engine.setState(true, 0, false, false);
  74395. }
  74396. }
  74397. else {
  74398. // Need to reset refresh rate of the shadowMap
  74399. if (this._shadowMap) {
  74400. this._shadowMap.resetRefreshCounter();
  74401. }
  74402. }
  74403. };
  74404. ShadowGenerator.prototype._applyFilterValues = function () {
  74405. if (!this._shadowMap) {
  74406. return;
  74407. }
  74408. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  74409. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  74410. }
  74411. else {
  74412. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74413. }
  74414. };
  74415. /**
  74416. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  74417. * @param onCompiled Callback triggered at the and of the effects compilation
  74418. * @param options Sets of optional options forcing the compilation with different modes
  74419. */
  74420. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  74421. var _this = this;
  74422. var localOptions = __assign({ useInstances: false }, options);
  74423. var shadowMap = this.getShadowMap();
  74424. if (!shadowMap) {
  74425. if (onCompiled) {
  74426. onCompiled(this);
  74427. }
  74428. return;
  74429. }
  74430. var renderList = shadowMap.renderList;
  74431. if (!renderList) {
  74432. if (onCompiled) {
  74433. onCompiled(this);
  74434. }
  74435. return;
  74436. }
  74437. var subMeshes = new Array();
  74438. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  74439. var mesh = renderList_1[_i];
  74440. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  74441. }
  74442. if (subMeshes.length === 0) {
  74443. if (onCompiled) {
  74444. onCompiled(this);
  74445. }
  74446. return;
  74447. }
  74448. var currentIndex = 0;
  74449. var checkReady = function () {
  74450. if (!_this._scene || !_this._scene.getEngine()) {
  74451. return;
  74452. }
  74453. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  74454. currentIndex++;
  74455. if (currentIndex >= subMeshes.length) {
  74456. if (onCompiled) {
  74457. onCompiled(_this);
  74458. }
  74459. return;
  74460. }
  74461. }
  74462. setTimeout(checkReady, 16);
  74463. };
  74464. checkReady();
  74465. };
  74466. /**
  74467. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  74468. * @param options Sets of optional options forcing the compilation with different modes
  74469. * @returns A promise that resolves when the compilation completes
  74470. */
  74471. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  74472. var _this = this;
  74473. return new Promise(function (resolve) {
  74474. _this.forceCompilation(function () {
  74475. resolve();
  74476. }, options);
  74477. });
  74478. };
  74479. /**
  74480. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  74481. * @param subMesh The submesh we want to render in the shadow map
  74482. * @param useInstances Defines wether will draw in the map using instances
  74483. * @returns true if ready otherwise, false
  74484. */
  74485. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  74486. var defines = [];
  74487. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74488. defines.push("#define FLOAT");
  74489. }
  74490. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  74491. defines.push("#define ESM");
  74492. }
  74493. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  74494. defines.push("#define DEPTHTEXTURE");
  74495. }
  74496. var attribs = [BABYLON.VertexBuffer.PositionKind];
  74497. var mesh = subMesh.getMesh();
  74498. var material = subMesh.getMaterial();
  74499. // Normal bias.
  74500. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  74501. attribs.push(BABYLON.VertexBuffer.NormalKind);
  74502. defines.push("#define NORMAL");
  74503. if (mesh.nonUniformScaling) {
  74504. defines.push("#define NONUNIFORMSCALING");
  74505. }
  74506. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  74507. defines.push("#define DIRECTIONINLIGHTDATA");
  74508. }
  74509. }
  74510. // Alpha test
  74511. if (material && material.needAlphaTesting()) {
  74512. var alphaTexture = material.getAlphaTestTexture();
  74513. if (alphaTexture) {
  74514. defines.push("#define ALPHATEST");
  74515. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74516. attribs.push(BABYLON.VertexBuffer.UVKind);
  74517. defines.push("#define UV1");
  74518. }
  74519. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74520. if (alphaTexture.coordinatesIndex === 1) {
  74521. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74522. defines.push("#define UV2");
  74523. }
  74524. }
  74525. }
  74526. }
  74527. // Bones
  74528. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  74529. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  74530. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  74531. if (mesh.numBoneInfluencers > 4) {
  74532. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  74533. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  74534. }
  74535. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  74536. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  74537. }
  74538. else {
  74539. defines.push("#define NUM_BONE_INFLUENCERS 0");
  74540. }
  74541. // Morph targets
  74542. var manager = mesh.morphTargetManager;
  74543. var morphInfluencers = 0;
  74544. if (manager) {
  74545. if (manager.numInfluencers > 0) {
  74546. defines.push("#define MORPHTARGETS");
  74547. morphInfluencers = manager.numInfluencers;
  74548. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  74549. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  74550. }
  74551. }
  74552. // Instances
  74553. if (useInstances) {
  74554. defines.push("#define INSTANCES");
  74555. attribs.push("world0");
  74556. attribs.push("world1");
  74557. attribs.push("world2");
  74558. attribs.push("world3");
  74559. }
  74560. // Get correct effect
  74561. var join = defines.join("\n");
  74562. if (this._cachedDefines !== join) {
  74563. this._cachedDefines = join;
  74564. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  74565. }
  74566. if (!this._effect.isReady()) {
  74567. return false;
  74568. }
  74569. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  74570. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  74571. this._initializeBlurRTTAndPostProcesses();
  74572. }
  74573. }
  74574. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  74575. return false;
  74576. }
  74577. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  74578. return false;
  74579. }
  74580. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  74581. return false;
  74582. }
  74583. return true;
  74584. };
  74585. /**
  74586. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  74587. * @param defines Defines of the material we want to update
  74588. * @param lightIndex Index of the light in the enabled light list of the material
  74589. */
  74590. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  74591. var scene = this._scene;
  74592. var light = this._light;
  74593. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  74594. return;
  74595. }
  74596. defines["SHADOW" + lightIndex] = true;
  74597. if (this.useContactHardeningShadow) {
  74598. defines["SHADOWPCSS" + lightIndex] = true;
  74599. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  74600. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  74601. }
  74602. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  74603. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  74604. }
  74605. // else default to high.
  74606. }
  74607. if (this.usePercentageCloserFiltering) {
  74608. defines["SHADOWPCF" + lightIndex] = true;
  74609. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  74610. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  74611. }
  74612. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  74613. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  74614. }
  74615. // else default to high.
  74616. }
  74617. else if (this.usePoissonSampling) {
  74618. defines["SHADOWPOISSON" + lightIndex] = true;
  74619. }
  74620. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  74621. defines["SHADOWESM" + lightIndex] = true;
  74622. }
  74623. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  74624. defines["SHADOWCLOSEESM" + lightIndex] = true;
  74625. }
  74626. if (light.needCube()) {
  74627. defines["SHADOWCUBE" + lightIndex] = true;
  74628. }
  74629. };
  74630. /**
  74631. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  74632. * defined in the generator but impacting the effect).
  74633. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  74634. * @param effect The effect we are binfing the information for
  74635. */
  74636. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  74637. var light = this._light;
  74638. var scene = this._scene;
  74639. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  74640. return;
  74641. }
  74642. var camera = scene.activeCamera;
  74643. if (!camera) {
  74644. return;
  74645. }
  74646. var shadowMap = this.getShadowMap();
  74647. if (!shadowMap) {
  74648. return;
  74649. }
  74650. if (!light.needCube()) {
  74651. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  74652. }
  74653. // Only PCF uses depth stencil texture.
  74654. if (this._filter === ShadowGenerator.FILTER_PCF) {
  74655. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  74656. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  74657. }
  74658. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  74659. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  74660. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  74661. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  74662. }
  74663. else {
  74664. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  74665. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  74666. }
  74667. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  74668. };
  74669. /**
  74670. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  74671. * (eq to shadow prjection matrix * light transform matrix)
  74672. * @returns The transform matrix used to create the shadow map
  74673. */
  74674. ShadowGenerator.prototype.getTransformMatrix = function () {
  74675. var scene = this._scene;
  74676. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  74677. return this._transformMatrix;
  74678. }
  74679. this._currentRenderID = scene.getRenderId();
  74680. this._currentFaceIndexCache = this._currentFaceIndex;
  74681. var lightPosition = this._light.position;
  74682. if (this._light.computeTransformedInformation()) {
  74683. lightPosition = this._light.transformedPosition;
  74684. }
  74685. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  74686. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  74687. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  74688. }
  74689. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  74690. this._cachedPosition.copyFrom(lightPosition);
  74691. this._cachedDirection.copyFrom(this._lightDirection);
  74692. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  74693. var shadowMap = this.getShadowMap();
  74694. if (shadowMap) {
  74695. var renderList = shadowMap.renderList;
  74696. if (renderList) {
  74697. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  74698. }
  74699. }
  74700. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  74701. }
  74702. return this._transformMatrix;
  74703. };
  74704. /**
  74705. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  74706. * Cube and 2D textures for instance.
  74707. */
  74708. ShadowGenerator.prototype.recreateShadowMap = function () {
  74709. var shadowMap = this._shadowMap;
  74710. if (!shadowMap) {
  74711. return;
  74712. }
  74713. // Track render list.
  74714. var renderList = shadowMap.renderList;
  74715. // Clean up existing data.
  74716. this._disposeRTTandPostProcesses();
  74717. // Reinitializes.
  74718. this._initializeGenerator();
  74719. // Reaffect the filter to ensure a correct fallback if necessary.
  74720. this.filter = this.filter;
  74721. // Reaffect the filter.
  74722. this._applyFilterValues();
  74723. // Reaffect Render List.
  74724. this._shadowMap.renderList = renderList;
  74725. };
  74726. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  74727. if (this._shadowMap2) {
  74728. this._shadowMap2.dispose();
  74729. this._shadowMap2 = null;
  74730. }
  74731. if (this._boxBlurPostprocess) {
  74732. this._boxBlurPostprocess.dispose();
  74733. this._boxBlurPostprocess = null;
  74734. }
  74735. if (this._kernelBlurXPostprocess) {
  74736. this._kernelBlurXPostprocess.dispose();
  74737. this._kernelBlurXPostprocess = null;
  74738. }
  74739. if (this._kernelBlurYPostprocess) {
  74740. this._kernelBlurYPostprocess.dispose();
  74741. this._kernelBlurYPostprocess = null;
  74742. }
  74743. this._blurPostProcesses = [];
  74744. };
  74745. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  74746. if (this._shadowMap) {
  74747. this._shadowMap.dispose();
  74748. this._shadowMap = null;
  74749. }
  74750. this._disposeBlurPostProcesses();
  74751. };
  74752. /**
  74753. * Disposes the ShadowGenerator.
  74754. * Returns nothing.
  74755. */
  74756. ShadowGenerator.prototype.dispose = function () {
  74757. this._disposeRTTandPostProcesses();
  74758. if (this._light) {
  74759. this._light._shadowGenerator = null;
  74760. this._light._markMeshesAsLightDirty();
  74761. }
  74762. };
  74763. /**
  74764. * Serializes the shadow generator setup to a json object.
  74765. * @returns The serialized JSON object
  74766. */
  74767. ShadowGenerator.prototype.serialize = function () {
  74768. var serializationObject = {};
  74769. var shadowMap = this.getShadowMap();
  74770. if (!shadowMap) {
  74771. return serializationObject;
  74772. }
  74773. serializationObject.lightId = this._light.id;
  74774. serializationObject.mapSize = shadowMap.getRenderSize();
  74775. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  74776. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  74777. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  74778. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  74779. serializationObject.usePoissonSampling = this.usePoissonSampling;
  74780. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  74781. serializationObject.depthScale = this.depthScale;
  74782. serializationObject.darkness = this.getDarkness();
  74783. serializationObject.blurBoxOffset = this.blurBoxOffset;
  74784. serializationObject.blurKernel = this.blurKernel;
  74785. serializationObject.blurScale = this.blurScale;
  74786. serializationObject.useKernelBlur = this.useKernelBlur;
  74787. serializationObject.transparencyShadow = this._transparencyShadow;
  74788. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  74789. serializationObject.bias = this.bias;
  74790. serializationObject.normalBias = this.normalBias;
  74791. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  74792. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  74793. serializationObject.filteringQuality = this.filteringQuality;
  74794. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  74795. serializationObject.renderList = [];
  74796. if (shadowMap.renderList) {
  74797. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  74798. var mesh = shadowMap.renderList[meshIndex];
  74799. serializationObject.renderList.push(mesh.id);
  74800. }
  74801. }
  74802. return serializationObject;
  74803. };
  74804. /**
  74805. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  74806. * @param parsedShadowGenerator The JSON object to parse
  74807. * @param scene The scene to create the shadow map for
  74808. * @returns The parsed shadow generator
  74809. */
  74810. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  74811. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  74812. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  74813. var shadowMap = shadowGenerator.getShadowMap();
  74814. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  74815. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  74816. meshes.forEach(function (mesh) {
  74817. if (!shadowMap) {
  74818. return;
  74819. }
  74820. if (!shadowMap.renderList) {
  74821. shadowMap.renderList = [];
  74822. }
  74823. shadowMap.renderList.push(mesh);
  74824. });
  74825. }
  74826. if (parsedShadowGenerator.usePoissonSampling) {
  74827. shadowGenerator.usePoissonSampling = true;
  74828. }
  74829. else if (parsedShadowGenerator.useExponentialShadowMap) {
  74830. shadowGenerator.useExponentialShadowMap = true;
  74831. }
  74832. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  74833. shadowGenerator.useBlurExponentialShadowMap = true;
  74834. }
  74835. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  74836. shadowGenerator.useCloseExponentialShadowMap = true;
  74837. }
  74838. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  74839. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  74840. }
  74841. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  74842. shadowGenerator.usePercentageCloserFiltering = true;
  74843. }
  74844. else if (parsedShadowGenerator.useContactHardeningShadow) {
  74845. shadowGenerator.useContactHardeningShadow = true;
  74846. }
  74847. if (parsedShadowGenerator.filteringQuality) {
  74848. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  74849. }
  74850. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  74851. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  74852. }
  74853. // Backward compat
  74854. else if (parsedShadowGenerator.useVarianceShadowMap) {
  74855. shadowGenerator.useExponentialShadowMap = true;
  74856. }
  74857. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  74858. shadowGenerator.useBlurExponentialShadowMap = true;
  74859. }
  74860. if (parsedShadowGenerator.depthScale) {
  74861. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  74862. }
  74863. if (parsedShadowGenerator.blurScale) {
  74864. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  74865. }
  74866. if (parsedShadowGenerator.blurBoxOffset) {
  74867. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  74868. }
  74869. if (parsedShadowGenerator.useKernelBlur) {
  74870. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  74871. }
  74872. if (parsedShadowGenerator.blurKernel) {
  74873. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  74874. }
  74875. if (parsedShadowGenerator.bias !== undefined) {
  74876. shadowGenerator.bias = parsedShadowGenerator.bias;
  74877. }
  74878. if (parsedShadowGenerator.normalBias !== undefined) {
  74879. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  74880. }
  74881. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  74882. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  74883. }
  74884. if (parsedShadowGenerator.darkness) {
  74885. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  74886. }
  74887. if (parsedShadowGenerator.transparencyShadow) {
  74888. shadowGenerator.setTransparencyShadow(true);
  74889. }
  74890. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  74891. return shadowGenerator;
  74892. };
  74893. /**
  74894. * Shadow generator mode None: no filtering applied.
  74895. */
  74896. ShadowGenerator.FILTER_NONE = 0;
  74897. /**
  74898. * Shadow generator mode ESM: Exponential Shadow Mapping.
  74899. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74900. */
  74901. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  74902. /**
  74903. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  74904. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  74905. */
  74906. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  74907. /**
  74908. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  74909. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74910. */
  74911. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  74912. /**
  74913. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  74914. * edge artifacts on steep falloff.
  74915. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74916. */
  74917. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  74918. /**
  74919. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  74920. * edge artifacts on steep falloff.
  74921. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  74922. */
  74923. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  74924. /**
  74925. * Shadow generator mode PCF: Percentage Closer Filtering
  74926. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  74927. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  74928. */
  74929. ShadowGenerator.FILTER_PCF = 6;
  74930. /**
  74931. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  74932. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  74933. * Contact Hardening
  74934. */
  74935. ShadowGenerator.FILTER_PCSS = 7;
  74936. /**
  74937. * Reserved for PCF and PCSS
  74938. * Highest Quality.
  74939. *
  74940. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  74941. *
  74942. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  74943. */
  74944. ShadowGenerator.QUALITY_HIGH = 0;
  74945. /**
  74946. * Reserved for PCF and PCSS
  74947. * Good tradeoff for quality/perf cross devices
  74948. *
  74949. * Execute PCF on a 3*3 kernel.
  74950. *
  74951. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  74952. */
  74953. ShadowGenerator.QUALITY_MEDIUM = 1;
  74954. /**
  74955. * Reserved for PCF and PCSS
  74956. * The lowest quality but the fastest.
  74957. *
  74958. * Execute PCF on a 1*1 kernel.
  74959. *
  74960. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  74961. */
  74962. ShadowGenerator.QUALITY_LOW = 2;
  74963. return ShadowGenerator;
  74964. }());
  74965. BABYLON.ShadowGenerator = ShadowGenerator;
  74966. })(BABYLON || (BABYLON = {}));
  74967. //# sourceMappingURL=babylon.shadowGenerator.js.map
  74968. var BABYLON;
  74969. (function (BABYLON) {
  74970. // Adds the parser to the scene parsers.
  74971. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  74972. // Shadows
  74973. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  74974. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  74975. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  74976. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  74977. // SG would be available on their associated lights
  74978. }
  74979. }
  74980. });
  74981. /**
  74982. * Defines the shadow generator component responsible to manage any shadow generators
  74983. * in a given scene.
  74984. */
  74985. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  74986. /**
  74987. * Creates a new instance of the component for the given scene
  74988. * @param scene Defines the scene to register the component in
  74989. */
  74990. function ShadowGeneratorSceneComponent(scene) {
  74991. /**
  74992. * The component name helpfull to identify the component in the list of scene components.
  74993. */
  74994. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  74995. this.scene = scene;
  74996. }
  74997. /**
  74998. * Registers the component in a given scene
  74999. */
  75000. ShadowGeneratorSceneComponent.prototype.register = function () {
  75001. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  75002. };
  75003. /**
  75004. * Rebuilds the elements related to this component in case of
  75005. * context lost for instance.
  75006. */
  75007. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  75008. // Nothing To Do Here.
  75009. };
  75010. /**
  75011. * Serializes the component data to the specified json object
  75012. * @param serializationObject The object to serialize to
  75013. */
  75014. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  75015. // Shadows
  75016. serializationObject.shadowGenerators = [];
  75017. var lights = this.scene.lights;
  75018. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  75019. var light = lights_1[_i];
  75020. var shadowGenerator = light.getShadowGenerator();
  75021. if (shadowGenerator) {
  75022. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  75023. }
  75024. }
  75025. };
  75026. /**
  75027. * Adds all the element from the container to the scene
  75028. * @param container the container holding the elements
  75029. */
  75030. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  75031. // Nothing To Do Here. (directly attached to a light)
  75032. };
  75033. /**
  75034. * Removes all the elements in the container from the scene
  75035. * @param container contains the elements to remove
  75036. */
  75037. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  75038. // Nothing To Do Here. (directly attached to a light)
  75039. };
  75040. /**
  75041. * Rebuilds the elements related to this component in case of
  75042. * context lost for instance.
  75043. */
  75044. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  75045. // Nothing To Do Here.
  75046. };
  75047. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  75048. // Shadows
  75049. var scene = this.scene;
  75050. if (this.scene.shadowsEnabled) {
  75051. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  75052. var light = scene.lights[lightIndex];
  75053. var shadowGenerator = light.getShadowGenerator();
  75054. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  75055. var shadowMap = (shadowGenerator.getShadowMap());
  75056. if (scene.textures.indexOf(shadowMap) !== -1) {
  75057. renderTargets.push(shadowMap);
  75058. }
  75059. }
  75060. }
  75061. }
  75062. };
  75063. return ShadowGeneratorSceneComponent;
  75064. }());
  75065. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  75066. })(BABYLON || (BABYLON = {}));
  75067. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  75068. var BABYLON;
  75069. (function (BABYLON) {
  75070. var DefaultLoadingScreen = /** @class */ (function () {
  75071. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  75072. if (_loadingText === void 0) { _loadingText = ""; }
  75073. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  75074. var _this = this;
  75075. this._renderingCanvas = _renderingCanvas;
  75076. this._loadingText = _loadingText;
  75077. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  75078. // Resize
  75079. this._resizeLoadingUI = function () {
  75080. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  75081. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  75082. if (!_this._loadingDiv) {
  75083. return;
  75084. }
  75085. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  75086. _this._loadingDiv.style.left = canvasRect.left + "px";
  75087. _this._loadingDiv.style.top = canvasRect.top + "px";
  75088. _this._loadingDiv.style.width = canvasRect.width + "px";
  75089. _this._loadingDiv.style.height = canvasRect.height + "px";
  75090. };
  75091. }
  75092. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  75093. if (this._loadingDiv) {
  75094. // Do not add a loading screen if there is already one
  75095. return;
  75096. }
  75097. this._loadingDiv = document.createElement("div");
  75098. this._loadingDiv.id = "babylonjsLoadingDiv";
  75099. this._loadingDiv.style.opacity = "0";
  75100. this._loadingDiv.style.transition = "opacity 1.5s ease";
  75101. this._loadingDiv.style.pointerEvents = "none";
  75102. // Loading text
  75103. this._loadingTextDiv = document.createElement("div");
  75104. this._loadingTextDiv.style.position = "absolute";
  75105. this._loadingTextDiv.style.left = "0";
  75106. this._loadingTextDiv.style.top = "50%";
  75107. this._loadingTextDiv.style.marginTop = "80px";
  75108. this._loadingTextDiv.style.width = "100%";
  75109. this._loadingTextDiv.style.height = "20px";
  75110. this._loadingTextDiv.style.fontFamily = "Arial";
  75111. this._loadingTextDiv.style.fontSize = "14px";
  75112. this._loadingTextDiv.style.color = "white";
  75113. this._loadingTextDiv.style.textAlign = "center";
  75114. this._loadingTextDiv.innerHTML = "Loading";
  75115. this._loadingDiv.appendChild(this._loadingTextDiv);
  75116. //set the predefined text
  75117. this._loadingTextDiv.innerHTML = this._loadingText;
  75118. // Generating keyframes
  75119. var style = document.createElement('style');
  75120. style.type = 'text/css';
  75121. 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 }";
  75122. style.innerHTML = keyFrames;
  75123. document.getElementsByTagName('head')[0].appendChild(style);
  75124. // Loading img
  75125. var imgBack = new Image();
  75126. 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";
  75127. imgBack.style.position = "absolute";
  75128. imgBack.style.left = "50%";
  75129. imgBack.style.top = "50%";
  75130. imgBack.style.marginLeft = "-60px";
  75131. imgBack.style.marginTop = "-60px";
  75132. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  75133. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  75134. imgBack.style.transformOrigin = "50% 50%";
  75135. imgBack.style.webkitTransformOrigin = "50% 50%";
  75136. this._loadingDiv.appendChild(imgBack);
  75137. this._resizeLoadingUI();
  75138. window.addEventListener("resize", this._resizeLoadingUI);
  75139. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  75140. document.body.appendChild(this._loadingDiv);
  75141. this._loadingDiv.style.opacity = "1";
  75142. };
  75143. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  75144. var _this = this;
  75145. if (!this._loadingDiv) {
  75146. return;
  75147. }
  75148. var onTransitionEnd = function () {
  75149. if (!_this._loadingDiv) {
  75150. return;
  75151. }
  75152. document.body.removeChild(_this._loadingDiv);
  75153. window.removeEventListener("resize", _this._resizeLoadingUI);
  75154. _this._loadingDiv = null;
  75155. };
  75156. this._loadingDiv.style.opacity = "0";
  75157. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  75158. };
  75159. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  75160. set: function (text) {
  75161. this._loadingText = text;
  75162. if (this._loadingTextDiv) {
  75163. this._loadingTextDiv.innerHTML = this._loadingText;
  75164. }
  75165. },
  75166. enumerable: true,
  75167. configurable: true
  75168. });
  75169. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  75170. get: function () {
  75171. return this._loadingDivBackgroundColor;
  75172. },
  75173. set: function (color) {
  75174. this._loadingDivBackgroundColor = color;
  75175. if (!this._loadingDiv) {
  75176. return;
  75177. }
  75178. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  75179. },
  75180. enumerable: true,
  75181. configurable: true
  75182. });
  75183. return DefaultLoadingScreen;
  75184. }());
  75185. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  75186. })(BABYLON || (BABYLON = {}));
  75187. //# sourceMappingURL=babylon.loadingScreen.js.map
  75188. var BABYLON;
  75189. (function (BABYLON) {
  75190. var SceneLoaderProgressEvent = /** @class */ (function () {
  75191. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  75192. this.lengthComputable = lengthComputable;
  75193. this.loaded = loaded;
  75194. this.total = total;
  75195. }
  75196. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  75197. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  75198. };
  75199. return SceneLoaderProgressEvent;
  75200. }());
  75201. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  75202. var SceneLoader = /** @class */ (function () {
  75203. function SceneLoader() {
  75204. }
  75205. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  75206. get: function () {
  75207. return 0;
  75208. },
  75209. enumerable: true,
  75210. configurable: true
  75211. });
  75212. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  75213. get: function () {
  75214. return 1;
  75215. },
  75216. enumerable: true,
  75217. configurable: true
  75218. });
  75219. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  75220. get: function () {
  75221. return 2;
  75222. },
  75223. enumerable: true,
  75224. configurable: true
  75225. });
  75226. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  75227. get: function () {
  75228. return 3;
  75229. },
  75230. enumerable: true,
  75231. configurable: true
  75232. });
  75233. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  75234. get: function () {
  75235. return SceneLoader._ForceFullSceneLoadingForIncremental;
  75236. },
  75237. set: function (value) {
  75238. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  75239. },
  75240. enumerable: true,
  75241. configurable: true
  75242. });
  75243. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  75244. get: function () {
  75245. return SceneLoader._ShowLoadingScreen;
  75246. },
  75247. set: function (value) {
  75248. SceneLoader._ShowLoadingScreen = value;
  75249. },
  75250. enumerable: true,
  75251. configurable: true
  75252. });
  75253. Object.defineProperty(SceneLoader, "loggingLevel", {
  75254. get: function () {
  75255. return SceneLoader._loggingLevel;
  75256. },
  75257. set: function (value) {
  75258. SceneLoader._loggingLevel = value;
  75259. },
  75260. enumerable: true,
  75261. configurable: true
  75262. });
  75263. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  75264. get: function () {
  75265. return SceneLoader._CleanBoneMatrixWeights;
  75266. },
  75267. set: function (value) {
  75268. SceneLoader._CleanBoneMatrixWeights = value;
  75269. },
  75270. enumerable: true,
  75271. configurable: true
  75272. });
  75273. SceneLoader._getDefaultPlugin = function () {
  75274. return SceneLoader._registeredPlugins[".babylon"];
  75275. };
  75276. SceneLoader._getPluginForExtension = function (extension) {
  75277. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  75278. if (registeredPlugin) {
  75279. return registeredPlugin;
  75280. }
  75281. 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");
  75282. return SceneLoader._getDefaultPlugin();
  75283. };
  75284. SceneLoader._getPluginForDirectLoad = function (data) {
  75285. for (var extension in SceneLoader._registeredPlugins) {
  75286. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  75287. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  75288. return SceneLoader._registeredPlugins[extension];
  75289. }
  75290. }
  75291. return SceneLoader._getDefaultPlugin();
  75292. };
  75293. SceneLoader._getPluginForFilename = function (sceneFilename) {
  75294. var queryStringPosition = sceneFilename.indexOf("?");
  75295. if (queryStringPosition !== -1) {
  75296. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  75297. }
  75298. var dotPosition = sceneFilename.lastIndexOf(".");
  75299. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  75300. return SceneLoader._getPluginForExtension(extension);
  75301. };
  75302. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  75303. SceneLoader._getDirectLoad = function (sceneFilename) {
  75304. if (sceneFilename.substr(0, 5) === "data:") {
  75305. return sceneFilename.substr(5);
  75306. }
  75307. return null;
  75308. };
  75309. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  75310. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  75311. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  75312. var plugin;
  75313. if (registeredPlugin.plugin.createPlugin) {
  75314. plugin = registeredPlugin.plugin.createPlugin();
  75315. }
  75316. else {
  75317. plugin = registeredPlugin.plugin;
  75318. }
  75319. var useArrayBuffer = registeredPlugin.isBinary;
  75320. var database;
  75321. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  75322. var dataCallback = function (data, responseURL) {
  75323. if (scene.isDisposed) {
  75324. onError("Scene has been disposed");
  75325. return;
  75326. }
  75327. scene.database = database;
  75328. onSuccess(plugin, data, responseURL);
  75329. };
  75330. var request = null;
  75331. var pluginDisposed = false;
  75332. var onDisposeObservable = plugin.onDisposeObservable;
  75333. if (onDisposeObservable) {
  75334. onDisposeObservable.add(function () {
  75335. pluginDisposed = true;
  75336. if (request) {
  75337. request.abort();
  75338. request = null;
  75339. }
  75340. onDispose();
  75341. });
  75342. }
  75343. var manifestChecked = function () {
  75344. if (pluginDisposed) {
  75345. return;
  75346. }
  75347. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  75348. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  75349. } : undefined, database, useArrayBuffer, function (request, exception) {
  75350. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  75351. });
  75352. };
  75353. if (directLoad) {
  75354. dataCallback(directLoad);
  75355. return plugin;
  75356. }
  75357. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  75358. var engine = scene.getEngine();
  75359. var canUseOfflineSupport = engine.enableOfflineSupport;
  75360. if (canUseOfflineSupport) {
  75361. // Also check for exceptions
  75362. var exceptionFound = false;
  75363. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  75364. var regex = _a[_i];
  75365. if (regex.test(fileInfo.url)) {
  75366. exceptionFound = true;
  75367. break;
  75368. }
  75369. }
  75370. canUseOfflineSupport = !exceptionFound;
  75371. }
  75372. if (canUseOfflineSupport) {
  75373. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  75374. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  75375. }
  75376. else {
  75377. manifestChecked();
  75378. }
  75379. }
  75380. // Loading file from disk via input file or drag'n'drop
  75381. else {
  75382. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  75383. if (file) {
  75384. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  75385. }
  75386. else {
  75387. onError("Unable to find file named " + fileInfo.name);
  75388. }
  75389. }
  75390. return plugin;
  75391. };
  75392. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  75393. var url;
  75394. var name;
  75395. if (!sceneFilename) {
  75396. url = rootUrl;
  75397. name = BABYLON.Tools.GetFilename(rootUrl);
  75398. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  75399. }
  75400. else {
  75401. if (sceneFilename.substr(0, 1) === "/") {
  75402. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  75403. return null;
  75404. }
  75405. url = rootUrl + sceneFilename;
  75406. name = sceneFilename;
  75407. }
  75408. ;
  75409. return {
  75410. url: url,
  75411. rootUrl: rootUrl,
  75412. name: name
  75413. };
  75414. };
  75415. // Public functions
  75416. SceneLoader.GetPluginForExtension = function (extension) {
  75417. return SceneLoader._getPluginForExtension(extension).plugin;
  75418. };
  75419. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  75420. return !!SceneLoader._registeredPlugins[extension];
  75421. };
  75422. SceneLoader.RegisterPlugin = function (plugin) {
  75423. if (typeof plugin.extensions === "string") {
  75424. var extension = plugin.extensions;
  75425. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  75426. plugin: plugin,
  75427. isBinary: false
  75428. };
  75429. }
  75430. else {
  75431. var extensions = plugin.extensions;
  75432. Object.keys(extensions).forEach(function (extension) {
  75433. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  75434. plugin: plugin,
  75435. isBinary: extensions[extension].isBinary
  75436. };
  75437. });
  75438. }
  75439. };
  75440. /**
  75441. * Import meshes into a scene
  75442. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  75443. * @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)
  75444. * @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)
  75445. * @param scene the instance of BABYLON.Scene to append to
  75446. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  75447. * @param onProgress a callback with a progress event for each file being loaded
  75448. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  75449. * @param pluginExtension the extension used to determine the plugin
  75450. * @returns The loaded plugin
  75451. */
  75452. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  75453. if (sceneFilename === void 0) { sceneFilename = ""; }
  75454. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75455. if (onSuccess === void 0) { onSuccess = null; }
  75456. if (onProgress === void 0) { onProgress = null; }
  75457. if (onError === void 0) { onError = null; }
  75458. if (pluginExtension === void 0) { pluginExtension = null; }
  75459. if (!scene) {
  75460. BABYLON.Tools.Error("No scene available to import mesh to");
  75461. return null;
  75462. }
  75463. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  75464. if (!fileInfo) {
  75465. return null;
  75466. }
  75467. var loadingToken = {};
  75468. scene._addPendingData(loadingToken);
  75469. var disposeHandler = function () {
  75470. scene._removePendingData(loadingToken);
  75471. };
  75472. var errorHandler = function (message, exception) {
  75473. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  75474. if (onError) {
  75475. onError(scene, errorMessage, exception);
  75476. }
  75477. else {
  75478. BABYLON.Tools.Error(errorMessage);
  75479. // should the exception be thrown?
  75480. }
  75481. disposeHandler();
  75482. };
  75483. var progressHandler = onProgress ? function (event) {
  75484. try {
  75485. onProgress(event);
  75486. }
  75487. catch (e) {
  75488. errorHandler("Error in onProgress callback", e);
  75489. }
  75490. } : undefined;
  75491. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  75492. scene.importedMeshesFiles.push(fileInfo.url);
  75493. if (onSuccess) {
  75494. try {
  75495. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  75496. }
  75497. catch (e) {
  75498. errorHandler("Error in onSuccess callback", e);
  75499. }
  75500. }
  75501. scene._removePendingData(loadingToken);
  75502. };
  75503. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  75504. if (plugin.rewriteRootURL) {
  75505. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  75506. }
  75507. if (plugin.importMesh) {
  75508. var syncedPlugin = plugin;
  75509. var meshes = new Array();
  75510. var particleSystems = new Array();
  75511. var skeletons = new Array();
  75512. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  75513. return;
  75514. }
  75515. scene.loadingPluginName = plugin.name;
  75516. successHandler(meshes, particleSystems, skeletons, []);
  75517. }
  75518. else {
  75519. var asyncedPlugin = plugin;
  75520. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  75521. scene.loadingPluginName = plugin.name;
  75522. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  75523. }).catch(function (error) {
  75524. errorHandler(error.message, error);
  75525. });
  75526. }
  75527. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  75528. };
  75529. /**
  75530. * Import meshes into a scene
  75531. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  75532. * @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)
  75533. * @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)
  75534. * @param scene the instance of BABYLON.Scene to append to
  75535. * @param onProgress a callback with a progress event for each file being loaded
  75536. * @param pluginExtension the extension used to determine the plugin
  75537. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  75538. */
  75539. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  75540. if (sceneFilename === void 0) { sceneFilename = ""; }
  75541. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75542. if (onProgress === void 0) { onProgress = null; }
  75543. if (pluginExtension === void 0) { pluginExtension = null; }
  75544. return new Promise(function (resolve, reject) {
  75545. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  75546. resolve({
  75547. meshes: meshes,
  75548. particleSystems: particleSystems,
  75549. skeletons: skeletons,
  75550. animationGroups: animationGroups
  75551. });
  75552. }, onProgress, function (scene, message, exception) {
  75553. reject(exception || new Error(message));
  75554. }, pluginExtension);
  75555. });
  75556. };
  75557. /**
  75558. * Load a scene
  75559. * @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)
  75560. * @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)
  75561. * @param engine is the instance of BABYLON.Engine to use to create the scene
  75562. * @param onSuccess a callback with the scene when import succeeds
  75563. * @param onProgress a callback with a progress event for each file being loaded
  75564. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  75565. * @param pluginExtension the extension used to determine the plugin
  75566. * @returns The loaded plugin
  75567. */
  75568. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  75569. if (onSuccess === void 0) { onSuccess = null; }
  75570. if (onProgress === void 0) { onProgress = null; }
  75571. if (onError === void 0) { onError = null; }
  75572. if (pluginExtension === void 0) { pluginExtension = null; }
  75573. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  75574. };
  75575. /**
  75576. * Load a scene
  75577. * @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)
  75578. * @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)
  75579. * @param engine is the instance of BABYLON.Engine to use to create the scene
  75580. * @param onProgress a callback with a progress event for each file being loaded
  75581. * @param pluginExtension the extension used to determine the plugin
  75582. * @returns The loaded scene
  75583. */
  75584. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  75585. if (onProgress === void 0) { onProgress = null; }
  75586. if (pluginExtension === void 0) { pluginExtension = null; }
  75587. return new Promise(function (resolve, reject) {
  75588. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  75589. resolve(scene);
  75590. }, onProgress, function (scene, message, exception) {
  75591. reject(exception || new Error(message));
  75592. }, pluginExtension);
  75593. });
  75594. };
  75595. /**
  75596. * Append a scene
  75597. * @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)
  75598. * @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)
  75599. * @param scene is the instance of BABYLON.Scene to append to
  75600. * @param onSuccess a callback with the scene when import succeeds
  75601. * @param onProgress a callback with a progress event for each file being loaded
  75602. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  75603. * @param pluginExtension the extension used to determine the plugin
  75604. * @returns The loaded plugin
  75605. */
  75606. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  75607. if (sceneFilename === void 0) { sceneFilename = ""; }
  75608. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75609. if (onSuccess === void 0) { onSuccess = null; }
  75610. if (onProgress === void 0) { onProgress = null; }
  75611. if (onError === void 0) { onError = null; }
  75612. if (pluginExtension === void 0) { pluginExtension = null; }
  75613. if (!scene) {
  75614. BABYLON.Tools.Error("No scene available to append to");
  75615. return null;
  75616. }
  75617. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  75618. if (!fileInfo) {
  75619. return null;
  75620. }
  75621. if (SceneLoader.ShowLoadingScreen) {
  75622. scene.getEngine().displayLoadingUI();
  75623. }
  75624. var loadingToken = {};
  75625. scene._addPendingData(loadingToken);
  75626. var disposeHandler = function () {
  75627. scene._removePendingData(loadingToken);
  75628. scene.getEngine().hideLoadingUI();
  75629. };
  75630. var errorHandler = function (message, exception) {
  75631. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  75632. if (onError) {
  75633. onError(scene, errorMessage, exception);
  75634. }
  75635. else {
  75636. BABYLON.Tools.Error(errorMessage);
  75637. // should the exception be thrown?
  75638. }
  75639. disposeHandler();
  75640. };
  75641. var progressHandler = onProgress ? function (event) {
  75642. try {
  75643. onProgress(event);
  75644. }
  75645. catch (e) {
  75646. errorHandler("Error in onProgress callback", e);
  75647. }
  75648. } : undefined;
  75649. var successHandler = function () {
  75650. if (onSuccess) {
  75651. try {
  75652. onSuccess(scene);
  75653. }
  75654. catch (e) {
  75655. errorHandler("Error in onSuccess callback", e);
  75656. }
  75657. }
  75658. scene._removePendingData(loadingToken);
  75659. };
  75660. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  75661. if (plugin.load) {
  75662. var syncedPlugin = plugin;
  75663. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  75664. return;
  75665. }
  75666. scene.loadingPluginName = plugin.name;
  75667. successHandler();
  75668. }
  75669. else {
  75670. var asyncedPlugin = plugin;
  75671. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  75672. scene.loadingPluginName = plugin.name;
  75673. successHandler();
  75674. }).catch(function (error) {
  75675. errorHandler(error.message, error);
  75676. });
  75677. }
  75678. if (SceneLoader.ShowLoadingScreen) {
  75679. scene.executeWhenReady(function () {
  75680. scene.getEngine().hideLoadingUI();
  75681. });
  75682. }
  75683. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  75684. };
  75685. /**
  75686. * Append a scene
  75687. * @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)
  75688. * @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)
  75689. * @param scene is the instance of BABYLON.Scene to append to
  75690. * @param onProgress a callback with a progress event for each file being loaded
  75691. * @param pluginExtension the extension used to determine the plugin
  75692. * @returns The given scene
  75693. */
  75694. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  75695. if (sceneFilename === void 0) { sceneFilename = ""; }
  75696. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75697. if (onProgress === void 0) { onProgress = null; }
  75698. if (pluginExtension === void 0) { pluginExtension = null; }
  75699. return new Promise(function (resolve, reject) {
  75700. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  75701. resolve(scene);
  75702. }, onProgress, function (scene, message, exception) {
  75703. reject(exception || new Error(message));
  75704. }, pluginExtension);
  75705. });
  75706. };
  75707. /**
  75708. * Load a scene into an asset container
  75709. * @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)
  75710. * @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)
  75711. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  75712. * @param onSuccess a callback with the scene when import succeeds
  75713. * @param onProgress a callback with a progress event for each file being loaded
  75714. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  75715. * @param pluginExtension the extension used to determine the plugin
  75716. * @returns The loaded plugin
  75717. */
  75718. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  75719. if (sceneFilename === void 0) { sceneFilename = ""; }
  75720. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75721. if (onSuccess === void 0) { onSuccess = null; }
  75722. if (onProgress === void 0) { onProgress = null; }
  75723. if (onError === void 0) { onError = null; }
  75724. if (pluginExtension === void 0) { pluginExtension = null; }
  75725. if (!scene) {
  75726. BABYLON.Tools.Error("No scene available to load asset container to");
  75727. return null;
  75728. }
  75729. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  75730. if (!fileInfo) {
  75731. return null;
  75732. }
  75733. var loadingToken = {};
  75734. scene._addPendingData(loadingToken);
  75735. var disposeHandler = function () {
  75736. scene._removePendingData(loadingToken);
  75737. };
  75738. var errorHandler = function (message, exception) {
  75739. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  75740. if (onError) {
  75741. onError(scene, errorMessage, exception);
  75742. }
  75743. else {
  75744. BABYLON.Tools.Error(errorMessage);
  75745. // should the exception be thrown?
  75746. }
  75747. disposeHandler();
  75748. };
  75749. var progressHandler = onProgress ? function (event) {
  75750. try {
  75751. onProgress(event);
  75752. }
  75753. catch (e) {
  75754. errorHandler("Error in onProgress callback", e);
  75755. }
  75756. } : undefined;
  75757. var successHandler = function (assets) {
  75758. if (onSuccess) {
  75759. try {
  75760. onSuccess(assets);
  75761. }
  75762. catch (e) {
  75763. errorHandler("Error in onSuccess callback", e);
  75764. }
  75765. }
  75766. scene._removePendingData(loadingToken);
  75767. };
  75768. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  75769. if (plugin.loadAssetContainer) {
  75770. var syncedPlugin = plugin;
  75771. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  75772. if (!assetContainer) {
  75773. return;
  75774. }
  75775. scene.loadingPluginName = plugin.name;
  75776. successHandler(assetContainer);
  75777. }
  75778. else if (plugin.loadAssetContainerAsync) {
  75779. var asyncedPlugin = plugin;
  75780. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  75781. scene.loadingPluginName = plugin.name;
  75782. successHandler(assetContainer);
  75783. }).catch(function (error) {
  75784. errorHandler(error.message, error);
  75785. });
  75786. }
  75787. else {
  75788. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  75789. }
  75790. if (SceneLoader.ShowLoadingScreen) {
  75791. scene.executeWhenReady(function () {
  75792. scene.getEngine().hideLoadingUI();
  75793. });
  75794. }
  75795. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  75796. };
  75797. /**
  75798. * Load a scene into an asset container
  75799. * @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)
  75800. * @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)
  75801. * @param scene is the instance of BABYLON.Scene to append to
  75802. * @param onProgress a callback with a progress event for each file being loaded
  75803. * @param pluginExtension the extension used to determine the plugin
  75804. * @returns The loaded asset container
  75805. */
  75806. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  75807. if (sceneFilename === void 0) { sceneFilename = ""; }
  75808. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75809. if (onProgress === void 0) { onProgress = null; }
  75810. if (pluginExtension === void 0) { pluginExtension = null; }
  75811. return new Promise(function (resolve, reject) {
  75812. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  75813. resolve(assetContainer);
  75814. }, onProgress, function (scene, message, exception) {
  75815. reject(exception || new Error(message));
  75816. }, pluginExtension);
  75817. });
  75818. };
  75819. // Flags
  75820. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  75821. SceneLoader._ShowLoadingScreen = true;
  75822. SceneLoader._CleanBoneMatrixWeights = false;
  75823. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  75824. // Members
  75825. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  75826. SceneLoader._registeredPlugins = {};
  75827. return SceneLoader;
  75828. }());
  75829. BABYLON.SceneLoader = SceneLoader;
  75830. ;
  75831. })(BABYLON || (BABYLON = {}));
  75832. //# sourceMappingURL=babylon.sceneLoader.js.map
  75833. var BABYLON;
  75834. (function (BABYLON) {
  75835. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  75836. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  75837. var parsedMaterial = parsedData.materials[index];
  75838. if (parsedMaterial.id === id) {
  75839. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  75840. }
  75841. }
  75842. return null;
  75843. };
  75844. var isDescendantOf = function (mesh, names, hierarchyIds) {
  75845. for (var i in names) {
  75846. if (mesh.name === names[i]) {
  75847. hierarchyIds.push(mesh.id);
  75848. return true;
  75849. }
  75850. }
  75851. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  75852. hierarchyIds.push(mesh.id);
  75853. return true;
  75854. }
  75855. return false;
  75856. };
  75857. var logOperation = function (operation, producer) {
  75858. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  75859. };
  75860. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  75861. if (addToScene === void 0) { addToScene = false; }
  75862. var container = new BABYLON.AssetContainer(scene);
  75863. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  75864. // when SceneLoader.debugLogging = true (default), or exception encountered.
  75865. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  75866. // and avoid problems with multiple concurrent .babylon loads.
  75867. var log = "importScene has failed JSON parse";
  75868. try {
  75869. var parsedData = JSON.parse(data);
  75870. log = "";
  75871. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  75872. var index;
  75873. var cache;
  75874. // Lights
  75875. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  75876. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  75877. var parsedLight = parsedData.lights[index];
  75878. var light = BABYLON.Light.Parse(parsedLight, scene);
  75879. if (light) {
  75880. container.lights.push(light);
  75881. log += (index === 0 ? "\n\tLights:" : "");
  75882. log += "\n\t\t" + light.toString(fullDetails);
  75883. }
  75884. }
  75885. }
  75886. // Animations
  75887. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  75888. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  75889. var parsedAnimation = parsedData.animations[index];
  75890. var animation = BABYLON.Animation.Parse(parsedAnimation);
  75891. scene.animations.push(animation);
  75892. container.animations.push(animation);
  75893. log += (index === 0 ? "\n\tAnimations:" : "");
  75894. log += "\n\t\t" + animation.toString(fullDetails);
  75895. }
  75896. }
  75897. // Materials
  75898. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  75899. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  75900. var parsedMaterial = parsedData.materials[index];
  75901. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  75902. container.materials.push(mat);
  75903. log += (index === 0 ? "\n\tMaterials:" : "");
  75904. log += "\n\t\t" + mat.toString(fullDetails);
  75905. }
  75906. }
  75907. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  75908. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  75909. var parsedMultiMaterial = parsedData.multiMaterials[index];
  75910. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  75911. container.multiMaterials.push(mmat);
  75912. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  75913. log += "\n\t\t" + mmat.toString(fullDetails);
  75914. }
  75915. }
  75916. // Morph targets
  75917. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  75918. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  75919. var managerData = _a[_i];
  75920. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  75921. }
  75922. }
  75923. // Skeletons
  75924. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  75925. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  75926. var parsedSkeleton = parsedData.skeletons[index];
  75927. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  75928. container.skeletons.push(skeleton);
  75929. log += (index === 0 ? "\n\tSkeletons:" : "");
  75930. log += "\n\t\t" + skeleton.toString(fullDetails);
  75931. }
  75932. }
  75933. // Geometries
  75934. var geometries = parsedData.geometries;
  75935. if (geometries !== undefined && geometries !== null) {
  75936. var addedGeometry = new Array();
  75937. // Boxes
  75938. var boxes = geometries.boxes;
  75939. if (boxes !== undefined && boxes !== null) {
  75940. for (index = 0, cache = boxes.length; index < cache; index++) {
  75941. var parsedBox = boxes[index];
  75942. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  75943. }
  75944. }
  75945. // Spheres
  75946. var spheres = geometries.spheres;
  75947. if (spheres !== undefined && spheres !== null) {
  75948. for (index = 0, cache = spheres.length; index < cache; index++) {
  75949. var parsedSphere = spheres[index];
  75950. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  75951. }
  75952. }
  75953. // Cylinders
  75954. var cylinders = geometries.cylinders;
  75955. if (cylinders !== undefined && cylinders !== null) {
  75956. for (index = 0, cache = cylinders.length; index < cache; index++) {
  75957. var parsedCylinder = cylinders[index];
  75958. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  75959. }
  75960. }
  75961. // Toruses
  75962. var toruses = geometries.toruses;
  75963. if (toruses !== undefined && toruses !== null) {
  75964. for (index = 0, cache = toruses.length; index < cache; index++) {
  75965. var parsedTorus = toruses[index];
  75966. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  75967. }
  75968. }
  75969. // Grounds
  75970. var grounds = geometries.grounds;
  75971. if (grounds !== undefined && grounds !== null) {
  75972. for (index = 0, cache = grounds.length; index < cache; index++) {
  75973. var parsedGround = grounds[index];
  75974. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  75975. }
  75976. }
  75977. // Planes
  75978. var planes = geometries.planes;
  75979. if (planes !== undefined && planes !== null) {
  75980. for (index = 0, cache = planes.length; index < cache; index++) {
  75981. var parsedPlane = planes[index];
  75982. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  75983. }
  75984. }
  75985. // TorusKnots
  75986. var torusKnots = geometries.torusKnots;
  75987. if (torusKnots !== undefined && torusKnots !== null) {
  75988. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  75989. var parsedTorusKnot = torusKnots[index];
  75990. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  75991. }
  75992. }
  75993. // VertexData
  75994. var vertexData = geometries.vertexData;
  75995. if (vertexData !== undefined && vertexData !== null) {
  75996. for (index = 0, cache = vertexData.length; index < cache; index++) {
  75997. var parsedVertexData = vertexData[index];
  75998. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  75999. }
  76000. }
  76001. addedGeometry.forEach(function (g) {
  76002. if (g) {
  76003. container.geometries.push(g);
  76004. }
  76005. });
  76006. }
  76007. // Transform nodes
  76008. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  76009. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  76010. var parsedTransformNode = parsedData.transformNodes[index];
  76011. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  76012. container.transformNodes.push(node);
  76013. }
  76014. }
  76015. // Meshes
  76016. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  76017. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  76018. var parsedMesh = parsedData.meshes[index];
  76019. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  76020. container.meshes.push(mesh);
  76021. log += (index === 0 ? "\n\tMeshes:" : "");
  76022. log += "\n\t\t" + mesh.toString(fullDetails);
  76023. }
  76024. }
  76025. // Cameras
  76026. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  76027. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  76028. var parsedCamera = parsedData.cameras[index];
  76029. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  76030. container.cameras.push(camera);
  76031. log += (index === 0 ? "\n\tCameras:" : "");
  76032. log += "\n\t\t" + camera.toString(fullDetails);
  76033. }
  76034. }
  76035. // Animation Groups
  76036. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  76037. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  76038. var parsedAnimationGroup = parsedData.animationGroups[index];
  76039. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  76040. container.animationGroups.push(animationGroup);
  76041. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  76042. log += "\n\t\t" + animationGroup.toString(fullDetails);
  76043. }
  76044. }
  76045. // Browsing all the graph to connect the dots
  76046. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  76047. var camera = scene.cameras[index];
  76048. if (camera._waitingParentId) {
  76049. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  76050. camera._waitingParentId = null;
  76051. }
  76052. }
  76053. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  76054. var light_1 = scene.lights[index];
  76055. if (light_1 && light_1._waitingParentId) {
  76056. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  76057. light_1._waitingParentId = null;
  76058. }
  76059. }
  76060. // Connect parents & children and parse actions
  76061. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  76062. var transformNode = scene.transformNodes[index];
  76063. if (transformNode._waitingParentId) {
  76064. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  76065. transformNode._waitingParentId = null;
  76066. }
  76067. }
  76068. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76069. var mesh = scene.meshes[index];
  76070. if (mesh._waitingParentId) {
  76071. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  76072. mesh._waitingParentId = null;
  76073. }
  76074. }
  76075. // freeze world matrix application
  76076. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76077. var currentMesh = scene.meshes[index];
  76078. if (currentMesh._waitingFreezeWorldMatrix) {
  76079. currentMesh.freezeWorldMatrix();
  76080. currentMesh._waitingFreezeWorldMatrix = null;
  76081. }
  76082. else {
  76083. currentMesh.computeWorldMatrix(true);
  76084. }
  76085. }
  76086. // Lights exclusions / inclusions
  76087. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  76088. var light_2 = scene.lights[index];
  76089. // Excluded check
  76090. if (light_2._excludedMeshesIds.length > 0) {
  76091. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  76092. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  76093. if (excludedMesh) {
  76094. light_2.excludedMeshes.push(excludedMesh);
  76095. }
  76096. }
  76097. light_2._excludedMeshesIds = [];
  76098. }
  76099. // Included check
  76100. if (light_2._includedOnlyMeshesIds.length > 0) {
  76101. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  76102. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  76103. if (includedOnlyMesh) {
  76104. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  76105. }
  76106. }
  76107. light_2._includedOnlyMeshesIds = [];
  76108. }
  76109. }
  76110. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  76111. // Actions (scene) Done last as it can access other objects.
  76112. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76113. var mesh = scene.meshes[index];
  76114. if (mesh._waitingActions) {
  76115. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  76116. mesh._waitingActions = null;
  76117. }
  76118. }
  76119. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  76120. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  76121. }
  76122. if (!addToScene) {
  76123. container.removeAllFromScene();
  76124. }
  76125. }
  76126. catch (err) {
  76127. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  76128. if (onError) {
  76129. onError(msg, err);
  76130. }
  76131. else {
  76132. BABYLON.Tools.Log(msg);
  76133. throw err;
  76134. }
  76135. }
  76136. finally {
  76137. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  76138. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  76139. }
  76140. }
  76141. return container;
  76142. };
  76143. BABYLON.SceneLoader.RegisterPlugin({
  76144. name: "babylon.js",
  76145. extensions: ".babylon",
  76146. canDirectLoad: function (data) {
  76147. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  76148. return true;
  76149. }
  76150. return false;
  76151. },
  76152. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  76153. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  76154. // when SceneLoader.debugLogging = true (default), or exception encountered.
  76155. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  76156. // and avoid problems with multiple concurrent .babylon loads.
  76157. var log = "importMesh has failed JSON parse";
  76158. try {
  76159. var parsedData = JSON.parse(data);
  76160. log = "";
  76161. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  76162. if (!meshesNames) {
  76163. meshesNames = null;
  76164. }
  76165. else if (!Array.isArray(meshesNames)) {
  76166. meshesNames = [meshesNames];
  76167. }
  76168. var hierarchyIds = new Array();
  76169. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  76170. var loadedSkeletonsIds = [];
  76171. var loadedMaterialsIds = [];
  76172. var index;
  76173. var cache;
  76174. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  76175. var parsedMesh = parsedData.meshes[index];
  76176. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  76177. if (meshesNames !== null) {
  76178. // Remove found mesh name from list.
  76179. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  76180. }
  76181. //Geometry?
  76182. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  76183. //does the file contain geometries?
  76184. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  76185. //find the correct geometry and add it to the scene
  76186. var found = false;
  76187. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  76188. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  76189. return;
  76190. }
  76191. else {
  76192. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  76193. if (parsedGeometryData.id === parsedMesh.geometryId) {
  76194. switch (geometryType) {
  76195. case "boxes":
  76196. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  76197. break;
  76198. case "spheres":
  76199. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  76200. break;
  76201. case "cylinders":
  76202. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  76203. break;
  76204. case "toruses":
  76205. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  76206. break;
  76207. case "grounds":
  76208. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  76209. break;
  76210. case "planes":
  76211. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  76212. break;
  76213. case "torusKnots":
  76214. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  76215. break;
  76216. case "vertexData":
  76217. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  76218. break;
  76219. }
  76220. found = true;
  76221. }
  76222. });
  76223. }
  76224. });
  76225. if (found === false) {
  76226. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  76227. }
  76228. }
  76229. }
  76230. // Material ?
  76231. if (parsedMesh.materialId) {
  76232. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  76233. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  76234. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  76235. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  76236. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  76237. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  76238. var subMatId = parsedMultiMaterial.materials[matIndex];
  76239. loadedMaterialsIds.push(subMatId);
  76240. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  76241. if (mat) {
  76242. log += "\n\tMaterial " + mat.toString(fullDetails);
  76243. }
  76244. }
  76245. loadedMaterialsIds.push(parsedMultiMaterial.id);
  76246. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  76247. if (mmat) {
  76248. materialFound = true;
  76249. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  76250. }
  76251. break;
  76252. }
  76253. }
  76254. }
  76255. if (materialFound === false) {
  76256. loadedMaterialsIds.push(parsedMesh.materialId);
  76257. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  76258. if (!mat) {
  76259. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  76260. }
  76261. else {
  76262. log += "\n\tMaterial " + mat.toString(fullDetails);
  76263. }
  76264. }
  76265. }
  76266. // Skeleton ?
  76267. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  76268. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  76269. if (skeletonAlreadyLoaded === false) {
  76270. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  76271. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  76272. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  76273. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  76274. skeletons.push(skeleton);
  76275. loadedSkeletonsIds.push(parsedSkeleton.id);
  76276. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  76277. }
  76278. }
  76279. }
  76280. }
  76281. // Morph targets ?
  76282. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  76283. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  76284. var managerData = _a[_i];
  76285. BABYLON.MorphTargetManager.Parse(managerData, scene);
  76286. }
  76287. }
  76288. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  76289. meshes.push(mesh);
  76290. log += "\n\tMesh " + mesh.toString(fullDetails);
  76291. }
  76292. }
  76293. // Connecting parents
  76294. var currentMesh;
  76295. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76296. currentMesh = scene.meshes[index];
  76297. if (currentMesh._waitingParentId) {
  76298. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  76299. currentMesh._waitingParentId = null;
  76300. }
  76301. }
  76302. // freeze and compute world matrix application
  76303. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76304. currentMesh = scene.meshes[index];
  76305. if (currentMesh._waitingFreezeWorldMatrix) {
  76306. currentMesh.freezeWorldMatrix();
  76307. currentMesh._waitingFreezeWorldMatrix = null;
  76308. }
  76309. else {
  76310. currentMesh.computeWorldMatrix(true);
  76311. }
  76312. }
  76313. }
  76314. // Particles
  76315. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  76316. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  76317. if (parser) {
  76318. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  76319. var parsedParticleSystem = parsedData.particleSystems[index];
  76320. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  76321. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  76322. }
  76323. }
  76324. }
  76325. }
  76326. return true;
  76327. }
  76328. catch (err) {
  76329. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  76330. if (onError) {
  76331. onError(msg, err);
  76332. }
  76333. else {
  76334. BABYLON.Tools.Log(msg);
  76335. throw err;
  76336. }
  76337. }
  76338. finally {
  76339. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  76340. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  76341. }
  76342. }
  76343. return false;
  76344. },
  76345. load: function (scene, data, rootUrl, onError) {
  76346. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  76347. // when SceneLoader.debugLogging = true (default), or exception encountered.
  76348. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  76349. // and avoid problems with multiple concurrent .babylon loads.
  76350. var log = "importScene has failed JSON parse";
  76351. try {
  76352. var parsedData = JSON.parse(data);
  76353. log = "";
  76354. // Scene
  76355. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  76356. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  76357. }
  76358. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  76359. scene.autoClear = parsedData.autoClear;
  76360. }
  76361. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  76362. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  76363. }
  76364. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  76365. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  76366. }
  76367. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  76368. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  76369. }
  76370. // Fog
  76371. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  76372. scene.fogMode = parsedData.fogMode;
  76373. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  76374. scene.fogStart = parsedData.fogStart;
  76375. scene.fogEnd = parsedData.fogEnd;
  76376. scene.fogDensity = parsedData.fogDensity;
  76377. log += "\tFog mode for scene: ";
  76378. switch (scene.fogMode) {
  76379. // getters not compiling, so using hardcoded
  76380. case 1:
  76381. log += "exp\n";
  76382. break;
  76383. case 2:
  76384. log += "exp2\n";
  76385. break;
  76386. case 3:
  76387. log += "linear\n";
  76388. break;
  76389. }
  76390. }
  76391. //Physics
  76392. if (parsedData.physicsEnabled) {
  76393. var physicsPlugin;
  76394. if (parsedData.physicsEngine === "cannon") {
  76395. physicsPlugin = new BABYLON.CannonJSPlugin();
  76396. }
  76397. else if (parsedData.physicsEngine === "oimo") {
  76398. physicsPlugin = new BABYLON.OimoJSPlugin();
  76399. }
  76400. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  76401. //else - default engine, which is currently oimo
  76402. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  76403. scene.enablePhysics(physicsGravity, physicsPlugin);
  76404. }
  76405. // Metadata
  76406. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  76407. scene.metadata = parsedData.metadata;
  76408. }
  76409. //collisions, if defined. otherwise, default is true
  76410. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  76411. scene.collisionsEnabled = parsedData.collisionsEnabled;
  76412. }
  76413. scene.workerCollisions = !!parsedData.workerCollisions;
  76414. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  76415. if (!container) {
  76416. return false;
  76417. }
  76418. if (parsedData.autoAnimate) {
  76419. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  76420. }
  76421. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  76422. scene.setActiveCameraByID(parsedData.activeCameraID);
  76423. }
  76424. // Environment texture
  76425. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  76426. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  76427. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  76428. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  76429. if (parsedData.environmentTextureRotationY) {
  76430. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  76431. }
  76432. scene.environmentTexture = hdrTexture;
  76433. }
  76434. else {
  76435. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  76436. if (parsedData.environmentTextureRotationY) {
  76437. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  76438. }
  76439. scene.environmentTexture = cubeTexture;
  76440. }
  76441. if (parsedData.createDefaultSkybox === true) {
  76442. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  76443. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  76444. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  76445. }
  76446. }
  76447. // Finish
  76448. return true;
  76449. }
  76450. catch (err) {
  76451. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  76452. if (onError) {
  76453. onError(msg, err);
  76454. }
  76455. else {
  76456. BABYLON.Tools.Log(msg);
  76457. throw err;
  76458. }
  76459. }
  76460. finally {
  76461. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  76462. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  76463. }
  76464. }
  76465. return false;
  76466. },
  76467. loadAssetContainer: function (scene, data, rootUrl, onError) {
  76468. var container = loadAssetContainer(scene, data, rootUrl, onError);
  76469. return container;
  76470. }
  76471. });
  76472. })(BABYLON || (BABYLON = {}));
  76473. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  76474. var BABYLON;
  76475. (function (BABYLON) {
  76476. /**
  76477. * Class used to help managing file picking and drag'n'drop
  76478. */
  76479. var FilesInput = /** @class */ (function () {
  76480. /**
  76481. * Creates a new FilesInput
  76482. * @param engine defines the rendering engine
  76483. * @param scene defines the hosting scene
  76484. * @param sceneLoadedCallback callback called when scene is loaded
  76485. * @param progressCallback callback called to track progress
  76486. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  76487. * @param textureLoadingCallback callback called when a texture is loading
  76488. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  76489. * @param onReloadCallback callback called when a reload is requested
  76490. * @param errorCallback callback call if an error occurs
  76491. */
  76492. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  76493. /**
  76494. * Callback called when a file is processed
  76495. */
  76496. this.onProcessFileCallback = function () { return true; };
  76497. this._engine = engine;
  76498. this._currentScene = scene;
  76499. this._sceneLoadedCallback = sceneLoadedCallback;
  76500. this._progressCallback = progressCallback;
  76501. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  76502. this._textureLoadingCallback = textureLoadingCallback;
  76503. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  76504. this._onReloadCallback = onReloadCallback;
  76505. this._errorCallback = errorCallback;
  76506. }
  76507. /**
  76508. * Calls this function to listen to drag'n'drop events on a specific DOM element
  76509. * @param elementToMonitor defines the DOM element to track
  76510. */
  76511. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  76512. var _this = this;
  76513. if (elementToMonitor) {
  76514. this._elementToMonitor = elementToMonitor;
  76515. this._dragEnterHandler = function (e) { _this.drag(e); };
  76516. this._dragOverHandler = function (e) { _this.drag(e); };
  76517. this._dropHandler = function (e) { _this.drop(e); };
  76518. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  76519. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  76520. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  76521. }
  76522. };
  76523. /**
  76524. * Release all associated resources
  76525. */
  76526. FilesInput.prototype.dispose = function () {
  76527. if (!this._elementToMonitor) {
  76528. return;
  76529. }
  76530. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  76531. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  76532. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  76533. };
  76534. FilesInput.prototype.renderFunction = function () {
  76535. if (this._additionalRenderLoopLogicCallback) {
  76536. this._additionalRenderLoopLogicCallback();
  76537. }
  76538. if (this._currentScene) {
  76539. if (this._textureLoadingCallback) {
  76540. var remaining = this._currentScene.getWaitingItemsCount();
  76541. if (remaining > 0) {
  76542. this._textureLoadingCallback(remaining);
  76543. }
  76544. }
  76545. this._currentScene.render();
  76546. }
  76547. };
  76548. FilesInput.prototype.drag = function (e) {
  76549. e.stopPropagation();
  76550. e.preventDefault();
  76551. };
  76552. FilesInput.prototype.drop = function (eventDrop) {
  76553. eventDrop.stopPropagation();
  76554. eventDrop.preventDefault();
  76555. this.loadFiles(eventDrop);
  76556. };
  76557. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  76558. var _this = this;
  76559. var reader = folder.createReader();
  76560. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  76561. reader.readEntries(function (entries) {
  76562. remaining.count += entries.length;
  76563. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  76564. var entry = entries_1[_i];
  76565. if (entry.isFile) {
  76566. entry.file(function (file) {
  76567. file.correctName = relativePath + file.name;
  76568. files.push(file);
  76569. if (--remaining.count === 0) {
  76570. callback();
  76571. }
  76572. });
  76573. }
  76574. else if (entry.isDirectory) {
  76575. _this._traverseFolder(entry, files, remaining, callback);
  76576. }
  76577. }
  76578. if (--remaining.count) {
  76579. callback();
  76580. }
  76581. });
  76582. };
  76583. FilesInput.prototype._processFiles = function (files) {
  76584. for (var i = 0; i < files.length; i++) {
  76585. var name = files[i].correctName.toLowerCase();
  76586. var extension = name.split('.').pop();
  76587. if (!this.onProcessFileCallback(files[i], name, extension)) {
  76588. continue;
  76589. }
  76590. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  76591. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  76592. this._sceneFileToLoad = files[i];
  76593. }
  76594. FilesInput.FilesToLoad[name] = files[i];
  76595. }
  76596. };
  76597. /**
  76598. * Load files from a drop event
  76599. * @param event defines the drop event to use as source
  76600. */
  76601. FilesInput.prototype.loadFiles = function (event) {
  76602. var _this = this;
  76603. // Handling data transfer via drag'n'drop
  76604. if (event && event.dataTransfer && event.dataTransfer.files) {
  76605. this._filesToLoad = event.dataTransfer.files;
  76606. }
  76607. // Handling files from input files
  76608. if (event && event.target && event.target.files) {
  76609. this._filesToLoad = event.target.files;
  76610. }
  76611. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  76612. return;
  76613. }
  76614. if (this._startingProcessingFilesCallback) {
  76615. this._startingProcessingFilesCallback(this._filesToLoad);
  76616. }
  76617. if (this._filesToLoad && this._filesToLoad.length > 0) {
  76618. var files_1 = new Array();
  76619. var folders = [];
  76620. var items = event.dataTransfer ? event.dataTransfer.items : null;
  76621. for (var i = 0; i < this._filesToLoad.length; i++) {
  76622. var fileToLoad = this._filesToLoad[i];
  76623. var name_1 = fileToLoad.name.toLowerCase();
  76624. var entry = void 0;
  76625. fileToLoad.correctName = name_1;
  76626. if (items) {
  76627. var item = items[i];
  76628. if (item.getAsEntry) {
  76629. entry = item.getAsEntry();
  76630. }
  76631. else if (item.webkitGetAsEntry) {
  76632. entry = item.webkitGetAsEntry();
  76633. }
  76634. }
  76635. if (!entry) {
  76636. files_1.push(fileToLoad);
  76637. }
  76638. else {
  76639. if (entry.isDirectory) {
  76640. folders.push(entry);
  76641. }
  76642. else {
  76643. files_1.push(fileToLoad);
  76644. }
  76645. }
  76646. }
  76647. if (folders.length === 0) {
  76648. this._processFiles(files_1);
  76649. this._processReload();
  76650. }
  76651. else {
  76652. var remaining = { count: folders.length };
  76653. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  76654. var folder = folders_1[_i];
  76655. this._traverseFolder(folder, files_1, remaining, function () {
  76656. _this._processFiles(files_1);
  76657. if (remaining.count === 0) {
  76658. _this._processReload();
  76659. }
  76660. });
  76661. }
  76662. }
  76663. }
  76664. };
  76665. FilesInput.prototype._processReload = function () {
  76666. if (this._onReloadCallback) {
  76667. this._onReloadCallback(this._sceneFileToLoad);
  76668. }
  76669. else {
  76670. this.reload();
  76671. }
  76672. };
  76673. /**
  76674. * Reload the current scene from the loaded files
  76675. */
  76676. FilesInput.prototype.reload = function () {
  76677. var _this = this;
  76678. // If a scene file has been provided
  76679. if (this._sceneFileToLoad) {
  76680. if (this._currentScene) {
  76681. if (BABYLON.Tools.errorsCount > 0) {
  76682. BABYLON.Tools.ClearLogCache();
  76683. }
  76684. this._engine.stopRenderLoop();
  76685. }
  76686. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  76687. if (_this._progressCallback) {
  76688. _this._progressCallback(progress);
  76689. }
  76690. }).then(function (scene) {
  76691. if (_this._currentScene) {
  76692. _this._currentScene.dispose();
  76693. }
  76694. _this._currentScene = scene;
  76695. if (_this._sceneLoadedCallback) {
  76696. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  76697. }
  76698. // Wait for textures and shaders to be ready
  76699. _this._currentScene.executeWhenReady(function () {
  76700. _this._engine.runRenderLoop(function () {
  76701. _this.renderFunction();
  76702. });
  76703. });
  76704. }).catch(function (error) {
  76705. if (_this._errorCallback) {
  76706. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  76707. }
  76708. });
  76709. }
  76710. else {
  76711. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  76712. }
  76713. };
  76714. /**
  76715. * List of files ready to be loaded
  76716. */
  76717. FilesInput.FilesToLoad = {};
  76718. return FilesInput;
  76719. }());
  76720. BABYLON.FilesInput = FilesInput;
  76721. })(BABYLON || (BABYLON = {}));
  76722. //# sourceMappingURL=babylon.filesInput.js.map
  76723. var BABYLON;
  76724. (function (BABYLON) {
  76725. /**
  76726. * Class used to store custom tags
  76727. */
  76728. var Tags = /** @class */ (function () {
  76729. function Tags() {
  76730. }
  76731. /**
  76732. * Adds support for tags on the given object
  76733. * @param obj defines the object to use
  76734. */
  76735. Tags.EnableFor = function (obj) {
  76736. obj._tags = obj._tags || {};
  76737. obj.hasTags = function () {
  76738. return Tags.HasTags(obj);
  76739. };
  76740. obj.addTags = function (tagsString) {
  76741. return Tags.AddTagsTo(obj, tagsString);
  76742. };
  76743. obj.removeTags = function (tagsString) {
  76744. return Tags.RemoveTagsFrom(obj, tagsString);
  76745. };
  76746. obj.matchesTagsQuery = function (tagsQuery) {
  76747. return Tags.MatchesQuery(obj, tagsQuery);
  76748. };
  76749. };
  76750. /**
  76751. * Removes tags support
  76752. * @param obj defines the object to use
  76753. */
  76754. Tags.DisableFor = function (obj) {
  76755. delete obj._tags;
  76756. delete obj.hasTags;
  76757. delete obj.addTags;
  76758. delete obj.removeTags;
  76759. delete obj.matchesTagsQuery;
  76760. };
  76761. /**
  76762. * Gets a boolean indicating if the given object has tags
  76763. * @param obj defines the object to use
  76764. * @returns a boolean
  76765. */
  76766. Tags.HasTags = function (obj) {
  76767. if (!obj._tags) {
  76768. return false;
  76769. }
  76770. return !BABYLON.Tools.IsEmpty(obj._tags);
  76771. };
  76772. /**
  76773. * Gets the tags available on a given object
  76774. * @param obj defines the object to use
  76775. * @param asString defines if the tags must be returned as a string instead of an array of strings
  76776. * @returns the tags
  76777. */
  76778. Tags.GetTags = function (obj, asString) {
  76779. if (asString === void 0) { asString = true; }
  76780. if (!obj._tags) {
  76781. return null;
  76782. }
  76783. if (asString) {
  76784. var tagsArray = [];
  76785. for (var tag in obj._tags) {
  76786. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  76787. tagsArray.push(tag);
  76788. }
  76789. }
  76790. return tagsArray.join(" ");
  76791. }
  76792. else {
  76793. return obj._tags;
  76794. }
  76795. };
  76796. /**
  76797. * Adds tags to an object
  76798. * @param obj defines the object to use
  76799. * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
  76800. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
  76801. */
  76802. Tags.AddTagsTo = function (obj, tagsString) {
  76803. if (!tagsString) {
  76804. return;
  76805. }
  76806. if (typeof tagsString !== "string") {
  76807. return;
  76808. }
  76809. var tags = tagsString.split(" ");
  76810. tags.forEach(function (tag, index, array) {
  76811. Tags._AddTagTo(obj, tag);
  76812. });
  76813. };
  76814. /**
  76815. * @hidden
  76816. */
  76817. Tags._AddTagTo = function (obj, tag) {
  76818. tag = tag.trim();
  76819. if (tag === "" || tag === "true" || tag === "false") {
  76820. return;
  76821. }
  76822. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  76823. return;
  76824. }
  76825. Tags.EnableFor(obj);
  76826. obj._tags[tag] = true;
  76827. };
  76828. /**
  76829. * Removes specific tags from a specific object
  76830. * @param obj defines the object to use
  76831. * @param tagsString defines the tags to remove
  76832. */
  76833. Tags.RemoveTagsFrom = function (obj, tagsString) {
  76834. if (!Tags.HasTags(obj)) {
  76835. return;
  76836. }
  76837. var tags = tagsString.split(" ");
  76838. for (var t in tags) {
  76839. Tags._RemoveTagFrom(obj, tags[t]);
  76840. }
  76841. };
  76842. /**
  76843. * @hidden
  76844. */
  76845. Tags._RemoveTagFrom = function (obj, tag) {
  76846. delete obj._tags[tag];
  76847. };
  76848. /**
  76849. * Defines if tags hosted on an object match a given query
  76850. * @param obj defines the object to use
  76851. * @param tagsQuery defines the tag query
  76852. * @returns a boolean
  76853. */
  76854. Tags.MatchesQuery = function (obj, tagsQuery) {
  76855. if (tagsQuery === undefined) {
  76856. return true;
  76857. }
  76858. if (tagsQuery === "") {
  76859. return Tags.HasTags(obj);
  76860. }
  76861. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  76862. };
  76863. return Tags;
  76864. }());
  76865. BABYLON.Tags = Tags;
  76866. })(BABYLON || (BABYLON = {}));
  76867. //# sourceMappingURL=babylon.tags.js.map
  76868. var BABYLON;
  76869. (function (BABYLON) {
  76870. /**
  76871. * Class used to evalaute queries containing `and` and `or` operators
  76872. */
  76873. var AndOrNotEvaluator = /** @class */ (function () {
  76874. function AndOrNotEvaluator() {
  76875. }
  76876. /**
  76877. * Evaluate a query
  76878. * @param query defines the query to evaluate
  76879. * @param evaluateCallback defines the callback used to filter result
  76880. * @returns true if the query matches
  76881. */
  76882. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  76883. if (!query.match(/\([^\(\)]*\)/g)) {
  76884. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  76885. }
  76886. else {
  76887. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  76888. // remove parenthesis
  76889. r = r.slice(1, r.length - 1);
  76890. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  76891. });
  76892. }
  76893. if (query === "true") {
  76894. return true;
  76895. }
  76896. if (query === "false") {
  76897. return false;
  76898. }
  76899. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  76900. };
  76901. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  76902. evaluateCallback = evaluateCallback || (function (r) {
  76903. return r === "true" ? true : false;
  76904. });
  76905. var result;
  76906. var or = parenthesisContent.split("||");
  76907. for (var i in or) {
  76908. if (or.hasOwnProperty(i)) {
  76909. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  76910. var and = ori.split("&&");
  76911. if (and.length > 1) {
  76912. for (var j = 0; j < and.length; ++j) {
  76913. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  76914. if (andj !== "true" && andj !== "false") {
  76915. if (andj[0] === "!") {
  76916. result = !evaluateCallback(andj.substring(1));
  76917. }
  76918. else {
  76919. result = evaluateCallback(andj);
  76920. }
  76921. }
  76922. else {
  76923. result = andj === "true" ? true : false;
  76924. }
  76925. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  76926. ori = "false";
  76927. break;
  76928. }
  76929. }
  76930. }
  76931. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  76932. result = true;
  76933. break;
  76934. }
  76935. // result equals false (or undefined)
  76936. if (ori !== "true" && ori !== "false") {
  76937. if (ori[0] === "!") {
  76938. result = !evaluateCallback(ori.substring(1));
  76939. }
  76940. else {
  76941. result = evaluateCallback(ori);
  76942. }
  76943. }
  76944. else {
  76945. result = ori === "true" ? true : false;
  76946. }
  76947. }
  76948. }
  76949. // the whole parenthesis scope is replaced by 'true' or 'false'
  76950. return result ? "true" : "false";
  76951. };
  76952. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  76953. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  76954. // remove whitespaces
  76955. r = r.replace(/[\s]/g, function () { return ""; });
  76956. return r.length % 2 ? "!" : "";
  76957. });
  76958. booleanString = booleanString.trim();
  76959. if (booleanString === "!true") {
  76960. booleanString = "false";
  76961. }
  76962. else if (booleanString === "!false") {
  76963. booleanString = "true";
  76964. }
  76965. return booleanString;
  76966. };
  76967. return AndOrNotEvaluator;
  76968. }());
  76969. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  76970. })(BABYLON || (BABYLON = {}));
  76971. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  76972. var BABYLON;
  76973. (function (BABYLON) {
  76974. /**
  76975. * Class used to enable access to IndexedDB
  76976. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  76977. */
  76978. var Database = /** @class */ (function () {
  76979. /**
  76980. * Creates a new Database
  76981. * @param urlToScene defines the url to load the scene
  76982. * @param callbackManifestChecked defines the callback to use when manifest is checked
  76983. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  76984. */
  76985. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  76986. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  76987. var _this = this;
  76988. // Handling various flavors of prefixed version of IndexedDB
  76989. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  76990. this.callbackManifestChecked = callbackManifestChecked;
  76991. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  76992. this.db = null;
  76993. this._enableSceneOffline = false;
  76994. this._enableTexturesOffline = false;
  76995. this.manifestVersionFound = 0;
  76996. this.mustUpdateRessources = false;
  76997. this.hasReachedQuota = false;
  76998. if (!Database.IDBStorageEnabled) {
  76999. this.callbackManifestChecked(true);
  77000. }
  77001. else {
  77002. if (disableManifestCheck) {
  77003. this._enableSceneOffline = true;
  77004. this._enableTexturesOffline = true;
  77005. this.manifestVersionFound = 1;
  77006. BABYLON.Tools.SetImmediate(function () {
  77007. _this.callbackManifestChecked(true);
  77008. });
  77009. }
  77010. else {
  77011. this._checkManifestFile();
  77012. }
  77013. }
  77014. }
  77015. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  77016. /**
  77017. * Gets a boolean indicating if scene must be saved in the database
  77018. */
  77019. get: function () {
  77020. return this._enableSceneOffline;
  77021. },
  77022. enumerable: true,
  77023. configurable: true
  77024. });
  77025. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  77026. /**
  77027. * Gets a boolean indicating if textures must be saved in the database
  77028. */
  77029. get: function () {
  77030. return this._enableTexturesOffline;
  77031. },
  77032. enumerable: true,
  77033. configurable: true
  77034. });
  77035. Database.prototype._checkManifestFile = function () {
  77036. var _this = this;
  77037. var noManifestFile = function () {
  77038. _this._enableSceneOffline = false;
  77039. _this._enableTexturesOffline = false;
  77040. _this.callbackManifestChecked(false);
  77041. };
  77042. var timeStampUsed = false;
  77043. var manifestURL = this.currentSceneUrl + ".manifest";
  77044. var xhr = new XMLHttpRequest();
  77045. if (navigator.onLine) {
  77046. // Adding a timestamp to by-pass browsers' cache
  77047. timeStampUsed = true;
  77048. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  77049. }
  77050. xhr.open("GET", manifestURL, true);
  77051. xhr.addEventListener("load", function () {
  77052. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  77053. try {
  77054. var manifestFile = JSON.parse(xhr.response);
  77055. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  77056. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  77057. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  77058. _this.manifestVersionFound = manifestFile.version;
  77059. }
  77060. if (_this.callbackManifestChecked) {
  77061. _this.callbackManifestChecked(true);
  77062. }
  77063. }
  77064. catch (ex) {
  77065. noManifestFile();
  77066. }
  77067. }
  77068. else {
  77069. noManifestFile();
  77070. }
  77071. }, false);
  77072. xhr.addEventListener("error", function (event) {
  77073. if (timeStampUsed) {
  77074. timeStampUsed = false;
  77075. // Let's retry without the timeStamp
  77076. // It could fail when coupled with HTML5 Offline API
  77077. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  77078. xhr.open("GET", retryManifestURL, true);
  77079. xhr.send();
  77080. }
  77081. else {
  77082. noManifestFile();
  77083. }
  77084. }, false);
  77085. try {
  77086. xhr.send();
  77087. }
  77088. catch (ex) {
  77089. BABYLON.Tools.Error("Error on XHR send request.");
  77090. this.callbackManifestChecked(false);
  77091. }
  77092. };
  77093. /**
  77094. * Open the database and make it available
  77095. * @param successCallback defines the callback to call on success
  77096. * @param errorCallback defines the callback to call on error
  77097. */
  77098. Database.prototype.openAsync = function (successCallback, errorCallback) {
  77099. var _this = this;
  77100. var handleError = function () {
  77101. _this.isSupported = false;
  77102. if (errorCallback)
  77103. errorCallback();
  77104. };
  77105. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  77106. // Your browser doesn't support IndexedDB
  77107. this.isSupported = false;
  77108. if (errorCallback)
  77109. errorCallback();
  77110. }
  77111. else {
  77112. // If the DB hasn't been opened or created yet
  77113. if (!this.db) {
  77114. this.hasReachedQuota = false;
  77115. this.isSupported = true;
  77116. var request = this.idbFactory.open("babylonjs", 1);
  77117. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  77118. request.onerror = function (event) {
  77119. handleError();
  77120. };
  77121. // executes when a version change transaction cannot complete due to other active transactions
  77122. request.onblocked = function (event) {
  77123. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  77124. handleError();
  77125. };
  77126. // DB has been opened successfully
  77127. request.onsuccess = function (event) {
  77128. _this.db = request.result;
  77129. successCallback();
  77130. };
  77131. // Initialization of the DB. Creating Scenes & Textures stores
  77132. request.onupgradeneeded = function (event) {
  77133. _this.db = (event.target).result;
  77134. if (_this.db) {
  77135. try {
  77136. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  77137. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  77138. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  77139. }
  77140. catch (ex) {
  77141. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  77142. handleError();
  77143. }
  77144. }
  77145. };
  77146. }
  77147. // DB has already been created and opened
  77148. else {
  77149. if (successCallback)
  77150. successCallback();
  77151. }
  77152. }
  77153. };
  77154. /**
  77155. * Loads an image from the database
  77156. * @param url defines the url to load from
  77157. * @param image defines the target DOM image
  77158. */
  77159. Database.prototype.loadImageFromDB = function (url, image) {
  77160. var _this = this;
  77161. var completeURL = Database._ReturnFullUrlLocation(url);
  77162. var saveAndLoadImage = function () {
  77163. if (!_this.hasReachedQuota && _this.db !== null) {
  77164. // the texture is not yet in the DB, let's try to save it
  77165. _this._saveImageIntoDBAsync(completeURL, image);
  77166. }
  77167. // If the texture is not in the DB and we've reached the DB quota limit
  77168. // let's load it directly from the web
  77169. else {
  77170. image.src = url;
  77171. }
  77172. };
  77173. if (!this.mustUpdateRessources) {
  77174. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  77175. }
  77176. // First time we're download the images or update requested in the manifest file by a version change
  77177. else {
  77178. saveAndLoadImage();
  77179. }
  77180. };
  77181. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  77182. if (this.isSupported && this.db !== null) {
  77183. var texture;
  77184. var transaction = this.db.transaction(["textures"]);
  77185. transaction.onabort = function (event) {
  77186. image.src = url;
  77187. };
  77188. transaction.oncomplete = function (event) {
  77189. var blobTextureURL;
  77190. if (texture) {
  77191. var URL = window.URL || window.webkitURL;
  77192. blobTextureURL = URL.createObjectURL(texture.data);
  77193. image.onerror = function () {
  77194. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  77195. image.src = url;
  77196. };
  77197. image.src = blobTextureURL;
  77198. }
  77199. else {
  77200. notInDBCallback();
  77201. }
  77202. };
  77203. var getRequest = transaction.objectStore("textures").get(url);
  77204. getRequest.onsuccess = function (event) {
  77205. texture = (event.target).result;
  77206. };
  77207. getRequest.onerror = function (event) {
  77208. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  77209. image.src = url;
  77210. };
  77211. }
  77212. else {
  77213. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  77214. image.src = url;
  77215. }
  77216. };
  77217. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  77218. var _this = this;
  77219. if (this.isSupported) {
  77220. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  77221. var generateBlobUrl = function () {
  77222. var blobTextureURL;
  77223. if (blob) {
  77224. var URL = window.URL || window.webkitURL;
  77225. try {
  77226. blobTextureURL = URL.createObjectURL(blob);
  77227. }
  77228. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  77229. catch (ex) {
  77230. blobTextureURL = URL.createObjectURL(blob);
  77231. }
  77232. }
  77233. if (blobTextureURL) {
  77234. image.src = blobTextureURL;
  77235. }
  77236. };
  77237. if (Database.IsUASupportingBlobStorage) { // Create XHR
  77238. var xhr = new XMLHttpRequest(), blob;
  77239. xhr.open("GET", url, true);
  77240. xhr.responseType = "blob";
  77241. xhr.addEventListener("load", function () {
  77242. if (xhr.status === 200 && _this.db) {
  77243. // Blob as response (XHR2)
  77244. blob = xhr.response;
  77245. var transaction = _this.db.transaction(["textures"], "readwrite");
  77246. // the transaction could abort because of a QuotaExceededError error
  77247. transaction.onabort = function (event) {
  77248. try {
  77249. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  77250. var srcElement = (event.srcElement || event.target);
  77251. var error = srcElement.error;
  77252. if (error && error.name === "QuotaExceededError") {
  77253. _this.hasReachedQuota = true;
  77254. }
  77255. }
  77256. catch (ex) { }
  77257. generateBlobUrl();
  77258. };
  77259. transaction.oncomplete = function (event) {
  77260. generateBlobUrl();
  77261. };
  77262. var newTexture = { textureUrl: url, data: blob };
  77263. try {
  77264. // Put the blob into the dabase
  77265. var addRequest = transaction.objectStore("textures").put(newTexture);
  77266. addRequest.onsuccess = function (event) {
  77267. };
  77268. addRequest.onerror = function (event) {
  77269. generateBlobUrl();
  77270. };
  77271. }
  77272. catch (ex) {
  77273. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  77274. if (ex.code === 25) {
  77275. Database.IsUASupportingBlobStorage = false;
  77276. }
  77277. image.src = url;
  77278. }
  77279. }
  77280. else {
  77281. image.src = url;
  77282. }
  77283. }, false);
  77284. xhr.addEventListener("error", function (event) {
  77285. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  77286. image.src = url;
  77287. }, false);
  77288. xhr.send();
  77289. }
  77290. else {
  77291. image.src = url;
  77292. }
  77293. }
  77294. else {
  77295. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  77296. image.src = url;
  77297. }
  77298. };
  77299. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  77300. var _this = this;
  77301. var updateVersion = function () {
  77302. // the version is not yet in the DB or we need to update it
  77303. _this._saveVersionIntoDBAsync(url, versionLoaded);
  77304. };
  77305. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  77306. };
  77307. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  77308. var _this = this;
  77309. if (this.isSupported && this.db) {
  77310. var version;
  77311. try {
  77312. var transaction = this.db.transaction(["versions"]);
  77313. transaction.oncomplete = function (event) {
  77314. if (version) {
  77315. // If the version in the JSON file is different from the version in DB
  77316. if (_this.manifestVersionFound !== version.data) {
  77317. _this.mustUpdateRessources = true;
  77318. updateInDBCallback();
  77319. }
  77320. else {
  77321. callback(version.data);
  77322. }
  77323. }
  77324. // version was not found in DB
  77325. else {
  77326. _this.mustUpdateRessources = true;
  77327. updateInDBCallback();
  77328. }
  77329. };
  77330. transaction.onabort = function (event) {
  77331. callback(-1);
  77332. };
  77333. var getRequest = transaction.objectStore("versions").get(url);
  77334. getRequest.onsuccess = function (event) {
  77335. version = (event.target).result;
  77336. };
  77337. getRequest.onerror = function (event) {
  77338. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  77339. callback(-1);
  77340. };
  77341. }
  77342. catch (ex) {
  77343. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  77344. callback(-1);
  77345. }
  77346. }
  77347. else {
  77348. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  77349. callback(-1);
  77350. }
  77351. };
  77352. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  77353. var _this = this;
  77354. if (this.isSupported && !this.hasReachedQuota && this.db) {
  77355. try {
  77356. // Open a transaction to the database
  77357. var transaction = this.db.transaction(["versions"], "readwrite");
  77358. // the transaction could abort because of a QuotaExceededError error
  77359. transaction.onabort = function (event) {
  77360. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  77361. var error = event.srcElement['error'];
  77362. if (error && error.name === "QuotaExceededError") {
  77363. _this.hasReachedQuota = true;
  77364. }
  77365. }
  77366. catch (ex) { }
  77367. callback(-1);
  77368. };
  77369. transaction.oncomplete = function (event) {
  77370. callback(_this.manifestVersionFound);
  77371. };
  77372. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  77373. // Put the scene into the database
  77374. var addRequest = transaction.objectStore("versions").put(newVersion);
  77375. addRequest.onsuccess = function (event) {
  77376. };
  77377. addRequest.onerror = function (event) {
  77378. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  77379. };
  77380. }
  77381. catch (ex) {
  77382. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  77383. callback(-1);
  77384. }
  77385. }
  77386. else {
  77387. callback(-1);
  77388. }
  77389. };
  77390. /**
  77391. * Loads a file from database
  77392. * @param url defines the URL to load from
  77393. * @param sceneLoaded defines a callback to call on success
  77394. * @param progressCallBack defines a callback to call when progress changed
  77395. * @param errorCallback defines a callback to call on error
  77396. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  77397. */
  77398. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  77399. var _this = this;
  77400. var completeUrl = Database._ReturnFullUrlLocation(url);
  77401. var saveAndLoadFile = function () {
  77402. // the scene is not yet in the DB, let's try to save it
  77403. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  77404. };
  77405. this._checkVersionFromDB(completeUrl, function (version) {
  77406. if (version !== -1) {
  77407. if (!_this.mustUpdateRessources) {
  77408. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  77409. }
  77410. else {
  77411. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  77412. }
  77413. }
  77414. else {
  77415. if (errorCallback) {
  77416. errorCallback();
  77417. }
  77418. }
  77419. });
  77420. };
  77421. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  77422. if (this.isSupported && this.db) {
  77423. var targetStore;
  77424. if (url.indexOf(".babylon") !== -1) {
  77425. targetStore = "scenes";
  77426. }
  77427. else {
  77428. targetStore = "textures";
  77429. }
  77430. var file;
  77431. var transaction = this.db.transaction([targetStore]);
  77432. transaction.oncomplete = function (event) {
  77433. if (file) {
  77434. callback(file.data);
  77435. }
  77436. // file was not found in DB
  77437. else {
  77438. notInDBCallback();
  77439. }
  77440. };
  77441. transaction.onabort = function (event) {
  77442. notInDBCallback();
  77443. };
  77444. var getRequest = transaction.objectStore(targetStore).get(url);
  77445. getRequest.onsuccess = function (event) {
  77446. file = (event.target).result;
  77447. };
  77448. getRequest.onerror = function (event) {
  77449. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  77450. notInDBCallback();
  77451. };
  77452. }
  77453. else {
  77454. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  77455. callback();
  77456. }
  77457. };
  77458. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  77459. var _this = this;
  77460. if (this.isSupported) {
  77461. var targetStore;
  77462. if (url.indexOf(".babylon") !== -1) {
  77463. targetStore = "scenes";
  77464. }
  77465. else {
  77466. targetStore = "textures";
  77467. }
  77468. // Create XHR
  77469. var xhr = new XMLHttpRequest();
  77470. var fileData;
  77471. xhr.open("GET", url + "?" + Date.now(), true);
  77472. if (useArrayBuffer) {
  77473. xhr.responseType = "arraybuffer";
  77474. }
  77475. if (progressCallback) {
  77476. xhr.onprogress = progressCallback;
  77477. }
  77478. xhr.addEventListener("load", function () {
  77479. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  77480. // Blob as response (XHR2)
  77481. //fileData = xhr.responseText;
  77482. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  77483. if (!_this.hasReachedQuota && _this.db) {
  77484. // Open a transaction to the database
  77485. var transaction = _this.db.transaction([targetStore], "readwrite");
  77486. // the transaction could abort because of a QuotaExceededError error
  77487. transaction.onabort = function (event) {
  77488. try {
  77489. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  77490. var error = event.srcElement['error'];
  77491. if (error && error.name === "QuotaExceededError") {
  77492. _this.hasReachedQuota = true;
  77493. }
  77494. }
  77495. catch (ex) { }
  77496. callback(fileData);
  77497. };
  77498. transaction.oncomplete = function (event) {
  77499. callback(fileData);
  77500. };
  77501. var newFile;
  77502. if (targetStore === "scenes") {
  77503. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  77504. }
  77505. else {
  77506. newFile = { textureUrl: url, data: fileData };
  77507. }
  77508. try {
  77509. // Put the scene into the database
  77510. var addRequest = transaction.objectStore(targetStore).put(newFile);
  77511. addRequest.onsuccess = function (event) {
  77512. };
  77513. addRequest.onerror = function (event) {
  77514. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  77515. };
  77516. }
  77517. catch (ex) {
  77518. callback(fileData);
  77519. }
  77520. }
  77521. else {
  77522. callback(fileData);
  77523. }
  77524. }
  77525. else {
  77526. if (xhr.status >= 400 && errorCallback) {
  77527. errorCallback(xhr);
  77528. }
  77529. else {
  77530. callback();
  77531. }
  77532. }
  77533. }, false);
  77534. xhr.addEventListener("error", function (event) {
  77535. BABYLON.Tools.Error("error on XHR request.");
  77536. callback();
  77537. }, false);
  77538. xhr.send();
  77539. }
  77540. else {
  77541. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  77542. callback();
  77543. }
  77544. };
  77545. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  77546. Database.IsUASupportingBlobStorage = true;
  77547. /** Gets a boolean indicating if Database storate is enabled */
  77548. Database.IDBStorageEnabled = true;
  77549. Database._ParseURL = function (url) {
  77550. var a = document.createElement('a');
  77551. a.href = url;
  77552. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  77553. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  77554. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  77555. return absLocation;
  77556. };
  77557. Database._ReturnFullUrlLocation = function (url) {
  77558. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  77559. return (Database._ParseURL(window.location.href) + url);
  77560. }
  77561. else {
  77562. return url;
  77563. }
  77564. };
  77565. return Database;
  77566. }());
  77567. BABYLON.Database = Database;
  77568. })(BABYLON || (BABYLON = {}));
  77569. //# sourceMappingURL=babylon.database.js.map
  77570. var BABYLON;
  77571. (function (BABYLON) {
  77572. /**
  77573. * This represents all the required information to add a fresnel effect on a material:
  77574. * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters
  77575. */
  77576. var FresnelParameters = /** @class */ (function () {
  77577. function FresnelParameters() {
  77578. this._isEnabled = true;
  77579. /**
  77580. * Define the color used on edges (grazing angle)
  77581. */
  77582. this.leftColor = BABYLON.Color3.White();
  77583. /**
  77584. * Define the color used on center
  77585. */
  77586. this.rightColor = BABYLON.Color3.Black();
  77587. /**
  77588. * Define bias applied to computed fresnel term
  77589. */
  77590. this.bias = 0;
  77591. /**
  77592. * Defined the power exponent applied to fresnel term
  77593. */
  77594. this.power = 1;
  77595. }
  77596. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  77597. /**
  77598. * Define if the fresnel effect is enable or not.
  77599. */
  77600. get: function () {
  77601. return this._isEnabled;
  77602. },
  77603. set: function (value) {
  77604. if (this._isEnabled === value) {
  77605. return;
  77606. }
  77607. this._isEnabled = value;
  77608. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  77609. },
  77610. enumerable: true,
  77611. configurable: true
  77612. });
  77613. /**
  77614. * Clones the current fresnel and its valuues
  77615. * @returns a clone fresnel configuration
  77616. */
  77617. FresnelParameters.prototype.clone = function () {
  77618. var newFresnelParameters = new FresnelParameters();
  77619. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  77620. return newFresnelParameters;
  77621. };
  77622. /**
  77623. * Serializes the current fresnel parameters to a JSON representation.
  77624. * @return the JSON serialization
  77625. */
  77626. FresnelParameters.prototype.serialize = function () {
  77627. var serializationObject = {};
  77628. serializationObject.isEnabled = this.isEnabled;
  77629. serializationObject.leftColor = this.leftColor.asArray();
  77630. serializationObject.rightColor = this.rightColor.asArray();
  77631. serializationObject.bias = this.bias;
  77632. serializationObject.power = this.power;
  77633. return serializationObject;
  77634. };
  77635. /**
  77636. * Parse a JSON object and deserialize it to a new Fresnel parameter object.
  77637. * @param parsedFresnelParameters Define the JSON representation
  77638. * @returns the parsed parameters
  77639. */
  77640. FresnelParameters.Parse = function (parsedFresnelParameters) {
  77641. var fresnelParameters = new FresnelParameters();
  77642. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  77643. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  77644. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  77645. fresnelParameters.bias = parsedFresnelParameters.bias;
  77646. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  77647. return fresnelParameters;
  77648. };
  77649. return FresnelParameters;
  77650. }());
  77651. BABYLON.FresnelParameters = FresnelParameters;
  77652. })(BABYLON || (BABYLON = {}));
  77653. //# sourceMappingURL=babylon.fresnelParameters.js.map
  77654. var BABYLON;
  77655. (function (BABYLON) {
  77656. /**
  77657. * A multi-material is used to apply different materials to different parts of the same object without the need of
  77658. * separate meshes. This can be use to improve performances.
  77659. * @see http://doc.babylonjs.com/how_to/multi_materials
  77660. */
  77661. var MultiMaterial = /** @class */ (function (_super) {
  77662. __extends(MultiMaterial, _super);
  77663. /**
  77664. * Instantiates a new Multi Material
  77665. * A multi-material is used to apply different materials to different parts of the same object without the need of
  77666. * separate meshes. This can be use to improve performances.
  77667. * @see http://doc.babylonjs.com/how_to/multi_materials
  77668. * @param name Define the name in the scene
  77669. * @param scene Define the scene the material belongs to
  77670. */
  77671. function MultiMaterial(name, scene) {
  77672. var _this = _super.call(this, name, scene, true) || this;
  77673. scene.multiMaterials.push(_this);
  77674. _this.subMaterials = new Array();
  77675. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  77676. return _this;
  77677. }
  77678. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  77679. /**
  77680. * Gets or Sets the list of Materials used within the multi material.
  77681. * They need to be ordered according to the submeshes order in the associated mesh
  77682. */
  77683. get: function () {
  77684. return this._subMaterials;
  77685. },
  77686. set: function (value) {
  77687. this._subMaterials = value;
  77688. this._hookArray(value);
  77689. },
  77690. enumerable: true,
  77691. configurable: true
  77692. });
  77693. MultiMaterial.prototype._hookArray = function (array) {
  77694. var _this = this;
  77695. var oldPush = array.push;
  77696. array.push = function () {
  77697. var items = [];
  77698. for (var _i = 0; _i < arguments.length; _i++) {
  77699. items[_i] = arguments[_i];
  77700. }
  77701. var result = oldPush.apply(array, items);
  77702. _this._markAllSubMeshesAsTexturesDirty();
  77703. return result;
  77704. };
  77705. var oldSplice = array.splice;
  77706. array.splice = function (index, deleteCount) {
  77707. var deleted = oldSplice.apply(array, [index, deleteCount]);
  77708. _this._markAllSubMeshesAsTexturesDirty();
  77709. return deleted;
  77710. };
  77711. };
  77712. /**
  77713. * Get one of the submaterial by its index in the submaterials array
  77714. * @param index The index to look the sub material at
  77715. * @returns The Material if the index has been defined
  77716. */
  77717. MultiMaterial.prototype.getSubMaterial = function (index) {
  77718. if (index < 0 || index >= this.subMaterials.length) {
  77719. return this.getScene().defaultMaterial;
  77720. }
  77721. return this.subMaterials[index];
  77722. };
  77723. /**
  77724. * Get the list of active textures for the whole sub materials list.
  77725. * @returns All the textures that will be used during the rendering
  77726. */
  77727. MultiMaterial.prototype.getActiveTextures = function () {
  77728. var _a;
  77729. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  77730. if (subMaterial) {
  77731. return subMaterial.getActiveTextures();
  77732. }
  77733. else {
  77734. return [];
  77735. }
  77736. }));
  77737. };
  77738. /**
  77739. * Gets the current class name of the material e.g. "MultiMaterial"
  77740. * Mainly use in serialization.
  77741. * @returns the class name
  77742. */
  77743. MultiMaterial.prototype.getClassName = function () {
  77744. return "MultiMaterial";
  77745. };
  77746. /**
  77747. * Checks if the material is ready to render the requested sub mesh
  77748. * @param mesh Define the mesh the submesh belongs to
  77749. * @param subMesh Define the sub mesh to look readyness for
  77750. * @param useInstances Define whether or not the material is used with instances
  77751. * @returns true if ready, otherwise false
  77752. */
  77753. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  77754. for (var index = 0; index < this.subMaterials.length; index++) {
  77755. var subMaterial = this.subMaterials[index];
  77756. if (subMaterial) {
  77757. if (subMaterial.storeEffectOnSubMeshes) {
  77758. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  77759. return false;
  77760. }
  77761. continue;
  77762. }
  77763. if (!subMaterial.isReady(mesh)) {
  77764. return false;
  77765. }
  77766. }
  77767. }
  77768. return true;
  77769. };
  77770. /**
  77771. * Clones the current material and its related sub materials
  77772. * @param name Define the name of the newly cloned material
  77773. * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance
  77774. * @returns the cloned material
  77775. */
  77776. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  77777. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  77778. for (var index = 0; index < this.subMaterials.length; index++) {
  77779. var subMaterial = null;
  77780. var current = this.subMaterials[index];
  77781. if (cloneChildren && current) {
  77782. subMaterial = current.clone(name + "-" + current.name);
  77783. }
  77784. else {
  77785. subMaterial = this.subMaterials[index];
  77786. }
  77787. newMultiMaterial.subMaterials.push(subMaterial);
  77788. }
  77789. return newMultiMaterial;
  77790. };
  77791. /**
  77792. * Serializes the materials into a JSON representation.
  77793. * @returns the JSON representation
  77794. */
  77795. MultiMaterial.prototype.serialize = function () {
  77796. var serializationObject = {};
  77797. serializationObject.name = this.name;
  77798. serializationObject.id = this.id;
  77799. if (BABYLON.Tags) {
  77800. serializationObject.tags = BABYLON.Tags.GetTags(this);
  77801. }
  77802. serializationObject.materials = [];
  77803. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  77804. var subMat = this.subMaterials[matIndex];
  77805. if (subMat) {
  77806. serializationObject.materials.push(subMat.id);
  77807. }
  77808. else {
  77809. serializationObject.materials.push(null);
  77810. }
  77811. }
  77812. return serializationObject;
  77813. };
  77814. /**
  77815. * Dispose the material and release its associated resources
  77816. * @param forceDisposeEffect Define if we want to force disposing the associated effect (if false the shader is not released and could be reuse later on)
  77817. * @param forceDisposeTextures Define if we want to force disposing the associated textures (if false, they will not be disposed and can still be use elsewhere in the app)
  77818. */
  77819. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  77820. var scene = this.getScene();
  77821. if (!scene) {
  77822. return;
  77823. }
  77824. var index = scene.multiMaterials.indexOf(this);
  77825. if (index >= 0) {
  77826. scene.multiMaterials.splice(index, 1);
  77827. }
  77828. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  77829. };
  77830. return MultiMaterial;
  77831. }(BABYLON.Material));
  77832. BABYLON.MultiMaterial = MultiMaterial;
  77833. })(BABYLON || (BABYLON = {}));
  77834. //# sourceMappingURL=babylon.multiMaterial.js.map
  77835. var BABYLON;
  77836. (function (BABYLON) {
  77837. /**
  77838. * Manage the touch inputs to control the movement of a free camera.
  77839. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  77840. */
  77841. var FreeCameraTouchInput = /** @class */ (function () {
  77842. function FreeCameraTouchInput() {
  77843. /**
  77844. * Defines the touch sensibility for rotation.
  77845. * The higher the faster.
  77846. */
  77847. this.touchAngularSensibility = 200000.0;
  77848. /**
  77849. * Defines the touch sensibility for move.
  77850. * The higher the faster.
  77851. */
  77852. this.touchMoveSensibility = 250.0;
  77853. this._offsetX = null;
  77854. this._offsetY = null;
  77855. this._pointerPressed = new Array();
  77856. }
  77857. /**
  77858. * Attach the input controls to a specific dom element to get the input from.
  77859. * @param element Defines the element the controls should be listened from
  77860. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  77861. */
  77862. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  77863. var _this = this;
  77864. var previousPosition = null;
  77865. if (this._pointerInput === undefined) {
  77866. this._onLostFocus = function (evt) {
  77867. _this._offsetX = null;
  77868. _this._offsetY = null;
  77869. };
  77870. this._pointerInput = function (p, s) {
  77871. var evt = p.event;
  77872. if (evt.pointerType === "mouse") {
  77873. return;
  77874. }
  77875. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  77876. if (!noPreventDefault) {
  77877. evt.preventDefault();
  77878. }
  77879. _this._pointerPressed.push(evt.pointerId);
  77880. if (_this._pointerPressed.length !== 1) {
  77881. return;
  77882. }
  77883. previousPosition = {
  77884. x: evt.clientX,
  77885. y: evt.clientY
  77886. };
  77887. }
  77888. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  77889. if (!noPreventDefault) {
  77890. evt.preventDefault();
  77891. }
  77892. var index = _this._pointerPressed.indexOf(evt.pointerId);
  77893. if (index === -1) {
  77894. return;
  77895. }
  77896. _this._pointerPressed.splice(index, 1);
  77897. if (index != 0) {
  77898. return;
  77899. }
  77900. previousPosition = null;
  77901. _this._offsetX = null;
  77902. _this._offsetY = null;
  77903. }
  77904. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  77905. if (!noPreventDefault) {
  77906. evt.preventDefault();
  77907. }
  77908. if (!previousPosition) {
  77909. return;
  77910. }
  77911. var index = _this._pointerPressed.indexOf(evt.pointerId);
  77912. if (index != 0) {
  77913. return;
  77914. }
  77915. _this._offsetX = evt.clientX - previousPosition.x;
  77916. _this._offsetY = -(evt.clientY - previousPosition.y);
  77917. }
  77918. };
  77919. }
  77920. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  77921. if (this._onLostFocus) {
  77922. element.addEventListener("blur", this._onLostFocus);
  77923. }
  77924. };
  77925. /**
  77926. * Detach the current controls from the specified dom element.
  77927. * @param element Defines the element to stop listening the inputs from
  77928. */
  77929. FreeCameraTouchInput.prototype.detachControl = function (element) {
  77930. if (this._pointerInput && element) {
  77931. if (this._observer) {
  77932. this.camera.getScene().onPointerObservable.remove(this._observer);
  77933. this._observer = null;
  77934. }
  77935. if (this._onLostFocus) {
  77936. element.removeEventListener("blur", this._onLostFocus);
  77937. this._onLostFocus = null;
  77938. }
  77939. this._pointerPressed = [];
  77940. this._offsetX = null;
  77941. this._offsetY = null;
  77942. }
  77943. };
  77944. /**
  77945. * Update the current camera state depending on the inputs that have been used this frame.
  77946. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  77947. */
  77948. FreeCameraTouchInput.prototype.checkInputs = function () {
  77949. if (this._offsetX && this._offsetY) {
  77950. var camera = this.camera;
  77951. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  77952. if (this._pointerPressed.length > 1) {
  77953. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  77954. }
  77955. else {
  77956. var speed = camera._computeLocalCameraSpeed();
  77957. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  77958. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  77959. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  77960. }
  77961. }
  77962. };
  77963. /**
  77964. * Gets the class name of the current intput.
  77965. * @returns the class name
  77966. */
  77967. FreeCameraTouchInput.prototype.getClassName = function () {
  77968. return "FreeCameraTouchInput";
  77969. };
  77970. /**
  77971. * Get the friendly name associated with the input class.
  77972. * @returns the input friendly name
  77973. */
  77974. FreeCameraTouchInput.prototype.getSimpleName = function () {
  77975. return "touch";
  77976. };
  77977. __decorate([
  77978. BABYLON.serialize()
  77979. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  77980. __decorate([
  77981. BABYLON.serialize()
  77982. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  77983. return FreeCameraTouchInput;
  77984. }());
  77985. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  77986. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  77987. })(BABYLON || (BABYLON = {}));
  77988. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  77989. var BABYLON;
  77990. (function (BABYLON) {
  77991. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  77992. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  77993. });
  77994. /**
  77995. * This represents a FPS type of camera controlled by touch.
  77996. * This is like a universal camera minus the Gamepad controls.
  77997. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  77998. */
  77999. var TouchCamera = /** @class */ (function (_super) {
  78000. __extends(TouchCamera, _super);
  78001. /**
  78002. * Instantiates a new touch camera.
  78003. * This represents a FPS type of camera controlled by touch.
  78004. * This is like a universal camera minus the Gamepad controls.
  78005. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  78006. * @param name Define the name of the camera in the scene
  78007. * @param position Define the start position of the camera in the scene
  78008. * @param scene Define the scene the camera belongs to
  78009. */
  78010. function TouchCamera(name, position, scene) {
  78011. var _this = _super.call(this, name, position, scene) || this;
  78012. _this.inputs.addTouch();
  78013. _this._setupInputs();
  78014. return _this;
  78015. }
  78016. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  78017. /**
  78018. * Defines the touch sensibility for rotation.
  78019. * The higher the faster.
  78020. */
  78021. get: function () {
  78022. var touch = this.inputs.attached["touch"];
  78023. if (touch)
  78024. return touch.touchAngularSensibility;
  78025. return 0;
  78026. },
  78027. set: function (value) {
  78028. var touch = this.inputs.attached["touch"];
  78029. if (touch)
  78030. touch.touchAngularSensibility = value;
  78031. },
  78032. enumerable: true,
  78033. configurable: true
  78034. });
  78035. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  78036. /**
  78037. * Defines the touch sensibility for move.
  78038. * The higher the faster.
  78039. */
  78040. get: function () {
  78041. var touch = this.inputs.attached["touch"];
  78042. if (touch)
  78043. return touch.touchMoveSensibility;
  78044. return 0;
  78045. },
  78046. set: function (value) {
  78047. var touch = this.inputs.attached["touch"];
  78048. if (touch)
  78049. touch.touchMoveSensibility = value;
  78050. },
  78051. enumerable: true,
  78052. configurable: true
  78053. });
  78054. /**
  78055. * Gets the current object class name.
  78056. * @return the class name
  78057. */
  78058. TouchCamera.prototype.getClassName = function () {
  78059. return "TouchCamera";
  78060. };
  78061. /** @hidden */
  78062. TouchCamera.prototype._setupInputs = function () {
  78063. var mouse = this.inputs.attached["mouse"];
  78064. if (mouse) {
  78065. mouse.touchEnabled = false;
  78066. }
  78067. };
  78068. return TouchCamera;
  78069. }(BABYLON.FreeCamera));
  78070. BABYLON.TouchCamera = TouchCamera;
  78071. })(BABYLON || (BABYLON = {}));
  78072. //# sourceMappingURL=babylon.touchCamera.js.map
  78073. var BABYLON;
  78074. (function (BABYLON) {
  78075. /**
  78076. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  78077. * This is the base class of any Procedural texture and contains most of the shareable code.
  78078. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  78079. */
  78080. var ProceduralTexture = /** @class */ (function (_super) {
  78081. __extends(ProceduralTexture, _super);
  78082. /**
  78083. * Instantiates a new procedural texture.
  78084. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  78085. * This is the base class of any Procedural texture and contains most of the shareable code.
  78086. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  78087. * @param name Define the name of the texture
  78088. * @param size Define the size of the texture to create
  78089. * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later
  78090. * @param scene Define the scene the texture belongs to
  78091. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  78092. * @param generateMipMaps Define if the texture should creates mip maps or not
  78093. * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube)
  78094. */
  78095. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  78096. if (fallbackTexture === void 0) { fallbackTexture = null; }
  78097. if (generateMipMaps === void 0) { generateMipMaps = true; }
  78098. if (isCube === void 0) { isCube = false; }
  78099. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  78100. _this.isCube = isCube;
  78101. /**
  78102. * Define if the texture is enabled or not (disabled texture will not render)
  78103. */
  78104. _this.isEnabled = true;
  78105. /**
  78106. * Event raised when the texture is generated
  78107. */
  78108. _this.onGeneratedObservable = new BABYLON.Observable();
  78109. /** @hidden */
  78110. _this._textures = {};
  78111. _this._currentRefreshId = -1;
  78112. _this._refreshRate = 1;
  78113. _this._vertexBuffers = {};
  78114. _this._uniforms = new Array();
  78115. _this._samplers = new Array();
  78116. _this._floats = {};
  78117. _this._ints = {};
  78118. _this._floatsArrays = {};
  78119. _this._colors3 = {};
  78120. _this._colors4 = {};
  78121. _this._vectors2 = {};
  78122. _this._vectors3 = {};
  78123. _this._matrices = {};
  78124. _this._fallbackTextureUsed = false;
  78125. _this._cachedDefines = "";
  78126. _this._contentUpdateId = -1;
  78127. scene = _this.getScene();
  78128. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  78129. if (!component) {
  78130. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  78131. scene._addComponent(component);
  78132. }
  78133. scene.proceduralTextures.push(_this);
  78134. _this._engine = scene.getEngine();
  78135. _this.name = name;
  78136. _this.isRenderTarget = true;
  78137. _this._size = size;
  78138. _this._generateMipMaps = generateMipMaps;
  78139. _this.setFragment(fragment);
  78140. _this._fallbackTexture = fallbackTexture;
  78141. if (isCube) {
  78142. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  78143. _this.setFloat("face", 0);
  78144. }
  78145. else {
  78146. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  78147. }
  78148. // VBO
  78149. var vertices = [];
  78150. vertices.push(1, 1);
  78151. vertices.push(-1, 1);
  78152. vertices.push(-1, -1);
  78153. vertices.push(1, -1);
  78154. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  78155. _this._createIndexBuffer();
  78156. return _this;
  78157. }
  78158. /**
  78159. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  78160. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  78161. */
  78162. ProceduralTexture.prototype.getContent = function () {
  78163. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  78164. return this._contentData;
  78165. }
  78166. this._contentData = this.readPixels(0, 0, this._contentData);
  78167. this._contentUpdateId = this._currentRefreshId;
  78168. return this._contentData;
  78169. };
  78170. ProceduralTexture.prototype._createIndexBuffer = function () {
  78171. var engine = this._engine;
  78172. // Indices
  78173. var indices = [];
  78174. indices.push(0);
  78175. indices.push(1);
  78176. indices.push(2);
  78177. indices.push(0);
  78178. indices.push(2);
  78179. indices.push(3);
  78180. this._indexBuffer = engine.createIndexBuffer(indices);
  78181. };
  78182. /** @hidden */
  78183. ProceduralTexture.prototype._rebuild = function () {
  78184. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78185. if (vb) {
  78186. vb._rebuild();
  78187. }
  78188. this._createIndexBuffer();
  78189. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  78190. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  78191. }
  78192. };
  78193. /**
  78194. * Resets the texture in order to recreate its associated resources.
  78195. * This can be called in case of context loss
  78196. */
  78197. ProceduralTexture.prototype.reset = function () {
  78198. if (this._effect === undefined) {
  78199. return;
  78200. }
  78201. var engine = this._engine;
  78202. engine._releaseEffect(this._effect);
  78203. };
  78204. ProceduralTexture.prototype._getDefines = function () {
  78205. return "";
  78206. };
  78207. /**
  78208. * Is the texture ready to be used ? (rendered at least once)
  78209. * @returns true if ready, otherwise, false.
  78210. */
  78211. ProceduralTexture.prototype.isReady = function () {
  78212. var _this = this;
  78213. var engine = this._engine;
  78214. var shaders;
  78215. if (!this._fragment) {
  78216. return false;
  78217. }
  78218. if (this._fallbackTextureUsed) {
  78219. return true;
  78220. }
  78221. var defines = this._getDefines();
  78222. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  78223. return true;
  78224. }
  78225. if (this._fragment.fragmentElement !== undefined) {
  78226. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  78227. }
  78228. else {
  78229. shaders = { vertex: "procedural", fragment: this._fragment };
  78230. }
  78231. this._cachedDefines = defines;
  78232. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  78233. _this.releaseInternalTexture();
  78234. if (_this._fallbackTexture) {
  78235. _this._texture = _this._fallbackTexture._texture;
  78236. if (_this._texture) {
  78237. _this._texture.incrementReferences();
  78238. }
  78239. }
  78240. _this._fallbackTextureUsed = true;
  78241. });
  78242. return this._effect.isReady();
  78243. };
  78244. /**
  78245. * Resets the refresh counter of the texture and start bak from scratch.
  78246. * Could be usefull to regenerate the texture if it is setup to render only once.
  78247. */
  78248. ProceduralTexture.prototype.resetRefreshCounter = function () {
  78249. this._currentRefreshId = -1;
  78250. };
  78251. /**
  78252. * Set the fragment shader to use in order to render the texture.
  78253. * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property.
  78254. */
  78255. ProceduralTexture.prototype.setFragment = function (fragment) {
  78256. this._fragment = fragment;
  78257. };
  78258. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  78259. /**
  78260. * Define the refresh rate of the texture or the rendering frequency.
  78261. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  78262. */
  78263. get: function () {
  78264. return this._refreshRate;
  78265. },
  78266. set: function (value) {
  78267. this._refreshRate = value;
  78268. this.resetRefreshCounter();
  78269. },
  78270. enumerable: true,
  78271. configurable: true
  78272. });
  78273. /** @hidden */
  78274. ProceduralTexture.prototype._shouldRender = function () {
  78275. if (!this.isEnabled || !this.isReady() || !this._texture) {
  78276. if (this._texture) {
  78277. this._texture.isReady = false;
  78278. }
  78279. return false;
  78280. }
  78281. if (this._fallbackTextureUsed) {
  78282. return false;
  78283. }
  78284. if (this._currentRefreshId === -1) { // At least render once
  78285. this._currentRefreshId = 1;
  78286. return true;
  78287. }
  78288. if (this.refreshRate === this._currentRefreshId) {
  78289. this._currentRefreshId = 1;
  78290. return true;
  78291. }
  78292. this._currentRefreshId++;
  78293. return false;
  78294. };
  78295. /**
  78296. * Get the size the texture is rendering at.
  78297. * @returns the size (texture is always squared)
  78298. */
  78299. ProceduralTexture.prototype.getRenderSize = function () {
  78300. return this._size;
  78301. };
  78302. /**
  78303. * Resize the texture to new value.
  78304. * @param size Define the new size the texture should have
  78305. * @param generateMipMaps Define whether the new texture should create mip maps
  78306. */
  78307. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  78308. if (this._fallbackTextureUsed) {
  78309. return;
  78310. }
  78311. this.releaseInternalTexture();
  78312. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  78313. // Update properties
  78314. this._size = size;
  78315. this._generateMipMaps = generateMipMaps;
  78316. };
  78317. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  78318. if (this._uniforms.indexOf(uniformName) === -1) {
  78319. this._uniforms.push(uniformName);
  78320. }
  78321. };
  78322. /**
  78323. * Set a texture in the shader program used to render.
  78324. * @param name Define the name of the uniform samplers as defined in the shader
  78325. * @param texture Define the texture to bind to this sampler
  78326. * @return the texture itself allowing "fluent" like uniform updates
  78327. */
  78328. ProceduralTexture.prototype.setTexture = function (name, texture) {
  78329. if (this._samplers.indexOf(name) === -1) {
  78330. this._samplers.push(name);
  78331. }
  78332. this._textures[name] = texture;
  78333. return this;
  78334. };
  78335. /**
  78336. * Set a float in the shader.
  78337. * @param name Define the name of the uniform as defined in the shader
  78338. * @param value Define the value to give to the uniform
  78339. * @return the texture itself allowing "fluent" like uniform updates
  78340. */
  78341. ProceduralTexture.prototype.setFloat = function (name, value) {
  78342. this._checkUniform(name);
  78343. this._floats[name] = value;
  78344. return this;
  78345. };
  78346. /**
  78347. * Set a int in the shader.
  78348. * @param name Define the name of the uniform as defined in the shader
  78349. * @param value Define the value to give to the uniform
  78350. * @return the texture itself allowing "fluent" like uniform updates
  78351. */
  78352. ProceduralTexture.prototype.setInt = function (name, value) {
  78353. this._checkUniform(name);
  78354. this._ints[name] = value;
  78355. return this;
  78356. };
  78357. /**
  78358. * Set an array of floats in the shader.
  78359. * @param name Define the name of the uniform as defined in the shader
  78360. * @param value Define the value to give to the uniform
  78361. * @return the texture itself allowing "fluent" like uniform updates
  78362. */
  78363. ProceduralTexture.prototype.setFloats = function (name, value) {
  78364. this._checkUniform(name);
  78365. this._floatsArrays[name] = value;
  78366. return this;
  78367. };
  78368. /**
  78369. * Set a vec3 in the shader from a Color3.
  78370. * @param name Define the name of the uniform as defined in the shader
  78371. * @param value Define the value to give to the uniform
  78372. * @return the texture itself allowing "fluent" like uniform updates
  78373. */
  78374. ProceduralTexture.prototype.setColor3 = function (name, value) {
  78375. this._checkUniform(name);
  78376. this._colors3[name] = value;
  78377. return this;
  78378. };
  78379. /**
  78380. * Set a vec4 in the shader from a Color4.
  78381. * @param name Define the name of the uniform as defined in the shader
  78382. * @param value Define the value to give to the uniform
  78383. * @return the texture itself allowing "fluent" like uniform updates
  78384. */
  78385. ProceduralTexture.prototype.setColor4 = function (name, value) {
  78386. this._checkUniform(name);
  78387. this._colors4[name] = value;
  78388. return this;
  78389. };
  78390. /**
  78391. * Set a vec2 in the shader from a Vector2.
  78392. * @param name Define the name of the uniform as defined in the shader
  78393. * @param value Define the value to give to the uniform
  78394. * @return the texture itself allowing "fluent" like uniform updates
  78395. */
  78396. ProceduralTexture.prototype.setVector2 = function (name, value) {
  78397. this._checkUniform(name);
  78398. this._vectors2[name] = value;
  78399. return this;
  78400. };
  78401. /**
  78402. * Set a vec3 in the shader from a Vector3.
  78403. * @param name Define the name of the uniform as defined in the shader
  78404. * @param value Define the value to give to the uniform
  78405. * @return the texture itself allowing "fluent" like uniform updates
  78406. */
  78407. ProceduralTexture.prototype.setVector3 = function (name, value) {
  78408. this._checkUniform(name);
  78409. this._vectors3[name] = value;
  78410. return this;
  78411. };
  78412. /**
  78413. * Set a mat4 in the shader from a MAtrix.
  78414. * @param name Define the name of the uniform as defined in the shader
  78415. * @param value Define the value to give to the uniform
  78416. * @return the texture itself allowing "fluent" like uniform updates
  78417. */
  78418. ProceduralTexture.prototype.setMatrix = function (name, value) {
  78419. this._checkUniform(name);
  78420. this._matrices[name] = value;
  78421. return this;
  78422. };
  78423. /**
  78424. * Render the texture to its associated render target.
  78425. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  78426. */
  78427. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  78428. var scene = this.getScene();
  78429. if (!scene) {
  78430. return;
  78431. }
  78432. var engine = this._engine;
  78433. // Render
  78434. engine.enableEffect(this._effect);
  78435. engine.setState(false);
  78436. // Texture
  78437. for (var name in this._textures) {
  78438. this._effect.setTexture(name, this._textures[name]);
  78439. }
  78440. // Float
  78441. for (name in this._ints) {
  78442. this._effect.setInt(name, this._ints[name]);
  78443. }
  78444. // Float
  78445. for (name in this._floats) {
  78446. this._effect.setFloat(name, this._floats[name]);
  78447. }
  78448. // Floats
  78449. for (name in this._floatsArrays) {
  78450. this._effect.setArray(name, this._floatsArrays[name]);
  78451. }
  78452. // Color3
  78453. for (name in this._colors3) {
  78454. this._effect.setColor3(name, this._colors3[name]);
  78455. }
  78456. // Color4
  78457. for (name in this._colors4) {
  78458. var color = this._colors4[name];
  78459. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  78460. }
  78461. // Vector2
  78462. for (name in this._vectors2) {
  78463. this._effect.setVector2(name, this._vectors2[name]);
  78464. }
  78465. // Vector3
  78466. for (name in this._vectors3) {
  78467. this._effect.setVector3(name, this._vectors3[name]);
  78468. }
  78469. // Matrix
  78470. for (name in this._matrices) {
  78471. this._effect.setMatrix(name, this._matrices[name]);
  78472. }
  78473. if (!this._texture) {
  78474. return;
  78475. }
  78476. if (this.isCube) {
  78477. for (var face = 0; face < 6; face++) {
  78478. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  78479. // VBOs
  78480. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  78481. this._effect.setFloat("face", face);
  78482. // Clear
  78483. engine.clear(scene.clearColor, true, true, true);
  78484. // Draw order
  78485. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78486. // Mipmaps
  78487. if (face === 5) {
  78488. engine.generateMipMapsForCubemap(this._texture);
  78489. }
  78490. }
  78491. }
  78492. else {
  78493. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  78494. // VBOs
  78495. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  78496. // Clear
  78497. engine.clear(scene.clearColor, true, true, true);
  78498. // Draw order
  78499. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78500. }
  78501. // Unbind
  78502. engine.unBindFramebuffer(this._texture, this.isCube);
  78503. if (this.onGenerated) {
  78504. this.onGenerated();
  78505. }
  78506. this.onGeneratedObservable.notifyObservers(this);
  78507. };
  78508. /**
  78509. * Clone the texture.
  78510. * @returns the cloned texture
  78511. */
  78512. ProceduralTexture.prototype.clone = function () {
  78513. var textureSize = this.getSize();
  78514. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  78515. // Base texture
  78516. newTexture.hasAlpha = this.hasAlpha;
  78517. newTexture.level = this.level;
  78518. // RenderTarget Texture
  78519. newTexture.coordinatesMode = this.coordinatesMode;
  78520. return newTexture;
  78521. };
  78522. /**
  78523. * Dispose the texture and release its asoociated resources.
  78524. */
  78525. ProceduralTexture.prototype.dispose = function () {
  78526. var scene = this.getScene();
  78527. if (!scene) {
  78528. return;
  78529. }
  78530. var index = scene.proceduralTextures.indexOf(this);
  78531. if (index >= 0) {
  78532. scene.proceduralTextures.splice(index, 1);
  78533. }
  78534. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78535. if (vertexBuffer) {
  78536. vertexBuffer.dispose();
  78537. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78538. }
  78539. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  78540. this._indexBuffer = null;
  78541. }
  78542. _super.prototype.dispose.call(this);
  78543. };
  78544. __decorate([
  78545. BABYLON.serialize()
  78546. ], ProceduralTexture.prototype, "isEnabled", void 0);
  78547. __decorate([
  78548. BABYLON.serialize()
  78549. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  78550. __decorate([
  78551. BABYLON.serialize()
  78552. ], ProceduralTexture.prototype, "_size", void 0);
  78553. __decorate([
  78554. BABYLON.serialize()
  78555. ], ProceduralTexture.prototype, "refreshRate", null);
  78556. return ProceduralTexture;
  78557. }(BABYLON.Texture));
  78558. BABYLON.ProceduralTexture = ProceduralTexture;
  78559. })(BABYLON || (BABYLON = {}));
  78560. //# sourceMappingURL=babylon.proceduralTexture.js.map
  78561. var BABYLON;
  78562. (function (BABYLON) {
  78563. /**
  78564. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  78565. * in a given scene.
  78566. */
  78567. var ProceduralTextureSceneComponent = /** @class */ (function () {
  78568. /**
  78569. * Creates a new instance of the component for the given scene
  78570. * @param scene Defines the scene to register the component in
  78571. */
  78572. function ProceduralTextureSceneComponent(scene) {
  78573. /**
  78574. * The component name helpfull to identify the component in the list of scene components.
  78575. */
  78576. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  78577. this.scene = scene;
  78578. this.scene.proceduralTextures = new Array();
  78579. scene.layers = new Array();
  78580. }
  78581. /**
  78582. * Registers the component in a given scene
  78583. */
  78584. ProceduralTextureSceneComponent.prototype.register = function () {
  78585. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  78586. };
  78587. /**
  78588. * Rebuilds the elements related to this component in case of
  78589. * context lost for instance.
  78590. */
  78591. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  78592. // Nothing to do here.
  78593. };
  78594. /**
  78595. * Disposes the component and the associated ressources.
  78596. */
  78597. ProceduralTextureSceneComponent.prototype.dispose = function () {
  78598. // Nothing to do here.
  78599. };
  78600. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  78601. if (this.scene.proceduralTexturesEnabled) {
  78602. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  78603. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  78604. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  78605. if (proceduralTexture._shouldRender()) {
  78606. proceduralTexture.render();
  78607. }
  78608. }
  78609. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  78610. }
  78611. };
  78612. return ProceduralTextureSceneComponent;
  78613. }());
  78614. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  78615. })(BABYLON || (BABYLON = {}));
  78616. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  78617. var BABYLON;
  78618. (function (BABYLON) {
  78619. /**
  78620. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  78621. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  78622. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  78623. */
  78624. var CustomProceduralTexture = /** @class */ (function (_super) {
  78625. __extends(CustomProceduralTexture, _super);
  78626. /**
  78627. * Instantiates a new Custom Procedural Texture.
  78628. * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
  78629. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  78630. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  78631. * @param name Define the name of the texture
  78632. * @param texturePath Define the folder path containing all the cutom texture related files (config, shaders...)
  78633. * @param size Define the size of the texture to create
  78634. * @param scene Define the scene the texture belongs to
  78635. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  78636. * @param generateMipMaps Define if the texture should creates mip maps or not
  78637. */
  78638. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  78639. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  78640. _this._animate = true;
  78641. _this._time = 0;
  78642. _this._texturePath = texturePath;
  78643. //Try to load json
  78644. _this._loadJson(texturePath);
  78645. _this.refreshRate = 1;
  78646. return _this;
  78647. }
  78648. CustomProceduralTexture.prototype._loadJson = function (jsonUrl) {
  78649. var _this = this;
  78650. var noConfigFile = function () {
  78651. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  78652. try {
  78653. _this.setFragment(_this._texturePath);
  78654. }
  78655. catch (ex) {
  78656. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  78657. }
  78658. };
  78659. var configFileUrl = jsonUrl + "/config.json";
  78660. var xhr = new XMLHttpRequest();
  78661. xhr.open("GET", configFileUrl, true);
  78662. xhr.addEventListener("load", function () {
  78663. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  78664. try {
  78665. _this._config = JSON.parse(xhr.response);
  78666. _this.updateShaderUniforms();
  78667. _this.updateTextures();
  78668. _this.setFragment(_this._texturePath + "/custom");
  78669. _this._animate = _this._config.animate;
  78670. _this.refreshRate = _this._config.refreshrate;
  78671. }
  78672. catch (ex) {
  78673. noConfigFile();
  78674. }
  78675. }
  78676. else {
  78677. noConfigFile();
  78678. }
  78679. }, false);
  78680. xhr.addEventListener("error", function () {
  78681. noConfigFile();
  78682. }, false);
  78683. try {
  78684. xhr.send();
  78685. }
  78686. catch (ex) {
  78687. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  78688. }
  78689. };
  78690. /**
  78691. * Is the texture ready to be used ? (rendered at least once)
  78692. * @returns true if ready, otherwise, false.
  78693. */
  78694. CustomProceduralTexture.prototype.isReady = function () {
  78695. if (!_super.prototype.isReady.call(this)) {
  78696. return false;
  78697. }
  78698. for (var name in this._textures) {
  78699. var texture = this._textures[name];
  78700. if (!texture.isReady()) {
  78701. return false;
  78702. }
  78703. }
  78704. return true;
  78705. };
  78706. /**
  78707. * Render the texture to its associated render target.
  78708. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  78709. */
  78710. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  78711. var scene = this.getScene();
  78712. if (this._animate && scene) {
  78713. this._time += scene.getAnimationRatio() * 0.03;
  78714. this.updateShaderUniforms();
  78715. }
  78716. _super.prototype.render.call(this, useCameraPostProcess);
  78717. };
  78718. /**
  78719. * Update the list of dependant textures samplers in the shader.
  78720. */
  78721. CustomProceduralTexture.prototype.updateTextures = function () {
  78722. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  78723. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  78724. }
  78725. };
  78726. /**
  78727. * Update the uniform values of the procedural texture in the shader.
  78728. */
  78729. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  78730. if (this._config) {
  78731. for (var j = 0; j < this._config.uniforms.length; j++) {
  78732. var uniform = this._config.uniforms[j];
  78733. switch (uniform.type) {
  78734. case "float":
  78735. this.setFloat(uniform.name, uniform.value);
  78736. break;
  78737. case "color3":
  78738. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  78739. break;
  78740. case "color4":
  78741. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  78742. break;
  78743. case "vector2":
  78744. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  78745. break;
  78746. case "vector3":
  78747. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  78748. break;
  78749. }
  78750. }
  78751. }
  78752. this.setFloat("time", this._time);
  78753. };
  78754. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  78755. /**
  78756. * Define if the texture animates or not.
  78757. */
  78758. get: function () {
  78759. return this._animate;
  78760. },
  78761. set: function (value) {
  78762. this._animate = value;
  78763. },
  78764. enumerable: true,
  78765. configurable: true
  78766. });
  78767. return CustomProceduralTexture;
  78768. }(BABYLON.ProceduralTexture));
  78769. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  78770. })(BABYLON || (BABYLON = {}));
  78771. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  78772. var BABYLON;
  78773. (function (BABYLON) {
  78774. /**
  78775. * Manage the gamepad inputs to control a free camera.
  78776. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  78777. */
  78778. var FreeCameraGamepadInput = /** @class */ (function () {
  78779. function FreeCameraGamepadInput() {
  78780. /**
  78781. * Defines the gamepad rotation sensiblity.
  78782. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  78783. */
  78784. this.gamepadAngularSensibility = 200;
  78785. /**
  78786. * Defines the gamepad move sensiblity.
  78787. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  78788. */
  78789. this.gamepadMoveSensibility = 40;
  78790. this._cameraTransform = BABYLON.Matrix.Identity();
  78791. this._deltaTransform = BABYLON.Vector3.Zero();
  78792. this._vector3 = BABYLON.Vector3.Zero();
  78793. this._vector2 = BABYLON.Vector2.Zero();
  78794. }
  78795. /**
  78796. * Attach the input controls to a specific dom element to get the input from.
  78797. * @param element Defines the element the controls should be listened from
  78798. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  78799. */
  78800. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  78801. var _this = this;
  78802. var manager = this.camera.getScene().gamepadManager;
  78803. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78804. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78805. // prioritize XBOX gamepads.
  78806. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  78807. _this.gamepad = gamepad;
  78808. }
  78809. }
  78810. });
  78811. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78812. if (_this.gamepad === gamepad) {
  78813. _this.gamepad = null;
  78814. }
  78815. });
  78816. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  78817. };
  78818. /**
  78819. * Detach the current controls from the specified dom element.
  78820. * @param element Defines the element to stop listening the inputs from
  78821. */
  78822. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  78823. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  78824. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  78825. this.gamepad = null;
  78826. };
  78827. /**
  78828. * Update the current camera state depending on the inputs that have been used this frame.
  78829. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  78830. */
  78831. FreeCameraGamepadInput.prototype.checkInputs = function () {
  78832. if (this.gamepad && this.gamepad.leftStick) {
  78833. var camera = this.camera;
  78834. var LSValues = this.gamepad.leftStick;
  78835. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  78836. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  78837. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  78838. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  78839. var RSValues = this.gamepad.rightStick;
  78840. if (RSValues) {
  78841. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  78842. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  78843. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  78844. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  78845. }
  78846. else {
  78847. RSValues = { x: 0, y: 0 };
  78848. }
  78849. if (!camera.rotationQuaternion) {
  78850. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  78851. }
  78852. else {
  78853. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  78854. }
  78855. var speed = camera._computeLocalCameraSpeed() * 50.0;
  78856. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  78857. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  78858. camera.cameraDirection.addInPlace(this._deltaTransform);
  78859. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  78860. camera.cameraRotation.addInPlace(this._vector2);
  78861. }
  78862. };
  78863. /**
  78864. * Gets the class name of the current intput.
  78865. * @returns the class name
  78866. */
  78867. FreeCameraGamepadInput.prototype.getClassName = function () {
  78868. return "FreeCameraGamepadInput";
  78869. };
  78870. /**
  78871. * Get the friendly name associated with the input class.
  78872. * @returns the input friendly name
  78873. */
  78874. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  78875. return "gamepad";
  78876. };
  78877. __decorate([
  78878. BABYLON.serialize()
  78879. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  78880. __decorate([
  78881. BABYLON.serialize()
  78882. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  78883. return FreeCameraGamepadInput;
  78884. }());
  78885. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  78886. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  78887. })(BABYLON || (BABYLON = {}));
  78888. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  78889. var BABYLON;
  78890. (function (BABYLON) {
  78891. /**
  78892. * Manage the gamepad inputs to control an arc rotate camera.
  78893. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  78894. */
  78895. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  78896. function ArcRotateCameraGamepadInput() {
  78897. /**
  78898. * Defines the gamepad rotation sensiblity.
  78899. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  78900. */
  78901. this.gamepadRotationSensibility = 80;
  78902. /**
  78903. * Defines the gamepad move sensiblity.
  78904. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  78905. */
  78906. this.gamepadMoveSensibility = 40;
  78907. }
  78908. /**
  78909. * Attach the input controls to a specific dom element to get the input from.
  78910. * @param element Defines the element the controls should be listened from
  78911. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  78912. */
  78913. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  78914. var _this = this;
  78915. var manager = this.camera.getScene().gamepadManager;
  78916. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78917. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78918. // prioritize XBOX gamepads.
  78919. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  78920. _this.gamepad = gamepad;
  78921. }
  78922. }
  78923. });
  78924. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78925. if (_this.gamepad === gamepad) {
  78926. _this.gamepad = null;
  78927. }
  78928. });
  78929. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  78930. };
  78931. /**
  78932. * Detach the current controls from the specified dom element.
  78933. * @param element Defines the element to stop listening the inputs from
  78934. */
  78935. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  78936. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  78937. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  78938. this.gamepad = null;
  78939. };
  78940. /**
  78941. * Update the current camera state depending on the inputs that have been used this frame.
  78942. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  78943. */
  78944. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  78945. if (this.gamepad) {
  78946. var camera = this.camera;
  78947. var RSValues = this.gamepad.rightStick;
  78948. if (RSValues) {
  78949. if (RSValues.x != 0) {
  78950. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  78951. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  78952. camera.inertialAlphaOffset += normalizedRX;
  78953. }
  78954. }
  78955. if (RSValues.y != 0) {
  78956. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  78957. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  78958. camera.inertialBetaOffset += normalizedRY;
  78959. }
  78960. }
  78961. }
  78962. var LSValues = this.gamepad.leftStick;
  78963. if (LSValues && LSValues.y != 0) {
  78964. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  78965. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  78966. this.camera.inertialRadiusOffset -= normalizedLY;
  78967. }
  78968. }
  78969. }
  78970. };
  78971. /**
  78972. * Gets the class name of the current intput.
  78973. * @returns the class name
  78974. */
  78975. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  78976. return "ArcRotateCameraGamepadInput";
  78977. };
  78978. /**
  78979. * Get the friendly name associated with the input class.
  78980. * @returns the input friendly name
  78981. */
  78982. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  78983. return "gamepad";
  78984. };
  78985. __decorate([
  78986. BABYLON.serialize()
  78987. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  78988. __decorate([
  78989. BABYLON.serialize()
  78990. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  78991. return ArcRotateCameraGamepadInput;
  78992. }());
  78993. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  78994. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  78995. })(BABYLON || (BABYLON = {}));
  78996. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  78997. var BABYLON;
  78998. (function (BABYLON) {
  78999. /**
  79000. * Manager for handling gamepads
  79001. */
  79002. var GamepadManager = /** @class */ (function () {
  79003. /**
  79004. * Initializes the gamepad manager
  79005. * @param _scene BabylonJS scene
  79006. */
  79007. function GamepadManager(_scene) {
  79008. var _this = this;
  79009. this._scene = _scene;
  79010. this._babylonGamepads = [];
  79011. this._oneGamepadConnected = false;
  79012. /** @hidden */
  79013. this._isMonitoring = false;
  79014. /**
  79015. * observable to be triggered when the gamepad controller has been disconnected
  79016. */
  79017. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  79018. if (!BABYLON.Tools.IsWindowObjectExist()) {
  79019. this._gamepadEventSupported = false;
  79020. }
  79021. else {
  79022. this._gamepadEventSupported = 'GamepadEvent' in window;
  79023. this._gamepadSupport = (navigator.getGamepads ||
  79024. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  79025. }
  79026. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  79027. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  79028. for (var i in _this._babylonGamepads) {
  79029. var gamepad = _this._babylonGamepads[i];
  79030. if (gamepad && gamepad._isConnected) {
  79031. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  79032. }
  79033. }
  79034. });
  79035. this._onGamepadConnectedEvent = function (evt) {
  79036. var gamepad = evt.gamepad;
  79037. if (gamepad.index in _this._babylonGamepads) {
  79038. if (_this._babylonGamepads[gamepad.index].isConnected) {
  79039. return;
  79040. }
  79041. }
  79042. var newGamepad;
  79043. if (_this._babylonGamepads[gamepad.index]) {
  79044. newGamepad = _this._babylonGamepads[gamepad.index];
  79045. newGamepad.browserGamepad = gamepad;
  79046. newGamepad._isConnected = true;
  79047. }
  79048. else {
  79049. newGamepad = _this._addNewGamepad(gamepad);
  79050. }
  79051. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  79052. _this._startMonitoringGamepads();
  79053. };
  79054. this._onGamepadDisconnectedEvent = function (evt) {
  79055. var gamepad = evt.gamepad;
  79056. // Remove the gamepad from the list of gamepads to monitor.
  79057. for (var i in _this._babylonGamepads) {
  79058. if (_this._babylonGamepads[i].index === gamepad.index) {
  79059. var disconnectedGamepad = _this._babylonGamepads[i];
  79060. disconnectedGamepad._isConnected = false;
  79061. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  79062. break;
  79063. }
  79064. }
  79065. };
  79066. if (this._gamepadSupport) {
  79067. //first add already-connected gamepads
  79068. this._updateGamepadObjects();
  79069. if (this._babylonGamepads.length) {
  79070. this._startMonitoringGamepads();
  79071. }
  79072. // Checking if the gamepad connected event is supported (like in Firefox)
  79073. if (this._gamepadEventSupported) {
  79074. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  79075. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  79076. }
  79077. else {
  79078. this._startMonitoringGamepads();
  79079. }
  79080. }
  79081. }
  79082. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  79083. /**
  79084. * The gamepads in the game pad manager
  79085. */
  79086. get: function () {
  79087. return this._babylonGamepads;
  79088. },
  79089. enumerable: true,
  79090. configurable: true
  79091. });
  79092. /**
  79093. * Get the gamepad controllers based on type
  79094. * @param type The type of gamepad controller
  79095. * @returns Nullable gamepad
  79096. */
  79097. GamepadManager.prototype.getGamepadByType = function (type) {
  79098. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  79099. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  79100. var gamepad = _a[_i];
  79101. if (gamepad && gamepad.type === type) {
  79102. return gamepad;
  79103. }
  79104. }
  79105. return null;
  79106. };
  79107. /**
  79108. * Disposes the gamepad manager
  79109. */
  79110. GamepadManager.prototype.dispose = function () {
  79111. if (this._gamepadEventSupported) {
  79112. if (this._onGamepadConnectedEvent) {
  79113. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  79114. }
  79115. if (this._onGamepadDisconnectedEvent) {
  79116. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  79117. }
  79118. this._onGamepadConnectedEvent = null;
  79119. this._onGamepadDisconnectedEvent = null;
  79120. }
  79121. this._babylonGamepads.forEach(function (gamepad) {
  79122. gamepad.dispose();
  79123. });
  79124. this.onGamepadConnectedObservable.clear();
  79125. this.onGamepadDisconnectedObservable.clear();
  79126. this._oneGamepadConnected = false;
  79127. this._stopMonitoringGamepads();
  79128. this._babylonGamepads = [];
  79129. };
  79130. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  79131. if (!this._oneGamepadConnected) {
  79132. this._oneGamepadConnected = true;
  79133. }
  79134. var newGamepad;
  79135. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  79136. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  79137. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  79138. }
  79139. // if pose is supported, use the (WebVR) pose enabled controller
  79140. else if (gamepad.pose) {
  79141. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  79142. }
  79143. else {
  79144. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  79145. }
  79146. this._babylonGamepads[newGamepad.index] = newGamepad;
  79147. return newGamepad;
  79148. };
  79149. GamepadManager.prototype._startMonitoringGamepads = function () {
  79150. if (!this._isMonitoring) {
  79151. this._isMonitoring = true;
  79152. //back-comp
  79153. if (!this._scene) {
  79154. this._checkGamepadsStatus();
  79155. }
  79156. }
  79157. };
  79158. GamepadManager.prototype._stopMonitoringGamepads = function () {
  79159. this._isMonitoring = false;
  79160. };
  79161. /** @hidden */
  79162. GamepadManager.prototype._checkGamepadsStatus = function () {
  79163. var _this = this;
  79164. // Hack to be compatible Chrome
  79165. this._updateGamepadObjects();
  79166. for (var i in this._babylonGamepads) {
  79167. var gamepad = this._babylonGamepads[i];
  79168. if (!gamepad || !gamepad.isConnected) {
  79169. continue;
  79170. }
  79171. gamepad.update();
  79172. }
  79173. if (this._isMonitoring && !this._scene) {
  79174. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  79175. }
  79176. };
  79177. // This function is called only on Chrome, which does not properly support
  79178. // connection/disconnection events and forces you to recopy again the gamepad object
  79179. GamepadManager.prototype._updateGamepadObjects = function () {
  79180. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  79181. for (var i = 0; i < gamepads.length; i++) {
  79182. var gamepad = gamepads[i];
  79183. if (gamepad) {
  79184. if (!this._babylonGamepads[gamepad.index]) {
  79185. var newGamepad = this._addNewGamepad(gamepad);
  79186. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  79187. }
  79188. else {
  79189. // Forced to copy again this object for Chrome for unknown reason
  79190. this._babylonGamepads[i].browserGamepad = gamepad;
  79191. if (!this._babylonGamepads[i].isConnected) {
  79192. this._babylonGamepads[i]._isConnected = true;
  79193. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  79194. }
  79195. }
  79196. }
  79197. }
  79198. };
  79199. return GamepadManager;
  79200. }());
  79201. BABYLON.GamepadManager = GamepadManager;
  79202. })(BABYLON || (BABYLON = {}));
  79203. //# sourceMappingURL=babylon.gamepadManager.js.map
  79204. var BABYLON;
  79205. (function (BABYLON) {
  79206. /**
  79207. * Represents a gamepad control stick position
  79208. */
  79209. var StickValues = /** @class */ (function () {
  79210. /**
  79211. * Initializes the gamepad x and y control stick values
  79212. * @param x The x component of the gamepad control stick value
  79213. * @param y The y component of the gamepad control stick value
  79214. */
  79215. function StickValues(
  79216. /**
  79217. * The x component of the control stick
  79218. */
  79219. x,
  79220. /**
  79221. * The y component of the control stick
  79222. */
  79223. y) {
  79224. this.x = x;
  79225. this.y = y;
  79226. }
  79227. return StickValues;
  79228. }());
  79229. BABYLON.StickValues = StickValues;
  79230. /**
  79231. * Represents a gamepad
  79232. */
  79233. var Gamepad = /** @class */ (function () {
  79234. /**
  79235. * Initializes the gamepad
  79236. * @param id The id of the gamepad
  79237. * @param index The index of the gamepad
  79238. * @param browserGamepad The browser gamepad
  79239. * @param leftStickX The x component of the left joystick
  79240. * @param leftStickY The y component of the left joystick
  79241. * @param rightStickX The x component of the right joystick
  79242. * @param rightStickY The y component of the right joystick
  79243. */
  79244. function Gamepad(
  79245. /**
  79246. * The id of the gamepad
  79247. */
  79248. id,
  79249. /**
  79250. * The index of the gamepad
  79251. */
  79252. index,
  79253. /**
  79254. * The browser gamepad
  79255. */
  79256. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  79257. if (leftStickX === void 0) { leftStickX = 0; }
  79258. if (leftStickY === void 0) { leftStickY = 1; }
  79259. if (rightStickX === void 0) { rightStickX = 2; }
  79260. if (rightStickY === void 0) { rightStickY = 3; }
  79261. this.id = id;
  79262. this.index = index;
  79263. this.browserGamepad = browserGamepad;
  79264. this._leftStick = { x: 0, y: 0 };
  79265. this._rightStick = { x: 0, y: 0 };
  79266. /** @hidden */
  79267. this._isConnected = true;
  79268. /**
  79269. * Specifies whether the left control stick should be Y-inverted
  79270. */
  79271. this._invertLeftStickY = false;
  79272. this.type = Gamepad.GAMEPAD;
  79273. this._leftStickAxisX = leftStickX;
  79274. this._leftStickAxisY = leftStickY;
  79275. this._rightStickAxisX = rightStickX;
  79276. this._rightStickAxisY = rightStickY;
  79277. if (this.browserGamepad.axes.length >= 2) {
  79278. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  79279. }
  79280. if (this.browserGamepad.axes.length >= 4) {
  79281. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  79282. }
  79283. }
  79284. Object.defineProperty(Gamepad.prototype, "isConnected", {
  79285. /**
  79286. * Specifies if the gamepad has been connected
  79287. */
  79288. get: function () {
  79289. return this._isConnected;
  79290. },
  79291. enumerable: true,
  79292. configurable: true
  79293. });
  79294. /**
  79295. * Callback triggered when the left joystick has changed
  79296. * @param callback
  79297. */
  79298. Gamepad.prototype.onleftstickchanged = function (callback) {
  79299. this._onleftstickchanged = callback;
  79300. };
  79301. /**
  79302. * Callback triggered when the right joystick has changed
  79303. * @param callback
  79304. */
  79305. Gamepad.prototype.onrightstickchanged = function (callback) {
  79306. this._onrightstickchanged = callback;
  79307. };
  79308. Object.defineProperty(Gamepad.prototype, "leftStick", {
  79309. /**
  79310. * Gets the left joystick
  79311. */
  79312. get: function () {
  79313. return this._leftStick;
  79314. },
  79315. /**
  79316. * Sets the left joystick values
  79317. */
  79318. set: function (newValues) {
  79319. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  79320. this._onleftstickchanged(newValues);
  79321. }
  79322. this._leftStick = newValues;
  79323. },
  79324. enumerable: true,
  79325. configurable: true
  79326. });
  79327. Object.defineProperty(Gamepad.prototype, "rightStick", {
  79328. /**
  79329. * Gets the right joystick
  79330. */
  79331. get: function () {
  79332. return this._rightStick;
  79333. },
  79334. /**
  79335. * Sets the right joystick value
  79336. */
  79337. set: function (newValues) {
  79338. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  79339. this._onrightstickchanged(newValues);
  79340. }
  79341. this._rightStick = newValues;
  79342. },
  79343. enumerable: true,
  79344. configurable: true
  79345. });
  79346. /**
  79347. * Updates the gamepad joystick positions
  79348. */
  79349. Gamepad.prototype.update = function () {
  79350. if (this._leftStick) {
  79351. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  79352. if (this._invertLeftStickY) {
  79353. this.leftStick.y *= -1;
  79354. }
  79355. }
  79356. if (this._rightStick) {
  79357. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  79358. }
  79359. };
  79360. /**
  79361. * Disposes the gamepad
  79362. */
  79363. Gamepad.prototype.dispose = function () {
  79364. };
  79365. /**
  79366. * Represents a gamepad controller
  79367. */
  79368. Gamepad.GAMEPAD = 0;
  79369. /**
  79370. * Represents a generic controller
  79371. */
  79372. Gamepad.GENERIC = 1;
  79373. /**
  79374. * Represents an XBox controller
  79375. */
  79376. Gamepad.XBOX = 2;
  79377. /**
  79378. * Represents a pose-enabled controller
  79379. */
  79380. Gamepad.POSE_ENABLED = 3;
  79381. return Gamepad;
  79382. }());
  79383. BABYLON.Gamepad = Gamepad;
  79384. /**
  79385. * Represents a generic gamepad
  79386. */
  79387. var GenericPad = /** @class */ (function (_super) {
  79388. __extends(GenericPad, _super);
  79389. /**
  79390. * Initializes the generic gamepad
  79391. * @param id The id of the generic gamepad
  79392. * @param index The index of the generic gamepad
  79393. * @param browserGamepad The browser gamepad
  79394. */
  79395. function GenericPad(id, index, browserGamepad) {
  79396. var _this = _super.call(this, id, index, browserGamepad) || this;
  79397. /**
  79398. * Observable triggered when a button has been pressed
  79399. */
  79400. _this.onButtonDownObservable = new BABYLON.Observable();
  79401. /**
  79402. * Observable triggered when a button has been released
  79403. */
  79404. _this.onButtonUpObservable = new BABYLON.Observable();
  79405. _this.type = Gamepad.GENERIC;
  79406. _this._buttons = new Array(browserGamepad.buttons.length);
  79407. return _this;
  79408. }
  79409. /**
  79410. * Callback triggered when a button has been pressed
  79411. * @param callback Called when a button has been pressed
  79412. */
  79413. GenericPad.prototype.onbuttondown = function (callback) {
  79414. this._onbuttondown = callback;
  79415. };
  79416. /**
  79417. * Callback triggered when a button has been released
  79418. * @param callback Called when a button has been released
  79419. */
  79420. GenericPad.prototype.onbuttonup = function (callback) {
  79421. this._onbuttonup = callback;
  79422. };
  79423. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  79424. if (newValue !== currentValue) {
  79425. if (newValue === 1) {
  79426. if (this._onbuttondown) {
  79427. this._onbuttondown(buttonIndex);
  79428. }
  79429. this.onButtonDownObservable.notifyObservers(buttonIndex);
  79430. }
  79431. if (newValue === 0) {
  79432. if (this._onbuttonup) {
  79433. this._onbuttonup(buttonIndex);
  79434. }
  79435. this.onButtonUpObservable.notifyObservers(buttonIndex);
  79436. }
  79437. }
  79438. return newValue;
  79439. };
  79440. /**
  79441. * Updates the generic gamepad
  79442. */
  79443. GenericPad.prototype.update = function () {
  79444. _super.prototype.update.call(this);
  79445. for (var index = 0; index < this._buttons.length; index++) {
  79446. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  79447. }
  79448. };
  79449. /**
  79450. * Disposes the generic gamepad
  79451. */
  79452. GenericPad.prototype.dispose = function () {
  79453. _super.prototype.dispose.call(this);
  79454. this.onButtonDownObservable.clear();
  79455. this.onButtonUpObservable.clear();
  79456. };
  79457. return GenericPad;
  79458. }(Gamepad));
  79459. BABYLON.GenericPad = GenericPad;
  79460. })(BABYLON || (BABYLON = {}));
  79461. //# sourceMappingURL=babylon.gamepad.js.map
  79462. var BABYLON;
  79463. (function (BABYLON) {
  79464. /**
  79465. * Defines supported buttons for XBox360 compatible gamepads
  79466. */
  79467. var Xbox360Button;
  79468. (function (Xbox360Button) {
  79469. /** A */
  79470. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  79471. /** B */
  79472. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  79473. /** X */
  79474. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  79475. /** Y */
  79476. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  79477. /** Start */
  79478. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  79479. /** Back */
  79480. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  79481. /** Left button */
  79482. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  79483. /** Right button */
  79484. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  79485. /** Left stick */
  79486. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  79487. /** Right stick */
  79488. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  79489. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  79490. /** Defines values for XBox360 DPad */
  79491. var Xbox360Dpad;
  79492. (function (Xbox360Dpad) {
  79493. /** Up */
  79494. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  79495. /** Down */
  79496. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  79497. /** Left */
  79498. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  79499. /** Right */
  79500. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  79501. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  79502. /**
  79503. * Defines a XBox360 gamepad
  79504. */
  79505. var Xbox360Pad = /** @class */ (function (_super) {
  79506. __extends(Xbox360Pad, _super);
  79507. /**
  79508. * Creates a new XBox360 gamepad object
  79509. * @param id defines the id of this gamepad
  79510. * @param index defines its index
  79511. * @param gamepad defines the internal HTML gamepad object
  79512. * @param xboxOne defines if it is a XBox One gamepad
  79513. */
  79514. function Xbox360Pad(id, index, gamepad, xboxOne) {
  79515. if (xboxOne === void 0) { xboxOne = false; }
  79516. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  79517. _this._leftTrigger = 0;
  79518. _this._rightTrigger = 0;
  79519. /** Observable raised when a button is pressed */
  79520. _this.onButtonDownObservable = new BABYLON.Observable();
  79521. /** Observable raised when a button is released */
  79522. _this.onButtonUpObservable = new BABYLON.Observable();
  79523. /** Observable raised when a pad is pressed */
  79524. _this.onPadDownObservable = new BABYLON.Observable();
  79525. /** Observable raised when a pad is released */
  79526. _this.onPadUpObservable = new BABYLON.Observable();
  79527. _this._buttonA = 0;
  79528. _this._buttonB = 0;
  79529. _this._buttonX = 0;
  79530. _this._buttonY = 0;
  79531. _this._buttonBack = 0;
  79532. _this._buttonStart = 0;
  79533. _this._buttonLB = 0;
  79534. _this._buttonRB = 0;
  79535. _this._buttonLeftStick = 0;
  79536. _this._buttonRightStick = 0;
  79537. _this._dPadUp = 0;
  79538. _this._dPadDown = 0;
  79539. _this._dPadLeft = 0;
  79540. _this._dPadRight = 0;
  79541. _this._isXboxOnePad = false;
  79542. _this.type = BABYLON.Gamepad.XBOX;
  79543. _this._isXboxOnePad = xboxOne;
  79544. return _this;
  79545. }
  79546. /**
  79547. * Defines the callback to call when left trigger is pressed
  79548. * @param callback defines the callback to use
  79549. */
  79550. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  79551. this._onlefttriggerchanged = callback;
  79552. };
  79553. /**
  79554. * Defines the callback to call when right trigger is pressed
  79555. * @param callback defines the callback to use
  79556. */
  79557. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  79558. this._onrighttriggerchanged = callback;
  79559. };
  79560. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  79561. /**
  79562. * Gets the left trigger value
  79563. */
  79564. get: function () {
  79565. return this._leftTrigger;
  79566. },
  79567. /**
  79568. * Sets the left trigger value
  79569. */
  79570. set: function (newValue) {
  79571. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  79572. this._onlefttriggerchanged(newValue);
  79573. }
  79574. this._leftTrigger = newValue;
  79575. },
  79576. enumerable: true,
  79577. configurable: true
  79578. });
  79579. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  79580. /**
  79581. * Gets the right trigger value
  79582. */
  79583. get: function () {
  79584. return this._rightTrigger;
  79585. },
  79586. /**
  79587. * Sets the right trigger value
  79588. */
  79589. set: function (newValue) {
  79590. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  79591. this._onrighttriggerchanged(newValue);
  79592. }
  79593. this._rightTrigger = newValue;
  79594. },
  79595. enumerable: true,
  79596. configurable: true
  79597. });
  79598. /**
  79599. * Defines the callback to call when a button is pressed
  79600. * @param callback defines the callback to use
  79601. */
  79602. Xbox360Pad.prototype.onbuttondown = function (callback) {
  79603. this._onbuttondown = callback;
  79604. };
  79605. /**
  79606. * Defines the callback to call when a button is released
  79607. * @param callback defines the callback to use
  79608. */
  79609. Xbox360Pad.prototype.onbuttonup = function (callback) {
  79610. this._onbuttonup = callback;
  79611. };
  79612. /**
  79613. * Defines the callback to call when a pad is pressed
  79614. * @param callback defines the callback to use
  79615. */
  79616. Xbox360Pad.prototype.ondpaddown = function (callback) {
  79617. this._ondpaddown = callback;
  79618. };
  79619. /**
  79620. * Defines the callback to call when a pad is released
  79621. * @param callback defines the callback to use
  79622. */
  79623. Xbox360Pad.prototype.ondpadup = function (callback) {
  79624. this._ondpadup = callback;
  79625. };
  79626. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  79627. if (newValue !== currentValue) {
  79628. if (newValue === 1) {
  79629. if (this._onbuttondown) {
  79630. this._onbuttondown(buttonType);
  79631. }
  79632. this.onButtonDownObservable.notifyObservers(buttonType);
  79633. }
  79634. if (newValue === 0) {
  79635. if (this._onbuttonup) {
  79636. this._onbuttonup(buttonType);
  79637. }
  79638. this.onButtonUpObservable.notifyObservers(buttonType);
  79639. }
  79640. }
  79641. return newValue;
  79642. };
  79643. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  79644. if (newValue !== currentValue) {
  79645. if (newValue === 1) {
  79646. if (this._ondpaddown) {
  79647. this._ondpaddown(buttonType);
  79648. }
  79649. this.onPadDownObservable.notifyObservers(buttonType);
  79650. }
  79651. if (newValue === 0) {
  79652. if (this._ondpadup) {
  79653. this._ondpadup(buttonType);
  79654. }
  79655. this.onPadUpObservable.notifyObservers(buttonType);
  79656. }
  79657. }
  79658. return newValue;
  79659. };
  79660. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  79661. /**
  79662. * Gets the value of the `A` button
  79663. */
  79664. get: function () {
  79665. return this._buttonA;
  79666. },
  79667. /**
  79668. * Sets the value of the `A` button
  79669. */
  79670. set: function (value) {
  79671. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  79672. },
  79673. enumerable: true,
  79674. configurable: true
  79675. });
  79676. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  79677. /**
  79678. * Gets the value of the `B` button
  79679. */
  79680. get: function () {
  79681. return this._buttonB;
  79682. },
  79683. /**
  79684. * Sets the value of the `B` button
  79685. */
  79686. set: function (value) {
  79687. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  79688. },
  79689. enumerable: true,
  79690. configurable: true
  79691. });
  79692. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  79693. /**
  79694. * Gets the value of the `X` button
  79695. */
  79696. get: function () {
  79697. return this._buttonX;
  79698. },
  79699. /**
  79700. * Sets the value of the `X` button
  79701. */
  79702. set: function (value) {
  79703. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  79704. },
  79705. enumerable: true,
  79706. configurable: true
  79707. });
  79708. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  79709. /**
  79710. * Gets the value of the `Y` button
  79711. */
  79712. get: function () {
  79713. return this._buttonY;
  79714. },
  79715. /**
  79716. * Sets the value of the `Y` button
  79717. */
  79718. set: function (value) {
  79719. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  79720. },
  79721. enumerable: true,
  79722. configurable: true
  79723. });
  79724. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  79725. /**
  79726. * Gets the value of the `Start` button
  79727. */
  79728. get: function () {
  79729. return this._buttonStart;
  79730. },
  79731. /**
  79732. * Sets the value of the `Start` button
  79733. */
  79734. set: function (value) {
  79735. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  79736. },
  79737. enumerable: true,
  79738. configurable: true
  79739. });
  79740. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  79741. /**
  79742. * Gets the value of the `Back` button
  79743. */
  79744. get: function () {
  79745. return this._buttonBack;
  79746. },
  79747. /**
  79748. * Sets the value of the `Back` button
  79749. */
  79750. set: function (value) {
  79751. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  79752. },
  79753. enumerable: true,
  79754. configurable: true
  79755. });
  79756. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  79757. /**
  79758. * Gets the value of the `Left` button
  79759. */
  79760. get: function () {
  79761. return this._buttonLB;
  79762. },
  79763. /**
  79764. * Sets the value of the `Left` button
  79765. */
  79766. set: function (value) {
  79767. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  79768. },
  79769. enumerable: true,
  79770. configurable: true
  79771. });
  79772. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  79773. /**
  79774. * Gets the value of the `Right` button
  79775. */
  79776. get: function () {
  79777. return this._buttonRB;
  79778. },
  79779. /**
  79780. * Sets the value of the `Right` button
  79781. */
  79782. set: function (value) {
  79783. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  79784. },
  79785. enumerable: true,
  79786. configurable: true
  79787. });
  79788. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  79789. /**
  79790. * Gets the value of the Left joystick
  79791. */
  79792. get: function () {
  79793. return this._buttonLeftStick;
  79794. },
  79795. /**
  79796. * Sets the value of the Left joystick
  79797. */
  79798. set: function (value) {
  79799. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  79800. },
  79801. enumerable: true,
  79802. configurable: true
  79803. });
  79804. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  79805. /**
  79806. * Gets the value of the Right joystick
  79807. */
  79808. get: function () {
  79809. return this._buttonRightStick;
  79810. },
  79811. /**
  79812. * Sets the value of the Right joystick
  79813. */
  79814. set: function (value) {
  79815. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  79816. },
  79817. enumerable: true,
  79818. configurable: true
  79819. });
  79820. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  79821. /**
  79822. * Gets the value of D-pad up
  79823. */
  79824. get: function () {
  79825. return this._dPadUp;
  79826. },
  79827. /**
  79828. * Sets the value of D-pad up
  79829. */
  79830. set: function (value) {
  79831. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  79832. },
  79833. enumerable: true,
  79834. configurable: true
  79835. });
  79836. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  79837. /**
  79838. * Gets the value of D-pad down
  79839. */
  79840. get: function () {
  79841. return this._dPadDown;
  79842. },
  79843. /**
  79844. * Sets the value of D-pad down
  79845. */
  79846. set: function (value) {
  79847. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  79848. },
  79849. enumerable: true,
  79850. configurable: true
  79851. });
  79852. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  79853. /**
  79854. * Gets the value of D-pad left
  79855. */
  79856. get: function () {
  79857. return this._dPadLeft;
  79858. },
  79859. /**
  79860. * Sets the value of D-pad left
  79861. */
  79862. set: function (value) {
  79863. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  79864. },
  79865. enumerable: true,
  79866. configurable: true
  79867. });
  79868. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  79869. /**
  79870. * Gets the value of D-pad right
  79871. */
  79872. get: function () {
  79873. return this._dPadRight;
  79874. },
  79875. /**
  79876. * Sets the value of D-pad right
  79877. */
  79878. set: function (value) {
  79879. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  79880. },
  79881. enumerable: true,
  79882. configurable: true
  79883. });
  79884. /**
  79885. * Force the gamepad to synchronize with device values
  79886. */
  79887. Xbox360Pad.prototype.update = function () {
  79888. _super.prototype.update.call(this);
  79889. if (this._isXboxOnePad) {
  79890. this.buttonA = this.browserGamepad.buttons[0].value;
  79891. this.buttonB = this.browserGamepad.buttons[1].value;
  79892. this.buttonX = this.browserGamepad.buttons[2].value;
  79893. this.buttonY = this.browserGamepad.buttons[3].value;
  79894. this.buttonLB = this.browserGamepad.buttons[4].value;
  79895. this.buttonRB = this.browserGamepad.buttons[5].value;
  79896. this.leftTrigger = this.browserGamepad.axes[2];
  79897. this.rightTrigger = this.browserGamepad.axes[5];
  79898. this.buttonBack = this.browserGamepad.buttons[9].value;
  79899. this.buttonStart = this.browserGamepad.buttons[8].value;
  79900. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  79901. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  79902. this.dPadUp = this.browserGamepad.buttons[11].value;
  79903. this.dPadDown = this.browserGamepad.buttons[12].value;
  79904. this.dPadLeft = this.browserGamepad.buttons[13].value;
  79905. this.dPadRight = this.browserGamepad.buttons[14].value;
  79906. }
  79907. else {
  79908. this.buttonA = this.browserGamepad.buttons[0].value;
  79909. this.buttonB = this.browserGamepad.buttons[1].value;
  79910. this.buttonX = this.browserGamepad.buttons[2].value;
  79911. this.buttonY = this.browserGamepad.buttons[3].value;
  79912. this.buttonLB = this.browserGamepad.buttons[4].value;
  79913. this.buttonRB = this.browserGamepad.buttons[5].value;
  79914. this.leftTrigger = this.browserGamepad.buttons[6].value;
  79915. this.rightTrigger = this.browserGamepad.buttons[7].value;
  79916. this.buttonBack = this.browserGamepad.buttons[8].value;
  79917. this.buttonStart = this.browserGamepad.buttons[9].value;
  79918. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  79919. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  79920. this.dPadUp = this.browserGamepad.buttons[12].value;
  79921. this.dPadDown = this.browserGamepad.buttons[13].value;
  79922. this.dPadLeft = this.browserGamepad.buttons[14].value;
  79923. this.dPadRight = this.browserGamepad.buttons[15].value;
  79924. }
  79925. };
  79926. /**
  79927. * Disposes the gamepad
  79928. */
  79929. Xbox360Pad.prototype.dispose = function () {
  79930. _super.prototype.dispose.call(this);
  79931. this.onButtonDownObservable.clear();
  79932. this.onButtonUpObservable.clear();
  79933. this.onPadDownObservable.clear();
  79934. this.onPadUpObservable.clear();
  79935. };
  79936. return Xbox360Pad;
  79937. }(BABYLON.Gamepad));
  79938. BABYLON.Xbox360Pad = Xbox360Pad;
  79939. })(BABYLON || (BABYLON = {}));
  79940. //# sourceMappingURL=babylon.xboxGamepad.js.map
  79941. var BABYLON;
  79942. (function (BABYLON) {
  79943. /**
  79944. * Defines the types of pose enabled controllers that are supported
  79945. */
  79946. var PoseEnabledControllerType;
  79947. (function (PoseEnabledControllerType) {
  79948. /**
  79949. * HTC Vive
  79950. */
  79951. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  79952. /**
  79953. * Oculus Rift
  79954. */
  79955. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  79956. /**
  79957. * Windows mixed reality
  79958. */
  79959. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  79960. /**
  79961. * Samsung gear VR
  79962. */
  79963. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  79964. /**
  79965. * Google Daydream
  79966. */
  79967. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  79968. /**
  79969. * Generic
  79970. */
  79971. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  79972. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  79973. /**
  79974. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  79975. */
  79976. var PoseEnabledControllerHelper = /** @class */ (function () {
  79977. function PoseEnabledControllerHelper() {
  79978. }
  79979. /**
  79980. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  79981. * @param vrGamepad the gamepad to initialized
  79982. * @returns a vr controller of the type the gamepad identified as
  79983. */
  79984. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  79985. // Oculus Touch
  79986. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  79987. return new BABYLON.OculusTouchController(vrGamepad);
  79988. }
  79989. // Windows Mixed Reality controllers
  79990. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  79991. return new BABYLON.WindowsMotionController(vrGamepad);
  79992. }
  79993. // HTC Vive
  79994. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  79995. return new BABYLON.ViveController(vrGamepad);
  79996. }
  79997. // Samsung/Oculus Gear VR or Oculus Go
  79998. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  79999. return new BABYLON.GearVRController(vrGamepad);
  80000. }
  80001. // Google Daydream
  80002. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  80003. return new BABYLON.DaydreamController(vrGamepad);
  80004. }
  80005. // Generic
  80006. else {
  80007. return new BABYLON.GenericController(vrGamepad);
  80008. }
  80009. };
  80010. return PoseEnabledControllerHelper;
  80011. }());
  80012. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  80013. /**
  80014. * Defines the PoseEnabledController object that contains state of a vr capable controller
  80015. */
  80016. var PoseEnabledController = /** @class */ (function (_super) {
  80017. __extends(PoseEnabledController, _super);
  80018. /**
  80019. * Creates a new PoseEnabledController from a gamepad
  80020. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  80021. */
  80022. function PoseEnabledController(browserGamepad) {
  80023. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  80024. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  80025. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  80026. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  80027. /**
  80028. * The device position in babylon space
  80029. */
  80030. _this.devicePosition = BABYLON.Vector3.Zero();
  80031. /**
  80032. * The device rotation in babylon space
  80033. */
  80034. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  80035. /**
  80036. * The scale factor of the device in babylon space
  80037. */
  80038. _this.deviceScaleFactor = 1;
  80039. // Used to convert 6dof controllers to 3dof
  80040. _this._trackPosition = true;
  80041. _this._maxRotationDistFromHeadset = Math.PI / 5;
  80042. _this._draggedRoomRotation = 0;
  80043. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  80044. /**
  80045. * Internal, matrix used to convert room space to babylon space
  80046. * @hidden
  80047. */
  80048. _this._deviceToWorld = BABYLON.Matrix.Identity();
  80049. /**
  80050. * Node to be used when casting a ray from the controller
  80051. * @hidden
  80052. */
  80053. _this._pointingPoseNode = null;
  80054. _this._workingMatrix = BABYLON.Matrix.Identity();
  80055. /**
  80056. * @hidden
  80057. */
  80058. _this._meshAttachedObservable = new BABYLON.Observable();
  80059. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  80060. _this.controllerType = PoseEnabledControllerType.GENERIC;
  80061. _this.position = BABYLON.Vector3.Zero();
  80062. _this.rotationQuaternion = new BABYLON.Quaternion();
  80063. _this._calculatedPosition = BABYLON.Vector3.Zero();
  80064. _this._calculatedRotation = new BABYLON.Quaternion();
  80065. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  80066. return _this;
  80067. }
  80068. /**
  80069. * @hidden
  80070. */
  80071. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  80072. if (this._trackPosition) {
  80073. this._calculatedPosition.copyFrom(fixedPosition);
  80074. this._trackPosition = false;
  80075. }
  80076. };
  80077. /**
  80078. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  80079. */
  80080. PoseEnabledController.prototype.update = function () {
  80081. _super.prototype.update.call(this);
  80082. this._updatePoseAndMesh();
  80083. };
  80084. /**
  80085. * Updates only the pose device and mesh without doing any button event checking
  80086. */
  80087. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  80088. var pose = this.browserGamepad.pose;
  80089. this.updateFromDevice(pose);
  80090. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  80091. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  80092. camera._computeDevicePosition();
  80093. this._deviceToWorld.setTranslation(camera.devicePosition);
  80094. if (camera.deviceRotationQuaternion) {
  80095. var camera = camera;
  80096. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  80097. // Find the radian distance away that the headset is from the controllers rotation
  80098. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  80099. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  80100. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  80101. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  80102. this._draggedRoomRotation += rotationAmount;
  80103. // Rotate controller around headset
  80104. var sin = Math.sin(-rotationAmount);
  80105. var cos = Math.cos(-rotationAmount);
  80106. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  80107. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  80108. }
  80109. }
  80110. }
  80111. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  80112. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  80113. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  80114. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  80115. if (this._mesh) {
  80116. this._mesh.position.copyFrom(this.devicePosition);
  80117. if (this._mesh.rotationQuaternion) {
  80118. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  80119. }
  80120. }
  80121. };
  80122. /**
  80123. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  80124. * @param poseData raw pose fromthe device
  80125. */
  80126. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  80127. if (poseData) {
  80128. this.rawPose = poseData;
  80129. if (poseData.position) {
  80130. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  80131. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  80132. this._deviceRoomPosition.z *= -1;
  80133. }
  80134. if (this._trackPosition) {
  80135. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  80136. }
  80137. this._calculatedPosition.addInPlace(this.position);
  80138. }
  80139. var pose = this.rawPose;
  80140. if (poseData.orientation && pose.orientation) {
  80141. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  80142. if (this._mesh) {
  80143. if (this._mesh.getScene().useRightHandedSystem) {
  80144. this._deviceRoomRotationQuaternion.z *= -1;
  80145. this._deviceRoomRotationQuaternion.w *= -1;
  80146. }
  80147. else {
  80148. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  80149. }
  80150. }
  80151. // if the camera is set, rotate to the camera's rotation
  80152. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  80153. }
  80154. }
  80155. };
  80156. /**
  80157. * Attaches a mesh to the controller
  80158. * @param mesh the mesh to be attached
  80159. */
  80160. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  80161. if (this._mesh) {
  80162. this._mesh.parent = null;
  80163. }
  80164. this._mesh = mesh;
  80165. if (this._poseControlledCamera) {
  80166. this._mesh.parent = this._poseControlledCamera;
  80167. }
  80168. if (!this._mesh.rotationQuaternion) {
  80169. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  80170. }
  80171. // 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
  80172. this._updatePoseAndMesh();
  80173. if (this._pointingPoseNode) {
  80174. var parents = [];
  80175. var obj = this._pointingPoseNode;
  80176. while (obj.parent) {
  80177. parents.push(obj.parent);
  80178. obj = obj.parent;
  80179. }
  80180. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  80181. }
  80182. this._meshAttachedObservable.notifyObservers(mesh);
  80183. };
  80184. /**
  80185. * Attaches the controllers mesh to a camera
  80186. * @param camera the camera the mesh should be attached to
  80187. */
  80188. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  80189. this._poseControlledCamera = camera;
  80190. if (this._mesh) {
  80191. this._mesh.parent = this._poseControlledCamera;
  80192. }
  80193. };
  80194. /**
  80195. * Disposes of the controller
  80196. */
  80197. PoseEnabledController.prototype.dispose = function () {
  80198. if (this._mesh) {
  80199. this._mesh.dispose();
  80200. }
  80201. this._mesh = null;
  80202. _super.prototype.dispose.call(this);
  80203. };
  80204. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  80205. /**
  80206. * The mesh that is attached to the controller
  80207. */
  80208. get: function () {
  80209. return this._mesh;
  80210. },
  80211. enumerable: true,
  80212. configurable: true
  80213. });
  80214. /**
  80215. * Gets the ray of the controller in the direction the controller is pointing
  80216. * @param length the length the resulting ray should be
  80217. * @returns a ray in the direction the controller is pointing
  80218. */
  80219. PoseEnabledController.prototype.getForwardRay = function (length) {
  80220. if (length === void 0) { length = 100; }
  80221. if (!this.mesh) {
  80222. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  80223. }
  80224. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  80225. var origin = m.getTranslation();
  80226. var forward = new BABYLON.Vector3(0, 0, -1);
  80227. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  80228. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  80229. return new BABYLON.Ray(origin, direction, length);
  80230. };
  80231. /**
  80232. * Name of the child mesh that can be used to cast a ray from the controller
  80233. */
  80234. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  80235. return PoseEnabledController;
  80236. }(BABYLON.Gamepad));
  80237. BABYLON.PoseEnabledController = PoseEnabledController;
  80238. })(BABYLON || (BABYLON = {}));
  80239. //# sourceMappingURL=babylon.poseEnabledController.js.map
  80240. var BABYLON;
  80241. (function (BABYLON) {
  80242. /**
  80243. * Defines the WebVRController object that represents controllers tracked in 3D space
  80244. */
  80245. var WebVRController = /** @class */ (function (_super) {
  80246. __extends(WebVRController, _super);
  80247. /**
  80248. * Creates a new WebVRController from a gamepad
  80249. * @param vrGamepad the gamepad that the WebVRController should be created from
  80250. */
  80251. function WebVRController(vrGamepad) {
  80252. var _this = _super.call(this, vrGamepad) || this;
  80253. // Observables
  80254. /**
  80255. * Fired when the trigger state has changed
  80256. */
  80257. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  80258. /**
  80259. * Fired when the main button state has changed
  80260. */
  80261. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  80262. /**
  80263. * Fired when the secondary button state has changed
  80264. */
  80265. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  80266. /**
  80267. * Fired when the pad state has changed
  80268. */
  80269. _this.onPadStateChangedObservable = new BABYLON.Observable();
  80270. /**
  80271. * Fired when controllers stick values have changed
  80272. */
  80273. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  80274. /**
  80275. * X and Y axis corrisponding to the controllers joystick
  80276. */
  80277. _this.pad = { x: 0, y: 0 };
  80278. // avoid GC, store state in a tmp object
  80279. _this._changes = {
  80280. pressChanged: false,
  80281. touchChanged: false,
  80282. valueChanged: false,
  80283. changed: false
  80284. };
  80285. _this._buttons = new Array(vrGamepad.buttons.length);
  80286. _this.hand = vrGamepad.hand;
  80287. return _this;
  80288. }
  80289. /**
  80290. * Fired when a controller button's state has changed
  80291. * @param callback the callback containing the button that was modified
  80292. */
  80293. WebVRController.prototype.onButtonStateChange = function (callback) {
  80294. this._onButtonStateChange = callback;
  80295. };
  80296. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  80297. /**
  80298. * The default controller model for the controller
  80299. */
  80300. get: function () {
  80301. return this._defaultModel;
  80302. },
  80303. enumerable: true,
  80304. configurable: true
  80305. });
  80306. /**
  80307. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  80308. */
  80309. WebVRController.prototype.update = function () {
  80310. _super.prototype.update.call(this);
  80311. for (var index = 0; index < this._buttons.length; index++) {
  80312. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  80313. }
  80314. ;
  80315. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  80316. this.pad.x = this.leftStick.x;
  80317. this.pad.y = this.leftStick.y;
  80318. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  80319. }
  80320. };
  80321. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  80322. if (!newState) {
  80323. newState = {
  80324. pressed: false,
  80325. touched: false,
  80326. value: 0
  80327. };
  80328. }
  80329. if (!currentState) {
  80330. this._buttons[buttonIndex] = {
  80331. pressed: newState.pressed,
  80332. touched: newState.touched,
  80333. value: newState.value
  80334. };
  80335. return;
  80336. }
  80337. this._checkChanges(newState, currentState);
  80338. if (this._changes.changed) {
  80339. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  80340. this._handleButtonChange(buttonIndex, newState, this._changes);
  80341. }
  80342. this._buttons[buttonIndex].pressed = newState.pressed;
  80343. this._buttons[buttonIndex].touched = newState.touched;
  80344. // oculus triggers are never 0, thou not touched.
  80345. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  80346. };
  80347. WebVRController.prototype._checkChanges = function (newState, currentState) {
  80348. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  80349. this._changes.touchChanged = newState.touched !== currentState.touched;
  80350. this._changes.valueChanged = newState.value !== currentState.value;
  80351. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  80352. return this._changes;
  80353. };
  80354. /**
  80355. * Disposes of th webVRCOntroller
  80356. */
  80357. WebVRController.prototype.dispose = function () {
  80358. _super.prototype.dispose.call(this);
  80359. this.onTriggerStateChangedObservable.clear();
  80360. this.onMainButtonStateChangedObservable.clear();
  80361. this.onSecondaryButtonStateChangedObservable.clear();
  80362. this.onPadStateChangedObservable.clear();
  80363. this.onPadValuesChangedObservable.clear();
  80364. };
  80365. return WebVRController;
  80366. }(BABYLON.PoseEnabledController));
  80367. BABYLON.WebVRController = WebVRController;
  80368. })(BABYLON || (BABYLON = {}));
  80369. //# sourceMappingURL=babylon.webVRController.js.map
  80370. var BABYLON;
  80371. (function (BABYLON) {
  80372. /**
  80373. * Oculus Touch Controller
  80374. */
  80375. var OculusTouchController = /** @class */ (function (_super) {
  80376. __extends(OculusTouchController, _super);
  80377. /**
  80378. * Creates a new OculusTouchController from a gamepad
  80379. * @param vrGamepad the gamepad that the controller should be created from
  80380. */
  80381. function OculusTouchController(vrGamepad) {
  80382. var _this = _super.call(this, vrGamepad) || this;
  80383. /**
  80384. * Fired when the secondary trigger on this controller is modified
  80385. */
  80386. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  80387. /**
  80388. * Fired when the thumb rest on this controller is modified
  80389. */
  80390. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  80391. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  80392. return _this;
  80393. }
  80394. /**
  80395. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80396. * @param scene scene in which to add meshes
  80397. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80398. */
  80399. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  80400. var _this = this;
  80401. var meshName;
  80402. // Hand
  80403. if (this.hand === 'left') {
  80404. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  80405. }
  80406. else { // Right is the default if no hand is specified
  80407. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  80408. }
  80409. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  80410. /*
  80411. Parent Mesh name: oculus_touch_left
  80412. - body
  80413. - trigger
  80414. - thumbstick
  80415. - grip
  80416. - button_y
  80417. - button_x
  80418. - button_enter
  80419. */
  80420. _this._defaultModel = newMeshes[1];
  80421. _this.attachToMesh(_this._defaultModel);
  80422. if (meshLoaded) {
  80423. meshLoaded(_this._defaultModel);
  80424. }
  80425. });
  80426. };
  80427. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  80428. /**
  80429. * Fired when the A button on this controller is modified
  80430. */
  80431. get: function () {
  80432. if (this.hand === 'right') {
  80433. return this.onMainButtonStateChangedObservable;
  80434. }
  80435. else {
  80436. throw new Error('No A button on left hand');
  80437. }
  80438. },
  80439. enumerable: true,
  80440. configurable: true
  80441. });
  80442. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  80443. /**
  80444. * Fired when the B button on this controller is modified
  80445. */
  80446. get: function () {
  80447. if (this.hand === 'right') {
  80448. return this.onSecondaryButtonStateChangedObservable;
  80449. }
  80450. else {
  80451. throw new Error('No B button on left hand');
  80452. }
  80453. },
  80454. enumerable: true,
  80455. configurable: true
  80456. });
  80457. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  80458. /**
  80459. * Fired when the X button on this controller is modified
  80460. */
  80461. get: function () {
  80462. if (this.hand === 'left') {
  80463. return this.onMainButtonStateChangedObservable;
  80464. }
  80465. else {
  80466. throw new Error('No X button on right hand');
  80467. }
  80468. },
  80469. enumerable: true,
  80470. configurable: true
  80471. });
  80472. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  80473. /**
  80474. * Fired when the Y button on this controller is modified
  80475. */
  80476. get: function () {
  80477. if (this.hand === 'left') {
  80478. return this.onSecondaryButtonStateChangedObservable;
  80479. }
  80480. else {
  80481. throw new Error('No Y button on right hand');
  80482. }
  80483. },
  80484. enumerable: true,
  80485. configurable: true
  80486. });
  80487. /**
  80488. * Called once for each button that changed state since the last frame
  80489. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  80490. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  80491. * 2) secondary trigger (same)
  80492. * 3) A (right) X (left), touch, pressed = value
  80493. * 4) B / Y
  80494. * 5) thumb rest
  80495. * @param buttonIdx Which button index changed
  80496. * @param state New state of the button
  80497. * @param changes Which properties on the state changed since last frame
  80498. */
  80499. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80500. var notifyObject = state; //{ state: state, changes: changes };
  80501. var triggerDirection = this.hand === 'right' ? -1 : 1;
  80502. switch (buttonIdx) {
  80503. case 0:
  80504. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  80505. return;
  80506. case 1: // index trigger
  80507. if (this._defaultModel) {
  80508. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  80509. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  80510. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  80511. }
  80512. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  80513. return;
  80514. case 2: // secondary trigger
  80515. if (this._defaultModel) {
  80516. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  80517. }
  80518. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  80519. return;
  80520. case 3:
  80521. if (this._defaultModel) {
  80522. if (notifyObject.pressed) {
  80523. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  80524. }
  80525. else {
  80526. (this._defaultModel.getChildren()[1]).position.y = 0;
  80527. }
  80528. }
  80529. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  80530. return;
  80531. case 4:
  80532. if (this._defaultModel) {
  80533. if (notifyObject.pressed) {
  80534. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  80535. }
  80536. else {
  80537. (this._defaultModel.getChildren()[2]).position.y = 0;
  80538. }
  80539. }
  80540. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  80541. return;
  80542. case 5:
  80543. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  80544. return;
  80545. }
  80546. };
  80547. /**
  80548. * Base Url for the controller model.
  80549. */
  80550. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  80551. /**
  80552. * File name for the left controller model.
  80553. */
  80554. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  80555. /**
  80556. * File name for the right controller model.
  80557. */
  80558. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  80559. return OculusTouchController;
  80560. }(BABYLON.WebVRController));
  80561. BABYLON.OculusTouchController = OculusTouchController;
  80562. })(BABYLON || (BABYLON = {}));
  80563. //# sourceMappingURL=babylon.oculusTouchController.js.map
  80564. var BABYLON;
  80565. (function (BABYLON) {
  80566. /**
  80567. * Vive Controller
  80568. */
  80569. var ViveController = /** @class */ (function (_super) {
  80570. __extends(ViveController, _super);
  80571. /**
  80572. * Creates a new ViveController from a gamepad
  80573. * @param vrGamepad the gamepad that the controller should be created from
  80574. */
  80575. function ViveController(vrGamepad) {
  80576. var _this = _super.call(this, vrGamepad) || this;
  80577. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  80578. _this._invertLeftStickY = true;
  80579. return _this;
  80580. }
  80581. /**
  80582. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80583. * @param scene scene in which to add meshes
  80584. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80585. */
  80586. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  80587. var _this = this;
  80588. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  80589. /*
  80590. Parent Mesh name: ViveWand
  80591. - body
  80592. - r_gripper
  80593. - l_gripper
  80594. - menu_button
  80595. - system_button
  80596. - trackpad
  80597. - trigger
  80598. - LED
  80599. */
  80600. _this._defaultModel = newMeshes[1];
  80601. _this.attachToMesh(_this._defaultModel);
  80602. if (meshLoaded) {
  80603. meshLoaded(_this._defaultModel);
  80604. }
  80605. });
  80606. };
  80607. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  80608. /**
  80609. * Fired when the left button on this controller is modified
  80610. */
  80611. get: function () {
  80612. return this.onMainButtonStateChangedObservable;
  80613. },
  80614. enumerable: true,
  80615. configurable: true
  80616. });
  80617. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  80618. /**
  80619. * Fired when the right button on this controller is modified
  80620. */
  80621. get: function () {
  80622. return this.onMainButtonStateChangedObservable;
  80623. },
  80624. enumerable: true,
  80625. configurable: true
  80626. });
  80627. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  80628. /**
  80629. * Fired when the menu button on this controller is modified
  80630. */
  80631. get: function () {
  80632. return this.onSecondaryButtonStateChangedObservable;
  80633. },
  80634. enumerable: true,
  80635. configurable: true
  80636. });
  80637. /**
  80638. * Called once for each button that changed state since the last frame
  80639. * Vive mapping:
  80640. * 0: touchpad
  80641. * 1: trigger
  80642. * 2: left AND right buttons
  80643. * 3: menu button
  80644. * @param buttonIdx Which button index changed
  80645. * @param state New state of the button
  80646. * @param changes Which properties on the state changed since last frame
  80647. */
  80648. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80649. var notifyObject = state; //{ state: state, changes: changes };
  80650. switch (buttonIdx) {
  80651. case 0:
  80652. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  80653. return;
  80654. case 1: // index trigger
  80655. if (this._defaultModel) {
  80656. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  80657. }
  80658. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  80659. return;
  80660. case 2: // left AND right button
  80661. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  80662. return;
  80663. case 3:
  80664. if (this._defaultModel) {
  80665. if (notifyObject.pressed) {
  80666. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  80667. }
  80668. else {
  80669. (this._defaultModel.getChildren()[2]).position.y = 0;
  80670. }
  80671. }
  80672. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  80673. return;
  80674. }
  80675. };
  80676. /**
  80677. * Base Url for the controller model.
  80678. */
  80679. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  80680. /**
  80681. * File name for the controller model.
  80682. */
  80683. ViveController.MODEL_FILENAME = 'wand.babylon';
  80684. return ViveController;
  80685. }(BABYLON.WebVRController));
  80686. BABYLON.ViveController = ViveController;
  80687. })(BABYLON || (BABYLON = {}));
  80688. //# sourceMappingURL=babylon.viveController.js.map
  80689. var BABYLON;
  80690. (function (BABYLON) {
  80691. /**
  80692. * Generic Controller
  80693. */
  80694. var GenericController = /** @class */ (function (_super) {
  80695. __extends(GenericController, _super);
  80696. /**
  80697. * Creates a new GenericController from a gamepad
  80698. * @param vrGamepad the gamepad that the controller should be created from
  80699. */
  80700. function GenericController(vrGamepad) {
  80701. return _super.call(this, vrGamepad) || this;
  80702. }
  80703. /**
  80704. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80705. * @param scene scene in which to add meshes
  80706. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80707. */
  80708. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  80709. var _this = this;
  80710. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  80711. _this._defaultModel = newMeshes[1];
  80712. _this.attachToMesh(_this._defaultModel);
  80713. if (meshLoaded) {
  80714. meshLoaded(_this._defaultModel);
  80715. }
  80716. });
  80717. };
  80718. /**
  80719. * Called once for each button that changed state since the last frame
  80720. * @param buttonIdx Which button index changed
  80721. * @param state New state of the button
  80722. * @param changes Which properties on the state changed since last frame
  80723. */
  80724. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80725. console.log("Button id: " + buttonIdx + "state: ");
  80726. console.dir(state);
  80727. };
  80728. /**
  80729. * Base Url for the controller model.
  80730. */
  80731. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  80732. /**
  80733. * File name for the controller model.
  80734. */
  80735. GenericController.MODEL_FILENAME = 'generic.babylon';
  80736. return GenericController;
  80737. }(BABYLON.WebVRController));
  80738. BABYLON.GenericController = GenericController;
  80739. })(BABYLON || (BABYLON = {}));
  80740. //# sourceMappingURL=babylon.genericController.js.map
  80741. var BABYLON;
  80742. (function (BABYLON) {
  80743. /**
  80744. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  80745. */
  80746. var LoadedMeshInfo = /** @class */ (function () {
  80747. function LoadedMeshInfo() {
  80748. /**
  80749. * Map of the button meshes contained in the controller
  80750. */
  80751. this.buttonMeshes = {};
  80752. /**
  80753. * Map of the axis meshes contained in the controller
  80754. */
  80755. this.axisMeshes = {};
  80756. }
  80757. return LoadedMeshInfo;
  80758. }());
  80759. /**
  80760. * Defines the WindowsMotionController object that the state of the windows motion controller
  80761. */
  80762. var WindowsMotionController = /** @class */ (function (_super) {
  80763. __extends(WindowsMotionController, _super);
  80764. /**
  80765. * Creates a new WindowsMotionController from a gamepad
  80766. * @param vrGamepad the gamepad that the controller should be created from
  80767. */
  80768. function WindowsMotionController(vrGamepad) {
  80769. var _this = _super.call(this, vrGamepad) || this;
  80770. _this._mapping = {
  80771. // Semantic button names
  80772. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  80773. // A mapping of the button name to glTF model node name
  80774. // that should be transformed by button value.
  80775. buttonMeshNames: {
  80776. 'trigger': 'SELECT',
  80777. 'menu': 'MENU',
  80778. 'grip': 'GRASP',
  80779. 'thumbstick': 'THUMBSTICK_PRESS',
  80780. 'trackpad': 'TOUCHPAD_PRESS'
  80781. },
  80782. // This mapping is used to translate from the Motion Controller to Babylon semantics
  80783. buttonObservableNames: {
  80784. 'trigger': 'onTriggerStateChangedObservable',
  80785. 'menu': 'onSecondaryButtonStateChangedObservable',
  80786. 'grip': 'onMainButtonStateChangedObservable',
  80787. 'thumbstick': 'onPadStateChangedObservable',
  80788. 'trackpad': 'onTrackpadChangedObservable'
  80789. },
  80790. // A mapping of the axis name to glTF model node name
  80791. // that should be transformed by axis value.
  80792. // This array mirrors the browserGamepad.axes array, such that
  80793. // the mesh corresponding to axis 0 is in this array index 0.
  80794. axisMeshNames: [
  80795. 'THUMBSTICK_X',
  80796. 'THUMBSTICK_Y',
  80797. 'TOUCHPAD_TOUCH_X',
  80798. 'TOUCHPAD_TOUCH_Y'
  80799. ],
  80800. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  80801. };
  80802. /**
  80803. * Fired when the trackpad on this controller is clicked
  80804. */
  80805. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  80806. /**
  80807. * Fired when the trackpad on this controller is modified
  80808. */
  80809. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  80810. /**
  80811. * The current x and y values of this controller's trackpad
  80812. */
  80813. _this.trackpad = { x: 0, y: 0 };
  80814. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  80815. _this._loadedMeshInfo = null;
  80816. return _this;
  80817. }
  80818. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  80819. /**
  80820. * Fired when the trigger on this controller is modified
  80821. */
  80822. get: function () {
  80823. return this.onTriggerStateChangedObservable;
  80824. },
  80825. enumerable: true,
  80826. configurable: true
  80827. });
  80828. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  80829. /**
  80830. * Fired when the menu button on this controller is modified
  80831. */
  80832. get: function () {
  80833. return this.onSecondaryButtonStateChangedObservable;
  80834. },
  80835. enumerable: true,
  80836. configurable: true
  80837. });
  80838. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  80839. /**
  80840. * Fired when the grip button on this controller is modified
  80841. */
  80842. get: function () {
  80843. return this.onMainButtonStateChangedObservable;
  80844. },
  80845. enumerable: true,
  80846. configurable: true
  80847. });
  80848. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  80849. /**
  80850. * Fired when the thumbstick button on this controller is modified
  80851. */
  80852. get: function () {
  80853. return this.onPadStateChangedObservable;
  80854. },
  80855. enumerable: true,
  80856. configurable: true
  80857. });
  80858. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  80859. /**
  80860. * Fired when the touchpad button on this controller is modified
  80861. */
  80862. get: function () {
  80863. return this.onTrackpadChangedObservable;
  80864. },
  80865. enumerable: true,
  80866. configurable: true
  80867. });
  80868. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  80869. /**
  80870. * Fired when the touchpad values on this controller are modified
  80871. */
  80872. get: function () {
  80873. return this.onTrackpadValuesChangedObservable;
  80874. },
  80875. enumerable: true,
  80876. configurable: true
  80877. });
  80878. WindowsMotionController.prototype._updateTrackpad = function () {
  80879. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  80880. this.trackpad.x = this.browserGamepad["axes"][2];
  80881. this.trackpad.y = this.browserGamepad["axes"][3];
  80882. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  80883. }
  80884. };
  80885. /**
  80886. * Called once per frame by the engine.
  80887. */
  80888. WindowsMotionController.prototype.update = function () {
  80889. _super.prototype.update.call(this);
  80890. if (this.browserGamepad.axes) {
  80891. this._updateTrackpad();
  80892. // Only need to animate axes if there is a loaded mesh
  80893. if (this._loadedMeshInfo) {
  80894. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  80895. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  80896. }
  80897. }
  80898. }
  80899. };
  80900. /**
  80901. * Called once for each button that changed state since the last frame
  80902. * @param buttonIdx Which button index changed
  80903. * @param state New state of the button
  80904. * @param changes Which properties on the state changed since last frame
  80905. */
  80906. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  80907. var buttonName = this._mapping.buttons[buttonIdx];
  80908. if (!buttonName) {
  80909. return;
  80910. }
  80911. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  80912. this._updateTrackpad();
  80913. // Only emit events for buttons that we know how to map from index to name
  80914. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  80915. if (observable) {
  80916. observable.notifyObservers(state);
  80917. }
  80918. this._lerpButtonTransform(buttonName, state.value);
  80919. };
  80920. /**
  80921. * Moves the buttons on the controller mesh based on their current state
  80922. * @param buttonName the name of the button to move
  80923. * @param buttonValue the value of the button which determines the buttons new position
  80924. */
  80925. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  80926. // If there is no loaded mesh, there is nothing to transform.
  80927. if (!this._loadedMeshInfo) {
  80928. return;
  80929. }
  80930. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  80931. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  80932. return;
  80933. }
  80934. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  80935. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  80936. };
  80937. /**
  80938. * Moves the axis on the controller mesh based on its current state
  80939. * @param axis the index of the axis
  80940. * @param axisValue the value of the axis which determines the meshes new position
  80941. * @hidden
  80942. */
  80943. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  80944. if (!this._loadedMeshInfo) {
  80945. return;
  80946. }
  80947. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  80948. if (!meshInfo) {
  80949. return;
  80950. }
  80951. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  80952. return;
  80953. }
  80954. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  80955. var lerpValue = axisValue * 0.5 + 0.5;
  80956. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  80957. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  80958. };
  80959. /**
  80960. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  80961. * @param scene scene in which to add meshes
  80962. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  80963. */
  80964. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  80965. var _this = this;
  80966. if (forceDefault === void 0) { forceDefault = false; }
  80967. var path;
  80968. var filename;
  80969. // Checking if GLB loader is present
  80970. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  80971. // Determine the device specific folder based on the ID suffix
  80972. var device = 'default';
  80973. if (this.id && !forceDefault) {
  80974. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  80975. device = ((match && match[0]) || device);
  80976. }
  80977. // Hand
  80978. if (this.hand === 'left') {
  80979. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  80980. }
  80981. else { // Right is the default if no hand is specified
  80982. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  80983. }
  80984. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  80985. }
  80986. else {
  80987. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  80988. path = BABYLON.GenericController.MODEL_BASE_URL;
  80989. filename = BABYLON.GenericController.MODEL_FILENAME;
  80990. }
  80991. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  80992. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  80993. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  80994. if (!_this._loadedMeshInfo) {
  80995. return;
  80996. }
  80997. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  80998. _this.attachToMesh(_this._defaultModel);
  80999. if (meshLoaded) {
  81000. meshLoaded(_this._defaultModel);
  81001. }
  81002. }, null, function (scene, message) {
  81003. BABYLON.Tools.Log(message);
  81004. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  81005. if (!forceDefault) {
  81006. _this.initControllerMesh(scene, meshLoaded, true);
  81007. }
  81008. });
  81009. };
  81010. /**
  81011. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  81012. * can be transformed by button presses and axes values, based on this._mapping.
  81013. *
  81014. * @param scene scene in which the meshes exist
  81015. * @param meshes list of meshes that make up the controller model to process
  81016. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  81017. */
  81018. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  81019. var loadedMeshInfo = null;
  81020. // Create a new mesh to contain the glTF hierarchy
  81021. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  81022. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  81023. var childMesh = null;
  81024. for (var i = 0; i < meshes.length; i++) {
  81025. var mesh = meshes[i];
  81026. if (!mesh.parent) {
  81027. // Exclude controller meshes from picking results
  81028. mesh.isPickable = false;
  81029. // Handle root node, attach to the new parentMesh
  81030. childMesh = mesh;
  81031. break;
  81032. }
  81033. }
  81034. if (childMesh) {
  81035. childMesh.setParent(parentMesh);
  81036. // Create our mesh info. Note that this method will always return non-null.
  81037. loadedMeshInfo = this.createMeshInfo(parentMesh);
  81038. }
  81039. else {
  81040. BABYLON.Tools.Warn('Could not find root node in model file.');
  81041. }
  81042. return loadedMeshInfo;
  81043. };
  81044. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  81045. var loadedMeshInfo = new LoadedMeshInfo();
  81046. var i;
  81047. loadedMeshInfo.rootNode = rootNode;
  81048. // Reset the caches
  81049. loadedMeshInfo.buttonMeshes = {};
  81050. loadedMeshInfo.axisMeshes = {};
  81051. // Button Meshes
  81052. for (i = 0; i < this._mapping.buttons.length; i++) {
  81053. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  81054. if (!buttonMeshName) {
  81055. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  81056. continue;
  81057. }
  81058. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  81059. if (!buttonMesh) {
  81060. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  81061. continue;
  81062. }
  81063. var buttonMeshInfo = {
  81064. index: i,
  81065. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  81066. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  81067. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  81068. };
  81069. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  81070. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  81071. }
  81072. else {
  81073. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  81074. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  81075. '(VALUE: ' + !!buttonMeshInfo.value +
  81076. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  81077. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  81078. ')');
  81079. }
  81080. }
  81081. // Axis Meshes
  81082. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  81083. var axisMeshName = this._mapping.axisMeshNames[i];
  81084. if (!axisMeshName) {
  81085. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  81086. continue;
  81087. }
  81088. var axisMesh = getChildByName(rootNode, axisMeshName);
  81089. if (!axisMesh) {
  81090. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  81091. continue;
  81092. }
  81093. var axisMeshInfo = {
  81094. index: i,
  81095. value: getImmediateChildByName(axisMesh, 'VALUE'),
  81096. min: getImmediateChildByName(axisMesh, 'MIN'),
  81097. max: getImmediateChildByName(axisMesh, 'MAX')
  81098. };
  81099. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  81100. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  81101. }
  81102. else {
  81103. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  81104. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  81105. '(VALUE: ' + !!axisMeshInfo.value +
  81106. ', MIN: ' + !!axisMeshInfo.min +
  81107. ', MAX:' + !!axisMeshInfo.max +
  81108. ')');
  81109. }
  81110. }
  81111. // Pointing Ray
  81112. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  81113. if (!loadedMeshInfo.pointingPoseNode) {
  81114. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  81115. }
  81116. else {
  81117. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  81118. }
  81119. return loadedMeshInfo;
  81120. // Look through all children recursively. This will return null if no mesh exists with the given name.
  81121. function getChildByName(node, name) {
  81122. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  81123. }
  81124. // Look through only immediate children. This will return null if no mesh exists with the given name.
  81125. function getImmediateChildByName(node, name) {
  81126. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  81127. }
  81128. };
  81129. /**
  81130. * Gets the ray of the controller in the direction the controller is pointing
  81131. * @param length the length the resulting ray should be
  81132. * @returns a ray in the direction the controller is pointing
  81133. */
  81134. WindowsMotionController.prototype.getForwardRay = function (length) {
  81135. if (length === void 0) { length = 100; }
  81136. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  81137. return _super.prototype.getForwardRay.call(this, length);
  81138. }
  81139. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  81140. var origin = m.getTranslation();
  81141. var forward = new BABYLON.Vector3(0, 0, -1);
  81142. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  81143. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  81144. return new BABYLON.Ray(origin, direction, length);
  81145. };
  81146. /**
  81147. * Disposes of the controller
  81148. */
  81149. WindowsMotionController.prototype.dispose = function () {
  81150. _super.prototype.dispose.call(this);
  81151. this.onTrackpadChangedObservable.clear();
  81152. };
  81153. /**
  81154. * The base url used to load the left and right controller models
  81155. */
  81156. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  81157. /**
  81158. * The name of the left controller model file
  81159. */
  81160. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  81161. /**
  81162. * The name of the right controller model file
  81163. */
  81164. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  81165. /**
  81166. * The controller name prefix for this controller type
  81167. */
  81168. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  81169. /**
  81170. * The controller id pattern for this controller type
  81171. */
  81172. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  81173. return WindowsMotionController;
  81174. }(BABYLON.WebVRController));
  81175. BABYLON.WindowsMotionController = WindowsMotionController;
  81176. })(BABYLON || (BABYLON = {}));
  81177. //# sourceMappingURL=babylon.windowsMotionController.js.map
  81178. var BABYLON;
  81179. (function (BABYLON) {
  81180. /**
  81181. * Gear VR Controller
  81182. */
  81183. var GearVRController = /** @class */ (function (_super) {
  81184. __extends(GearVRController, _super);
  81185. /**
  81186. * Creates a new GearVRController from a gamepad
  81187. * @param vrGamepad the gamepad that the controller should be created from
  81188. */
  81189. function GearVRController(vrGamepad) {
  81190. var _this = _super.call(this, vrGamepad) || this;
  81191. _this._buttonIndexToObservableNameMap = [
  81192. 'onTrackpadChangedObservable',
  81193. 'onTriggerStateChangedObservable' // Trigger
  81194. ];
  81195. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  81196. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  81197. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  81198. _this._disableTrackPosition(_this._calculatedPosition);
  81199. return _this;
  81200. }
  81201. /**
  81202. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81203. * @param scene scene in which to add meshes
  81204. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81205. */
  81206. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81207. var _this = this;
  81208. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  81209. // Offset the controller so it will rotate around the users wrist
  81210. var mesh = new BABYLON.Mesh("", scene);
  81211. newMeshes[1].parent = mesh;
  81212. newMeshes[1].position.z = -0.15;
  81213. _this._defaultModel = mesh;
  81214. _this.attachToMesh(_this._defaultModel);
  81215. if (meshLoaded) {
  81216. meshLoaded(_this._defaultModel);
  81217. }
  81218. });
  81219. };
  81220. /**
  81221. * Called once for each button that changed state since the last frame
  81222. * @param buttonIdx Which button index changed
  81223. * @param state New state of the button
  81224. * @param changes Which properties on the state changed since last frame
  81225. */
  81226. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81227. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  81228. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  81229. // Only emit events for buttons that we know how to map from index to observable
  81230. var observable = this[observableName];
  81231. if (observable) {
  81232. observable.notifyObservers(state);
  81233. }
  81234. }
  81235. };
  81236. /**
  81237. * Base Url for the controller model.
  81238. */
  81239. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  81240. /**
  81241. * File name for the controller model.
  81242. */
  81243. GearVRController.MODEL_FILENAME = 'generic.babylon';
  81244. /**
  81245. * Gamepad Id prefix used to identify this controller.
  81246. */
  81247. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  81248. return GearVRController;
  81249. }(BABYLON.WebVRController));
  81250. BABYLON.GearVRController = GearVRController;
  81251. })(BABYLON || (BABYLON = {}));
  81252. //# sourceMappingURL=babylon.gearVRController.js.map
  81253. var BABYLON;
  81254. (function (BABYLON) {
  81255. /**
  81256. * Google Daydream controller
  81257. */
  81258. var DaydreamController = /** @class */ (function (_super) {
  81259. __extends(DaydreamController, _super);
  81260. /**
  81261. * Creates a new DaydreamController from a gamepad
  81262. * @param vrGamepad the gamepad that the controller should be created from
  81263. */
  81264. function DaydreamController(vrGamepad) {
  81265. var _this = _super.call(this, vrGamepad) || this;
  81266. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  81267. return _this;
  81268. }
  81269. /**
  81270. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81271. * @param scene scene in which to add meshes
  81272. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81273. */
  81274. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81275. var _this = this;
  81276. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  81277. _this._defaultModel = newMeshes[1];
  81278. _this.attachToMesh(_this._defaultModel);
  81279. if (meshLoaded) {
  81280. meshLoaded(_this._defaultModel);
  81281. }
  81282. });
  81283. };
  81284. /**
  81285. * Called once for each button that changed state since the last frame
  81286. * @param buttonIdx Which button index changed
  81287. * @param state New state of the button
  81288. * @param changes Which properties on the state changed since last frame
  81289. */
  81290. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81291. // Daydream controller only has 1 GamepadButton (on the trackpad).
  81292. if (buttonIdx === 0) {
  81293. var observable = this.onTriggerStateChangedObservable;
  81294. if (observable) {
  81295. observable.notifyObservers(state);
  81296. }
  81297. }
  81298. else {
  81299. // If the app or home buttons are ever made available
  81300. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  81301. }
  81302. };
  81303. /**
  81304. * Base Url for the controller model.
  81305. */
  81306. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  81307. /**
  81308. * File name for the controller model.
  81309. */
  81310. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  81311. /**
  81312. * Gamepad Id prefix used to identify Daydream Controller.
  81313. */
  81314. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  81315. return DaydreamController;
  81316. }(BABYLON.WebVRController));
  81317. BABYLON.DaydreamController = DaydreamController;
  81318. })(BABYLON || (BABYLON = {}));
  81319. //# sourceMappingURL=babylon.daydreamController.js.map
  81320. var BABYLON;
  81321. (function (BABYLON) {
  81322. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  81323. get: function () {
  81324. if (!this._gamepadManager) {
  81325. this._gamepadManager = new BABYLON.GamepadManager(this);
  81326. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  81327. if (!component) {
  81328. component = new GamepadSystemSceneComponent(this);
  81329. this._addComponent(component);
  81330. }
  81331. }
  81332. return this._gamepadManager;
  81333. },
  81334. enumerable: true,
  81335. configurable: true
  81336. });
  81337. /**
  81338. * Adds a gamepad to the free camera inputs manager
  81339. */
  81340. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  81341. this.add(new BABYLON.FreeCameraGamepadInput());
  81342. return this;
  81343. };
  81344. /**
  81345. * Adds a gamepad to the arc rotate camera inputs manager
  81346. */
  81347. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  81348. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  81349. return this;
  81350. };
  81351. /**
  81352. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  81353. */
  81354. var GamepadSystemSceneComponent = /** @class */ (function () {
  81355. /**
  81356. * Creates a new instance of the component for the given scene
  81357. * @param scene Defines the scene to register the component in
  81358. */
  81359. function GamepadSystemSceneComponent(scene) {
  81360. /**
  81361. * The component name helpfull to identify the component in the list of scene components.
  81362. */
  81363. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  81364. this.scene = scene;
  81365. }
  81366. /**
  81367. * Registers the component in a given scene
  81368. */
  81369. GamepadSystemSceneComponent.prototype.register = function () {
  81370. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  81371. };
  81372. /**
  81373. * Rebuilds the elements related to this component in case of
  81374. * context lost for instance.
  81375. */
  81376. GamepadSystemSceneComponent.prototype.rebuild = function () {
  81377. // Nothing to do for gamepads
  81378. };
  81379. /**
  81380. * Disposes the component and the associated ressources
  81381. */
  81382. GamepadSystemSceneComponent.prototype.dispose = function () {
  81383. var gamepadManager = this.scene._gamepadManager;
  81384. if (gamepadManager) {
  81385. gamepadManager.dispose();
  81386. this.scene._gamepadManager = null;
  81387. }
  81388. };
  81389. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  81390. var gamepadManager = this.scene._gamepadManager;
  81391. if (gamepadManager && gamepadManager._isMonitoring) {
  81392. gamepadManager._checkGamepadsStatus();
  81393. }
  81394. };
  81395. return GamepadSystemSceneComponent;
  81396. }());
  81397. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  81398. })(BABYLON || (BABYLON = {}));
  81399. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  81400. var BABYLON;
  81401. (function (BABYLON) {
  81402. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  81403. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  81404. });
  81405. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  81406. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  81407. });
  81408. /**
  81409. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  81410. * an arc rotate version arcFollowCamera are available.
  81411. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  81412. */
  81413. var FollowCamera = /** @class */ (function (_super) {
  81414. __extends(FollowCamera, _super);
  81415. /**
  81416. * Instantiates the follow camera.
  81417. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  81418. * @param name Define the name of the camera in the scene
  81419. * @param position Define the position of the camera
  81420. * @param scene Define the scene the camera belong to
  81421. * @param lockedTarget Define the target of the camera
  81422. */
  81423. function FollowCamera(name, position, scene, lockedTarget) {
  81424. if (lockedTarget === void 0) { lockedTarget = null; }
  81425. var _this = _super.call(this, name, position, scene) || this;
  81426. /**
  81427. * Distance the follow camera should follow an object at
  81428. */
  81429. _this.radius = 12;
  81430. /**
  81431. * Define a rotation offset between the camera and the object it follows
  81432. */
  81433. _this.rotationOffset = 0;
  81434. /**
  81435. * Define a height offset between the camera and the object it follows.
  81436. * It can help following an object from the top (like a car chaing a plane)
  81437. */
  81438. _this.heightOffset = 4;
  81439. /**
  81440. * Define how fast the camera can accelerate to follow it s target.
  81441. */
  81442. _this.cameraAcceleration = 0.05;
  81443. /**
  81444. * Define the speed limit of the camera following an object.
  81445. */
  81446. _this.maxCameraSpeed = 20;
  81447. _this.lockedTarget = lockedTarget;
  81448. return _this;
  81449. }
  81450. FollowCamera.prototype._follow = function (cameraTarget) {
  81451. if (!cameraTarget)
  81452. return;
  81453. var yRotation;
  81454. if (cameraTarget.rotationQuaternion) {
  81455. var rotMatrix = new BABYLON.Matrix();
  81456. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  81457. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  81458. }
  81459. else {
  81460. yRotation = cameraTarget.rotation.y;
  81461. }
  81462. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  81463. var targetPosition = cameraTarget.getAbsolutePosition();
  81464. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  81465. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  81466. var dx = targetX - this.position.x;
  81467. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  81468. var dz = (targetZ) - this.position.z;
  81469. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  81470. var vy = dy * this.cameraAcceleration;
  81471. var vz = dz * this.cameraAcceleration * 2;
  81472. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  81473. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  81474. }
  81475. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  81476. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  81477. }
  81478. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  81479. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  81480. }
  81481. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  81482. this.setTarget(targetPosition);
  81483. };
  81484. /** @hidden */
  81485. FollowCamera.prototype._checkInputs = function () {
  81486. _super.prototype._checkInputs.call(this);
  81487. if (this.lockedTarget) {
  81488. this._follow(this.lockedTarget);
  81489. }
  81490. };
  81491. /**
  81492. * Gets the camera class name.
  81493. * @returns the class name
  81494. */
  81495. FollowCamera.prototype.getClassName = function () {
  81496. return "FollowCamera";
  81497. };
  81498. __decorate([
  81499. BABYLON.serialize()
  81500. ], FollowCamera.prototype, "radius", void 0);
  81501. __decorate([
  81502. BABYLON.serialize()
  81503. ], FollowCamera.prototype, "rotationOffset", void 0);
  81504. __decorate([
  81505. BABYLON.serialize()
  81506. ], FollowCamera.prototype, "heightOffset", void 0);
  81507. __decorate([
  81508. BABYLON.serialize()
  81509. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  81510. __decorate([
  81511. BABYLON.serialize()
  81512. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  81513. __decorate([
  81514. BABYLON.serializeAsMeshReference("lockedTargetId")
  81515. ], FollowCamera.prototype, "lockedTarget", void 0);
  81516. return FollowCamera;
  81517. }(BABYLON.TargetCamera));
  81518. BABYLON.FollowCamera = FollowCamera;
  81519. /**
  81520. * Arc Rotate version of the follow camera.
  81521. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  81522. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  81523. */
  81524. var ArcFollowCamera = /** @class */ (function (_super) {
  81525. __extends(ArcFollowCamera, _super);
  81526. /**
  81527. * Instantiates a new ArcFollowCamera
  81528. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  81529. * @param name Define the name of the camera
  81530. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  81531. * @param beta Define the rotation angle of the camera around the elevation axis
  81532. * @param radius Define the radius of the camera from its target point
  81533. * @param target Define the target of the camera
  81534. * @param scene Define the scene the camera belongs to
  81535. */
  81536. function ArcFollowCamera(name,
  81537. /** The longitudinal angle of the camera */
  81538. alpha,
  81539. /** The latitudinal angle of the camera */
  81540. beta,
  81541. /** The radius of the camera from its target */
  81542. radius,
  81543. /** Define the camera target (the messh it should follow) */
  81544. target, scene) {
  81545. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  81546. _this.alpha = alpha;
  81547. _this.beta = beta;
  81548. _this.radius = radius;
  81549. _this.target = target;
  81550. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  81551. _this._follow();
  81552. return _this;
  81553. }
  81554. ArcFollowCamera.prototype._follow = function () {
  81555. if (!this.target) {
  81556. return;
  81557. }
  81558. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  81559. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  81560. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  81561. var targetPosition = this.target.getAbsolutePosition();
  81562. this.position = targetPosition.add(this._cartesianCoordinates);
  81563. this.setTarget(targetPosition);
  81564. };
  81565. /** @hidden */
  81566. ArcFollowCamera.prototype._checkInputs = function () {
  81567. _super.prototype._checkInputs.call(this);
  81568. this._follow();
  81569. };
  81570. /**
  81571. * Returns the class name of the object.
  81572. * It is mostly used internally for serialization purposes.
  81573. */
  81574. ArcFollowCamera.prototype.getClassName = function () {
  81575. return "ArcFollowCamera";
  81576. };
  81577. return ArcFollowCamera;
  81578. }(BABYLON.TargetCamera));
  81579. BABYLON.ArcFollowCamera = ArcFollowCamera;
  81580. })(BABYLON || (BABYLON = {}));
  81581. //# sourceMappingURL=babylon.followCamera.js.map
  81582. var BABYLON;
  81583. (function (BABYLON) {
  81584. /**
  81585. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  81586. * which still works and will still be found in many Playgrounds.
  81587. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  81588. */
  81589. var UniversalCamera = /** @class */ (function (_super) {
  81590. __extends(UniversalCamera, _super);
  81591. /**
  81592. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  81593. * which still works and will still be found in many Playgrounds.
  81594. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  81595. * @param name Define the name of the camera in the scene
  81596. * @param position Define the start position of the camera in the scene
  81597. * @param scene Define the scene the camera belongs to
  81598. */
  81599. function UniversalCamera(name, position, scene) {
  81600. var _this = _super.call(this, name, position, scene) || this;
  81601. _this.inputs.addGamepad();
  81602. return _this;
  81603. }
  81604. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  81605. /**
  81606. * Defines the gamepad rotation sensiblity.
  81607. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  81608. */
  81609. get: function () {
  81610. var gamepad = this.inputs.attached["gamepad"];
  81611. if (gamepad)
  81612. return gamepad.gamepadAngularSensibility;
  81613. return 0;
  81614. },
  81615. set: function (value) {
  81616. var gamepad = this.inputs.attached["gamepad"];
  81617. if (gamepad)
  81618. gamepad.gamepadAngularSensibility = value;
  81619. },
  81620. enumerable: true,
  81621. configurable: true
  81622. });
  81623. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  81624. /**
  81625. * Defines the gamepad move sensiblity.
  81626. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  81627. */
  81628. get: function () {
  81629. var gamepad = this.inputs.attached["gamepad"];
  81630. if (gamepad)
  81631. return gamepad.gamepadMoveSensibility;
  81632. return 0;
  81633. },
  81634. set: function (value) {
  81635. var gamepad = this.inputs.attached["gamepad"];
  81636. if (gamepad)
  81637. gamepad.gamepadMoveSensibility = value;
  81638. },
  81639. enumerable: true,
  81640. configurable: true
  81641. });
  81642. /**
  81643. * Gets the current object class name.
  81644. * @return the class name
  81645. */
  81646. UniversalCamera.prototype.getClassName = function () {
  81647. return "UniversalCamera";
  81648. };
  81649. return UniversalCamera;
  81650. }(BABYLON.TouchCamera));
  81651. BABYLON.UniversalCamera = UniversalCamera;
  81652. })(BABYLON || (BABYLON = {}));
  81653. //# sourceMappingURL=babylon.universalCamera.js.map
  81654. var BABYLON;
  81655. (function (BABYLON) {
  81656. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  81657. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  81658. });
  81659. /**
  81660. * This represents a FPS type of camera. This is only here for back compat purpose.
  81661. * Please use the UniversalCamera instead as both are identical.
  81662. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  81663. */
  81664. var GamepadCamera = /** @class */ (function (_super) {
  81665. __extends(GamepadCamera, _super);
  81666. /**
  81667. * Instantiates a new Gamepad Camera
  81668. * This represents a FPS type of camera. This is only here for back compat purpose.
  81669. * Please use the UniversalCamera instead as both are identical.
  81670. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  81671. * @param name Define the name of the camera in the scene
  81672. * @param position Define the start position of the camera in the scene
  81673. * @param scene Define the scene the camera belongs to
  81674. */
  81675. function GamepadCamera(name, position, scene) {
  81676. return _super.call(this, name, position, scene) || this;
  81677. }
  81678. /**
  81679. * Gets the current object class name.
  81680. * @return the class name
  81681. */
  81682. GamepadCamera.prototype.getClassName = function () {
  81683. return "GamepadCamera";
  81684. };
  81685. return GamepadCamera;
  81686. }(BABYLON.UniversalCamera));
  81687. BABYLON.GamepadCamera = GamepadCamera;
  81688. })(BABYLON || (BABYLON = {}));
  81689. //# sourceMappingURL=babylon.gamepadCamera.js.map
  81690. var BABYLON;
  81691. (function (BABYLON) {
  81692. /**
  81693. * PostProcessRenderPipelineManager class
  81694. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  81695. */
  81696. var PostProcessRenderPipelineManager = /** @class */ (function () {
  81697. /**
  81698. * Initializes a PostProcessRenderPipelineManager
  81699. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  81700. */
  81701. function PostProcessRenderPipelineManager() {
  81702. this._renderPipelines = {};
  81703. }
  81704. /**
  81705. * Adds a pipeline to the manager
  81706. * @param renderPipeline The pipeline to add
  81707. */
  81708. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  81709. this._renderPipelines[renderPipeline._name] = renderPipeline;
  81710. };
  81711. /**
  81712. * Attaches a camera to the pipeline
  81713. * @param renderPipelineName The name of the pipeline to attach to
  81714. * @param cameras the camera to attach
  81715. * @param unique if the camera can be attached multiple times to the pipeline
  81716. */
  81717. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  81718. if (unique === void 0) { unique = false; }
  81719. var renderPipeline = this._renderPipelines[renderPipelineName];
  81720. if (!renderPipeline) {
  81721. return;
  81722. }
  81723. renderPipeline._attachCameras(cameras, unique);
  81724. };
  81725. /**
  81726. * Detaches a camera from the pipeline
  81727. * @param renderPipelineName The name of the pipeline to detach from
  81728. * @param cameras the camera to detach
  81729. */
  81730. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  81731. var renderPipeline = this._renderPipelines[renderPipelineName];
  81732. if (!renderPipeline) {
  81733. return;
  81734. }
  81735. renderPipeline._detachCameras(cameras);
  81736. };
  81737. /**
  81738. * Enables an effect by name on a pipeline
  81739. * @param renderPipelineName the name of the pipeline to enable the effect in
  81740. * @param renderEffectName the name of the effect to enable
  81741. * @param cameras the cameras that the effect should be enabled on
  81742. */
  81743. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  81744. var renderPipeline = this._renderPipelines[renderPipelineName];
  81745. if (!renderPipeline) {
  81746. return;
  81747. }
  81748. renderPipeline._enableEffect(renderEffectName, cameras);
  81749. };
  81750. /**
  81751. * Disables an effect by name on a pipeline
  81752. * @param renderPipelineName the name of the pipeline to disable the effect in
  81753. * @param renderEffectName the name of the effect to disable
  81754. * @param cameras the cameras that the effect should be disabled on
  81755. */
  81756. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  81757. var renderPipeline = this._renderPipelines[renderPipelineName];
  81758. if (!renderPipeline) {
  81759. return;
  81760. }
  81761. renderPipeline._disableEffect(renderEffectName, cameras);
  81762. };
  81763. /**
  81764. * Updates the state of all contained render pipelines and disposes of any non supported pipelines
  81765. */
  81766. PostProcessRenderPipelineManager.prototype.update = function () {
  81767. for (var renderPipelineName in this._renderPipelines) {
  81768. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  81769. var pipeline = this._renderPipelines[renderPipelineName];
  81770. if (!pipeline.isSupported) {
  81771. pipeline.dispose();
  81772. delete this._renderPipelines[renderPipelineName];
  81773. }
  81774. else {
  81775. pipeline._update();
  81776. }
  81777. }
  81778. }
  81779. };
  81780. /** @hidden */
  81781. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  81782. for (var renderPipelineName in this._renderPipelines) {
  81783. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  81784. var pipeline = this._renderPipelines[renderPipelineName];
  81785. pipeline._rebuild();
  81786. }
  81787. }
  81788. };
  81789. /**
  81790. * Disposes of the manager and pipelines
  81791. */
  81792. PostProcessRenderPipelineManager.prototype.dispose = function () {
  81793. for (var renderPipelineName in this._renderPipelines) {
  81794. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  81795. var pipeline = this._renderPipelines[renderPipelineName];
  81796. pipeline.dispose();
  81797. }
  81798. }
  81799. };
  81800. return PostProcessRenderPipelineManager;
  81801. }());
  81802. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  81803. })(BABYLON || (BABYLON = {}));
  81804. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  81805. var BABYLON;
  81806. (function (BABYLON) {
  81807. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  81808. get: function () {
  81809. if (!this._postProcessRenderPipelineManager) {
  81810. // Register the G Buffer component to the scene.
  81811. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  81812. if (!component) {
  81813. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  81814. this._addComponent(component);
  81815. }
  81816. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  81817. }
  81818. return this._postProcessRenderPipelineManager;
  81819. },
  81820. enumerable: true,
  81821. configurable: true
  81822. });
  81823. /**
  81824. * Defines the Render Pipeline scene component responsible to rendering pipelines
  81825. */
  81826. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  81827. /**
  81828. * Creates a new instance of the component for the given scene
  81829. * @param scene Defines the scene to register the component in
  81830. */
  81831. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  81832. /**
  81833. * The component name helpfull to identify the component in the list of scene components.
  81834. */
  81835. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  81836. this.scene = scene;
  81837. }
  81838. /**
  81839. * Registers the component in a given scene
  81840. */
  81841. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  81842. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  81843. };
  81844. /**
  81845. * Rebuilds the elements related to this component in case of
  81846. * context lost for instance.
  81847. */
  81848. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  81849. if (this.scene._postProcessRenderPipelineManager) {
  81850. this.scene._postProcessRenderPipelineManager._rebuild();
  81851. }
  81852. };
  81853. /**
  81854. * Disposes the component and the associated ressources
  81855. */
  81856. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  81857. if (this.scene._postProcessRenderPipelineManager) {
  81858. this.scene._postProcessRenderPipelineManager.dispose();
  81859. }
  81860. };
  81861. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  81862. if (this.scene._postProcessRenderPipelineManager) {
  81863. this.scene._postProcessRenderPipelineManager.update();
  81864. }
  81865. };
  81866. return PostProcessRenderPipelineManagerSceneComponent;
  81867. }());
  81868. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  81869. })(BABYLON || (BABYLON = {}));
  81870. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  81871. var BABYLON;
  81872. (function (BABYLON) {
  81873. /**
  81874. * This represents a set of one or more post processes in Babylon.
  81875. * A post process can be used to apply a shader to a texture after it is rendered.
  81876. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  81877. */
  81878. var PostProcessRenderEffect = /** @class */ (function () {
  81879. /**
  81880. * Instantiates a post process render effect.
  81881. * A post process can be used to apply a shader to a texture after it is rendered.
  81882. * @param engine The engine the effect is tied to
  81883. * @param name The name of the effect
  81884. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  81885. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  81886. */
  81887. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  81888. this._name = name;
  81889. this._singleInstance = singleInstance || true;
  81890. this._getPostProcesses = getPostProcesses;
  81891. this._cameras = {};
  81892. this._indicesForCamera = {};
  81893. this._postProcesses = {};
  81894. }
  81895. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  81896. /**
  81897. * Checks if all the post processes in the effect are supported.
  81898. */
  81899. get: function () {
  81900. for (var index in this._postProcesses) {
  81901. if (this._postProcesses.hasOwnProperty(index)) {
  81902. var pps = this._postProcesses[index];
  81903. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  81904. if (!pps[ppIndex].isSupported) {
  81905. return false;
  81906. }
  81907. }
  81908. }
  81909. }
  81910. return true;
  81911. },
  81912. enumerable: true,
  81913. configurable: true
  81914. });
  81915. /**
  81916. * Updates the current state of the effect
  81917. * @hidden
  81918. */
  81919. PostProcessRenderEffect.prototype._update = function () {
  81920. };
  81921. /**
  81922. * Attaches the effect on cameras
  81923. * @param cameras The camera to attach to.
  81924. * @hidden
  81925. */
  81926. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  81927. var _this = this;
  81928. var cameraKey;
  81929. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81930. if (!cams) {
  81931. return;
  81932. }
  81933. for (var i = 0; i < cams.length; i++) {
  81934. var camera = cams[i];
  81935. var cameraName = camera.name;
  81936. if (this._singleInstance) {
  81937. cameraKey = 0;
  81938. }
  81939. else {
  81940. cameraKey = cameraName;
  81941. }
  81942. if (!this._postProcesses[cameraKey]) {
  81943. var postProcess = this._getPostProcesses();
  81944. if (postProcess) {
  81945. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  81946. }
  81947. }
  81948. if (!this._indicesForCamera[cameraName]) {
  81949. this._indicesForCamera[cameraName] = [];
  81950. }
  81951. this._postProcesses[cameraKey].forEach(function (postProcess) {
  81952. var index = camera.attachPostProcess(postProcess);
  81953. _this._indicesForCamera[cameraName].push(index);
  81954. });
  81955. if (!this._cameras[cameraName]) {
  81956. this._cameras[cameraName] = camera;
  81957. }
  81958. }
  81959. };
  81960. /**
  81961. * Detatches the effect on cameras
  81962. * @param cameras The camera to detatch from.
  81963. * @hidden
  81964. */
  81965. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  81966. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81967. if (!cams) {
  81968. return;
  81969. }
  81970. for (var i = 0; i < cams.length; i++) {
  81971. var camera = cams[i];
  81972. var cameraName = camera.name;
  81973. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  81974. camera.detachPostProcess(postProcess);
  81975. });
  81976. if (this._cameras[cameraName]) {
  81977. //this._indicesForCamera.splice(index, 1);
  81978. this._cameras[cameraName] = null;
  81979. }
  81980. }
  81981. };
  81982. /**
  81983. * Enables the effect on given cameras
  81984. * @param cameras The camera to enable.
  81985. * @hidden
  81986. */
  81987. PostProcessRenderEffect.prototype._enable = function (cameras) {
  81988. var _this = this;
  81989. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  81990. if (!cams) {
  81991. return;
  81992. }
  81993. for (var i = 0; i < cams.length; i++) {
  81994. var camera = cams[i];
  81995. var cameraName = camera.name;
  81996. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  81997. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  81998. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  81999. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  82000. });
  82001. }
  82002. }
  82003. }
  82004. };
  82005. /**
  82006. * Disables the effect on the given cameras
  82007. * @param cameras The camera to disable.
  82008. * @hidden
  82009. */
  82010. PostProcessRenderEffect.prototype._disable = function (cameras) {
  82011. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82012. if (!cams) {
  82013. return;
  82014. }
  82015. for (var i = 0; i < cams.length; i++) {
  82016. var camera = cams[i];
  82017. var cameraName = camera.name;
  82018. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  82019. camera.detachPostProcess(postProcess);
  82020. });
  82021. }
  82022. };
  82023. /**
  82024. * Gets a list of the post processes contained in the effect.
  82025. * @param camera The camera to get the post processes on.
  82026. * @returns The list of the post processes in the effect.
  82027. */
  82028. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  82029. if (this._singleInstance) {
  82030. return this._postProcesses[0];
  82031. }
  82032. else {
  82033. if (!camera) {
  82034. return null;
  82035. }
  82036. return this._postProcesses[camera.name];
  82037. }
  82038. };
  82039. return PostProcessRenderEffect;
  82040. }());
  82041. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  82042. })(BABYLON || (BABYLON = {}));
  82043. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  82044. var BABYLON;
  82045. (function (BABYLON) {
  82046. /**
  82047. * PostProcessRenderPipeline
  82048. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82049. */
  82050. var PostProcessRenderPipeline = /** @class */ (function () {
  82051. /**
  82052. * Initializes a PostProcessRenderPipeline
  82053. * @param engine engine to add the pipeline to
  82054. * @param name name of the pipeline
  82055. */
  82056. function PostProcessRenderPipeline(engine, name) {
  82057. this.engine = engine;
  82058. this._name = name;
  82059. this._renderEffects = {};
  82060. this._renderEffectsForIsolatedPass = new Array();
  82061. this._cameras = [];
  82062. }
  82063. /**
  82064. * "PostProcessRenderPipeline"
  82065. * @returns "PostProcessRenderPipeline"
  82066. */
  82067. PostProcessRenderPipeline.prototype.getClassName = function () {
  82068. return "PostProcessRenderPipeline";
  82069. };
  82070. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  82071. /**
  82072. * If all the render effects in the pipeline are support
  82073. */
  82074. get: function () {
  82075. for (var renderEffectName in this._renderEffects) {
  82076. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  82077. if (!this._renderEffects[renderEffectName].isSupported) {
  82078. return false;
  82079. }
  82080. }
  82081. }
  82082. return true;
  82083. },
  82084. enumerable: true,
  82085. configurable: true
  82086. });
  82087. /**
  82088. * Adds an effect to the pipeline
  82089. * @param renderEffect the effect to add
  82090. */
  82091. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  82092. this._renderEffects[renderEffect._name] = renderEffect;
  82093. };
  82094. // private
  82095. /** @hidden */
  82096. PostProcessRenderPipeline.prototype._rebuild = function () {
  82097. };
  82098. /** @hidden */
  82099. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  82100. var renderEffects = this._renderEffects[renderEffectName];
  82101. if (!renderEffects) {
  82102. return;
  82103. }
  82104. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  82105. };
  82106. /** @hidden */
  82107. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  82108. var renderEffects = this._renderEffects[renderEffectName];
  82109. if (!renderEffects) {
  82110. return;
  82111. }
  82112. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  82113. };
  82114. /** @hidden */
  82115. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  82116. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82117. if (!cams) {
  82118. return;
  82119. }
  82120. var indicesToDelete = [];
  82121. var i;
  82122. for (i = 0; i < cams.length; i++) {
  82123. var camera = cams[i];
  82124. var cameraName = camera.name;
  82125. if (this._cameras.indexOf(camera) === -1) {
  82126. this._cameras[cameraName] = camera;
  82127. }
  82128. else if (unique) {
  82129. indicesToDelete.push(i);
  82130. }
  82131. }
  82132. for (i = 0; i < indicesToDelete.length; i++) {
  82133. cameras.splice(indicesToDelete[i], 1);
  82134. }
  82135. for (var renderEffectName in this._renderEffects) {
  82136. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  82137. this._renderEffects[renderEffectName]._attachCameras(cams);
  82138. }
  82139. }
  82140. };
  82141. /** @hidden */
  82142. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  82143. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82144. if (!cams) {
  82145. return;
  82146. }
  82147. for (var renderEffectName in this._renderEffects) {
  82148. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  82149. this._renderEffects[renderEffectName]._detachCameras(cams);
  82150. }
  82151. }
  82152. for (var i = 0; i < cams.length; i++) {
  82153. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  82154. }
  82155. };
  82156. /** @hidden */
  82157. PostProcessRenderPipeline.prototype._update = function () {
  82158. for (var renderEffectName in this._renderEffects) {
  82159. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  82160. this._renderEffects[renderEffectName]._update();
  82161. }
  82162. }
  82163. for (var i = 0; i < this._cameras.length; i++) {
  82164. var cameraName = this._cameras[i].name;
  82165. if (this._renderEffectsForIsolatedPass[cameraName]) {
  82166. this._renderEffectsForIsolatedPass[cameraName]._update();
  82167. }
  82168. }
  82169. };
  82170. /** @hidden */
  82171. PostProcessRenderPipeline.prototype._reset = function () {
  82172. this._renderEffects = {};
  82173. this._renderEffectsForIsolatedPass = new Array();
  82174. };
  82175. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  82176. // 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)
  82177. var effectKeys = Object.keys(this._renderEffects);
  82178. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  82179. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  82180. if (postProcesses) {
  82181. postProcesses[0].samples = sampleCount;
  82182. return true;
  82183. }
  82184. }
  82185. return false;
  82186. };
  82187. /**
  82188. * Disposes of the pipeline
  82189. */
  82190. PostProcessRenderPipeline.prototype.dispose = function () {
  82191. // Must be implemented by children
  82192. };
  82193. __decorate([
  82194. BABYLON.serialize()
  82195. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  82196. return PostProcessRenderPipeline;
  82197. }());
  82198. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  82199. })(BABYLON || (BABYLON = {}));
  82200. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  82201. var BABYLON;
  82202. (function (BABYLON) {
  82203. /**
  82204. * This represents a depth renderer in Babylon.
  82205. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  82206. */
  82207. var DepthRenderer = /** @class */ (function () {
  82208. /**
  82209. * Instantiates a depth renderer
  82210. * @param scene The scene the renderer belongs to
  82211. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  82212. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  82213. */
  82214. function DepthRenderer(scene, type, camera) {
  82215. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  82216. if (camera === void 0) { camera = null; }
  82217. var _this = this;
  82218. /**
  82219. * Specifiess that the depth renderer will only be used within
  82220. * the camera it is created for.
  82221. * This can help forcing its rendering during the camera processing.
  82222. */
  82223. this.useOnlyInActiveCamera = false;
  82224. this._scene = scene;
  82225. // Register the G Buffer component to the scene.
  82226. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  82227. if (!component) {
  82228. component = new BABYLON.DepthRendererSceneComponent(scene);
  82229. scene._addComponent(component);
  82230. }
  82231. this._camera = camera;
  82232. var engine = scene.getEngine();
  82233. // Render target
  82234. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  82235. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82236. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82237. this._depthMap.refreshRate = 1;
  82238. this._depthMap.renderParticles = false;
  82239. this._depthMap.renderList = null;
  82240. // Camera to get depth map from to support multiple concurrent cameras
  82241. this._depthMap.activeCamera = this._camera;
  82242. this._depthMap.ignoreCameraViewport = true;
  82243. this._depthMap.useCameraPostProcesses = false;
  82244. // set default depth value to 1.0 (far away)
  82245. this._depthMap.onClearObservable.add(function (engine) {
  82246. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  82247. });
  82248. // Custom render function
  82249. var renderSubMesh = function (subMesh) {
  82250. var mesh = subMesh.getRenderingMesh();
  82251. var scene = _this._scene;
  82252. var engine = scene.getEngine();
  82253. var material = subMesh.getMaterial();
  82254. if (!material) {
  82255. return;
  82256. }
  82257. // Culling and reverse (right handed system)
  82258. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  82259. // Managing instances
  82260. var batch = mesh._getInstancesRenderList(subMesh._id);
  82261. if (batch.mustReturn) {
  82262. return;
  82263. }
  82264. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  82265. var camera = _this._camera || scene.activeCamera;
  82266. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  82267. engine.enableEffect(_this._effect);
  82268. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  82269. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  82270. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  82271. // Alpha test
  82272. if (material && material.needAlphaTesting()) {
  82273. var alphaTexture = material.getAlphaTestTexture();
  82274. if (alphaTexture) {
  82275. _this._effect.setTexture("diffuseSampler", alphaTexture);
  82276. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  82277. }
  82278. }
  82279. // Bones
  82280. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82281. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82282. }
  82283. // Draw
  82284. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  82285. }
  82286. };
  82287. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82288. var index;
  82289. if (depthOnlySubMeshes.length) {
  82290. engine.setColorWrite(false);
  82291. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82292. renderSubMesh(depthOnlySubMeshes.data[index]);
  82293. }
  82294. engine.setColorWrite(true);
  82295. }
  82296. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82297. renderSubMesh(opaqueSubMeshes.data[index]);
  82298. }
  82299. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82300. renderSubMesh(alphaTestSubMeshes.data[index]);
  82301. }
  82302. };
  82303. }
  82304. /**
  82305. * Creates the depth rendering effect and checks if the effect is ready.
  82306. * @param subMesh The submesh to be used to render the depth map of
  82307. * @param useInstances If multiple world instances should be used
  82308. * @returns if the depth renderer is ready to render the depth map
  82309. */
  82310. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  82311. var material = subMesh.getMaterial();
  82312. if (material.disableDepthWrite) {
  82313. return false;
  82314. }
  82315. var defines = [];
  82316. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82317. var mesh = subMesh.getMesh();
  82318. // Alpha test
  82319. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  82320. defines.push("#define ALPHATEST");
  82321. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82322. attribs.push(BABYLON.VertexBuffer.UVKind);
  82323. defines.push("#define UV1");
  82324. }
  82325. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  82326. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82327. defines.push("#define UV2");
  82328. }
  82329. }
  82330. // Bones
  82331. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82332. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82333. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82334. if (mesh.numBoneInfluencers > 4) {
  82335. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82336. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82337. }
  82338. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82339. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  82340. }
  82341. else {
  82342. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82343. }
  82344. // Instances
  82345. if (useInstances) {
  82346. defines.push("#define INSTANCES");
  82347. attribs.push("world0");
  82348. attribs.push("world1");
  82349. attribs.push("world2");
  82350. attribs.push("world3");
  82351. }
  82352. // Get correct effect
  82353. var join = defines.join("\n");
  82354. if (this._cachedDefines !== join) {
  82355. this._cachedDefines = join;
  82356. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  82357. }
  82358. return this._effect.isReady();
  82359. };
  82360. /**
  82361. * Gets the texture which the depth map will be written to.
  82362. * @returns The depth map texture
  82363. */
  82364. DepthRenderer.prototype.getDepthMap = function () {
  82365. return this._depthMap;
  82366. };
  82367. /**
  82368. * Disposes of the depth renderer.
  82369. */
  82370. DepthRenderer.prototype.dispose = function () {
  82371. this._depthMap.dispose();
  82372. };
  82373. return DepthRenderer;
  82374. }());
  82375. BABYLON.DepthRenderer = DepthRenderer;
  82376. })(BABYLON || (BABYLON = {}));
  82377. //# sourceMappingURL=babylon.depthRenderer.js.map
  82378. var BABYLON;
  82379. (function (BABYLON) {
  82380. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  82381. camera = camera || this.activeCamera;
  82382. if (!camera) {
  82383. throw "No camera available to enable depth renderer";
  82384. }
  82385. if (!this._depthRenderer) {
  82386. this._depthRenderer = {};
  82387. }
  82388. if (!this._depthRenderer[camera.id]) {
  82389. var textureType = 0;
  82390. if (this.getEngine().getCaps().textureHalfFloatRender) {
  82391. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82392. }
  82393. else if (this.getEngine().getCaps().textureFloatRender) {
  82394. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82395. }
  82396. else {
  82397. throw "Depth renderer does not support int texture type";
  82398. }
  82399. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  82400. }
  82401. return this._depthRenderer[camera.id];
  82402. };
  82403. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  82404. camera = camera || this.activeCamera;
  82405. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  82406. return;
  82407. }
  82408. this._depthRenderer[camera.id].dispose();
  82409. delete this._depthRenderer[camera.id];
  82410. };
  82411. /**
  82412. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  82413. * in several rendering techniques.
  82414. */
  82415. var DepthRendererSceneComponent = /** @class */ (function () {
  82416. /**
  82417. * Creates a new instance of the component for the given scene
  82418. * @param scene Defines the scene to register the component in
  82419. */
  82420. function DepthRendererSceneComponent(scene) {
  82421. /**
  82422. * The component name helpfull to identify the component in the list of scene components.
  82423. */
  82424. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  82425. this.scene = scene;
  82426. }
  82427. /**
  82428. * Registers the component in a given scene
  82429. */
  82430. DepthRendererSceneComponent.prototype.register = function () {
  82431. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  82432. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  82433. };
  82434. /**
  82435. * Rebuilds the elements related to this component in case of
  82436. * context lost for instance.
  82437. */
  82438. DepthRendererSceneComponent.prototype.rebuild = function () {
  82439. // Nothing to do for this component
  82440. };
  82441. /**
  82442. * Disposes the component and the associated ressources
  82443. */
  82444. DepthRendererSceneComponent.prototype.dispose = function () {
  82445. for (var key in this.scene._depthRenderer) {
  82446. this.scene._depthRenderer[key].dispose();
  82447. }
  82448. };
  82449. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  82450. if (this.scene._depthRenderer) {
  82451. for (var key in this.scene._depthRenderer) {
  82452. var depthRenderer = this.scene._depthRenderer[key];
  82453. if (!depthRenderer.useOnlyInActiveCamera) {
  82454. renderTargets.push(depthRenderer.getDepthMap());
  82455. }
  82456. }
  82457. }
  82458. };
  82459. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  82460. if (this.scene._depthRenderer) {
  82461. for (var key in this.scene._depthRenderer) {
  82462. var depthRenderer = this.scene._depthRenderer[key];
  82463. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  82464. renderTargets.push(depthRenderer.getDepthMap());
  82465. }
  82466. }
  82467. }
  82468. };
  82469. return DepthRendererSceneComponent;
  82470. }());
  82471. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  82472. })(BABYLON || (BABYLON = {}));
  82473. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  82474. var BABYLON;
  82475. (function (BABYLON) {
  82476. /**
  82477. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  82478. */
  82479. var GeometryBufferRenderer = /** @class */ (function () {
  82480. /**
  82481. * Creates a new G Buffer for the scene
  82482. * @param scene The scene the buffer belongs to
  82483. * @param ratio How big is the buffer related to the main canvas.
  82484. */
  82485. function GeometryBufferRenderer(scene, ratio) {
  82486. if (ratio === void 0) { ratio = 1; }
  82487. this._enablePosition = false;
  82488. this._scene = scene;
  82489. this._ratio = ratio;
  82490. // Register the G Buffer component to the scene.
  82491. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  82492. if (!component) {
  82493. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  82494. scene._addComponent(component);
  82495. }
  82496. // Render target
  82497. this._createRenderTargets();
  82498. }
  82499. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  82500. /**
  82501. * Set the render list (meshes to be rendered) used in the G buffer.
  82502. */
  82503. set: function (meshes) {
  82504. this._multiRenderTarget.renderList = meshes;
  82505. },
  82506. enumerable: true,
  82507. configurable: true
  82508. });
  82509. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  82510. /**
  82511. * Gets wether or not G buffer are supported by the running hardware.
  82512. * This requires draw buffer supports
  82513. */
  82514. get: function () {
  82515. return this._multiRenderTarget.isSupported;
  82516. },
  82517. enumerable: true,
  82518. configurable: true
  82519. });
  82520. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  82521. /**
  82522. * Gets wether or not position are enabled for the G buffer.
  82523. */
  82524. get: function () {
  82525. return this._enablePosition;
  82526. },
  82527. /**
  82528. * Sets wether or not position are enabled for the G buffer.
  82529. */
  82530. set: function (enable) {
  82531. this._enablePosition = enable;
  82532. this.dispose();
  82533. this._createRenderTargets();
  82534. },
  82535. enumerable: true,
  82536. configurable: true
  82537. });
  82538. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  82539. /**
  82540. * Gets the scene associated with the buffer.
  82541. */
  82542. get: function () {
  82543. return this._scene;
  82544. },
  82545. enumerable: true,
  82546. configurable: true
  82547. });
  82548. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  82549. /**
  82550. * Gets the ratio used by the buffer during its creation.
  82551. * How big is the buffer related to the main canvas.
  82552. */
  82553. get: function () {
  82554. return this._ratio;
  82555. },
  82556. enumerable: true,
  82557. configurable: true
  82558. });
  82559. /**
  82560. * Checks wether everything is ready to render a submesh to the G buffer.
  82561. * @param subMesh the submesh to check readiness for
  82562. * @param useInstances is the mesh drawn using instance or not
  82563. * @returns true if ready otherwise false
  82564. */
  82565. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  82566. var material = subMesh.getMaterial();
  82567. if (material && material.disableDepthWrite) {
  82568. return false;
  82569. }
  82570. var defines = [];
  82571. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  82572. var mesh = subMesh.getMesh();
  82573. // Alpha test
  82574. if (material && material.needAlphaTesting()) {
  82575. defines.push("#define ALPHATEST");
  82576. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82577. attribs.push(BABYLON.VertexBuffer.UVKind);
  82578. defines.push("#define UV1");
  82579. }
  82580. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  82581. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82582. defines.push("#define UV2");
  82583. }
  82584. }
  82585. // Buffers
  82586. if (this._enablePosition) {
  82587. defines.push("#define POSITION");
  82588. }
  82589. // Bones
  82590. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82591. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82592. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82593. if (mesh.numBoneInfluencers > 4) {
  82594. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82595. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82596. }
  82597. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82598. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  82599. }
  82600. else {
  82601. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82602. }
  82603. // Instances
  82604. if (useInstances) {
  82605. defines.push("#define INSTANCES");
  82606. attribs.push("world0");
  82607. attribs.push("world1");
  82608. attribs.push("world2");
  82609. attribs.push("world3");
  82610. }
  82611. // Get correct effect
  82612. var join = defines.join("\n");
  82613. if (this._cachedDefines !== join) {
  82614. this._cachedDefines = join;
  82615. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  82616. }
  82617. return this._effect.isReady();
  82618. };
  82619. /**
  82620. * Gets the current underlying G Buffer.
  82621. * @returns the buffer
  82622. */
  82623. GeometryBufferRenderer.prototype.getGBuffer = function () {
  82624. return this._multiRenderTarget;
  82625. };
  82626. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  82627. /**
  82628. * Gets the number of samples used to render the buffer (anti aliasing).
  82629. */
  82630. get: function () {
  82631. return this._multiRenderTarget.samples;
  82632. },
  82633. /**
  82634. * Sets the number of samples used to render the buffer (anti aliasing).
  82635. */
  82636. set: function (value) {
  82637. this._multiRenderTarget.samples = value;
  82638. },
  82639. enumerable: true,
  82640. configurable: true
  82641. });
  82642. /**
  82643. * Disposes the renderer and frees up associated resources.
  82644. */
  82645. GeometryBufferRenderer.prototype.dispose = function () {
  82646. this.getGBuffer().dispose();
  82647. };
  82648. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  82649. var _this = this;
  82650. var engine = this._scene.getEngine();
  82651. var count = this._enablePosition ? 3 : 2;
  82652. 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 });
  82653. if (!this.isSupported) {
  82654. return;
  82655. }
  82656. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82657. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82658. this._multiRenderTarget.refreshRate = 1;
  82659. this._multiRenderTarget.renderParticles = false;
  82660. this._multiRenderTarget.renderList = null;
  82661. // set default depth value to 1.0 (far away)
  82662. this._multiRenderTarget.onClearObservable.add(function (engine) {
  82663. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  82664. });
  82665. // Custom render function
  82666. var renderSubMesh = function (subMesh) {
  82667. var mesh = subMesh.getRenderingMesh();
  82668. var scene = _this._scene;
  82669. var engine = scene.getEngine();
  82670. var material = subMesh.getMaterial();
  82671. if (!material) {
  82672. return;
  82673. }
  82674. // Culling
  82675. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  82676. // Managing instances
  82677. var batch = mesh._getInstancesRenderList(subMesh._id);
  82678. if (batch.mustReturn) {
  82679. return;
  82680. }
  82681. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  82682. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  82683. engine.enableEffect(_this._effect);
  82684. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  82685. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  82686. _this._effect.setMatrix("view", scene.getViewMatrix());
  82687. // Alpha test
  82688. if (material && material.needAlphaTesting()) {
  82689. var alphaTexture = material.getAlphaTestTexture();
  82690. if (alphaTexture) {
  82691. _this._effect.setTexture("diffuseSampler", alphaTexture);
  82692. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  82693. }
  82694. }
  82695. // Bones
  82696. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82697. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82698. }
  82699. // Draw
  82700. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  82701. }
  82702. };
  82703. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82704. var index;
  82705. if (depthOnlySubMeshes.length) {
  82706. engine.setColorWrite(false);
  82707. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82708. renderSubMesh(depthOnlySubMeshes.data[index]);
  82709. }
  82710. engine.setColorWrite(true);
  82711. }
  82712. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82713. renderSubMesh(opaqueSubMeshes.data[index]);
  82714. }
  82715. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82716. renderSubMesh(alphaTestSubMeshes.data[index]);
  82717. }
  82718. };
  82719. };
  82720. return GeometryBufferRenderer;
  82721. }());
  82722. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  82723. })(BABYLON || (BABYLON = {}));
  82724. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  82725. var BABYLON;
  82726. (function (BABYLON) {
  82727. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  82728. get: function () {
  82729. this._geometryBufferRenderer;
  82730. },
  82731. set: function (value) {
  82732. if (value && value.isSupported) {
  82733. this._geometryBufferRenderer = value;
  82734. }
  82735. ;
  82736. },
  82737. enumerable: true,
  82738. configurable: true
  82739. });
  82740. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  82741. if (ratio === void 0) { ratio = 1; }
  82742. if (this._geometryBufferRenderer) {
  82743. return this._geometryBufferRenderer;
  82744. }
  82745. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  82746. if (!this._geometryBufferRenderer.isSupported) {
  82747. this._geometryBufferRenderer = null;
  82748. }
  82749. return this._geometryBufferRenderer;
  82750. };
  82751. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  82752. if (!this._geometryBufferRenderer) {
  82753. return;
  82754. }
  82755. this._geometryBufferRenderer.dispose();
  82756. this._geometryBufferRenderer = null;
  82757. };
  82758. /**
  82759. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  82760. * in several rendering techniques.
  82761. */
  82762. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  82763. /**
  82764. * Creates a new instance of the component for the given scene
  82765. * @param scene Defines the scene to register the component in
  82766. */
  82767. function GeometryBufferRendererSceneComponent(scene) {
  82768. /**
  82769. * The component name helpful to identify the component in the list of scene components.
  82770. */
  82771. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  82772. this.scene = scene;
  82773. }
  82774. /**
  82775. * Registers the component in a given scene
  82776. */
  82777. GeometryBufferRendererSceneComponent.prototype.register = function () {
  82778. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  82779. };
  82780. /**
  82781. * Rebuilds the elements related to this component in case of
  82782. * context lost for instance.
  82783. */
  82784. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  82785. // Nothing to do for this component
  82786. };
  82787. /**
  82788. * Disposes the component and the associated ressources
  82789. */
  82790. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  82791. // Nothing to do for this component
  82792. };
  82793. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  82794. if (this.scene._geometryBufferRenderer) {
  82795. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  82796. }
  82797. };
  82798. return GeometryBufferRendererSceneComponent;
  82799. }());
  82800. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  82801. })(BABYLON || (BABYLON = {}));
  82802. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  82803. var BABYLON;
  82804. (function (BABYLON) {
  82805. var SSAORenderingPipeline = /** @class */ (function (_super) {
  82806. __extends(SSAORenderingPipeline, _super);
  82807. /**
  82808. * @constructor
  82809. * @param {string} name - The rendering pipeline name
  82810. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  82811. * @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 }
  82812. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  82813. */
  82814. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  82815. var _this = _super.call(this, scene.getEngine(), name) || this;
  82816. // Members
  82817. /**
  82818. * The PassPostProcess id in the pipeline that contains the original scene color
  82819. */
  82820. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  82821. /**
  82822. * The SSAO PostProcess id in the pipeline
  82823. */
  82824. _this.SSAORenderEffect = "SSAORenderEffect";
  82825. /**
  82826. * The horizontal blur PostProcess id in the pipeline
  82827. */
  82828. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  82829. /**
  82830. * The vertical blur PostProcess id in the pipeline
  82831. */
  82832. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  82833. /**
  82834. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  82835. */
  82836. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  82837. /**
  82838. * The output strength of the SSAO post-process. Default value is 1.0.
  82839. */
  82840. _this.totalStrength = 1.0;
  82841. /**
  82842. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  82843. */
  82844. _this.radius = 0.0001;
  82845. /**
  82846. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  82847. * Must not be equal to fallOff and superior to fallOff.
  82848. * Default value is 0.975
  82849. */
  82850. _this.area = 0.0075;
  82851. /**
  82852. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  82853. * Must not be equal to area and inferior to area.
  82854. * Default value is 0.0
  82855. */
  82856. _this.fallOff = 0.000001;
  82857. /**
  82858. * The base color of the SSAO post-process
  82859. * The final result is "base + ssao" between [0, 1]
  82860. */
  82861. _this.base = 0.5;
  82862. _this._firstUpdate = true;
  82863. _this._scene = scene;
  82864. // Set up assets
  82865. _this._createRandomTexture();
  82866. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  82867. var ssaoRatio = ratio.ssaoRatio || ratio;
  82868. var combineRatio = ratio.combineRatio || ratio;
  82869. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  82870. _this._createSSAOPostProcess(ssaoRatio);
  82871. _this._createBlurPostProcess(ssaoRatio);
  82872. _this._createSSAOCombinePostProcess(combineRatio);
  82873. // Set up pipeline
  82874. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  82875. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  82876. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  82877. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  82878. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  82879. // Finish
  82880. scene.postProcessRenderPipelineManager.addPipeline(_this);
  82881. if (cameras)
  82882. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  82883. return _this;
  82884. }
  82885. // Public Methods
  82886. /**
  82887. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  82888. */
  82889. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  82890. if (disableDepthRender === void 0) { disableDepthRender = false; }
  82891. for (var i = 0; i < this._scene.cameras.length; i++) {
  82892. var camera = this._scene.cameras[i];
  82893. this._originalColorPostProcess.dispose(camera);
  82894. this._ssaoPostProcess.dispose(camera);
  82895. this._blurHPostProcess.dispose(camera);
  82896. this._blurVPostProcess.dispose(camera);
  82897. this._ssaoCombinePostProcess.dispose(camera);
  82898. }
  82899. this._randomTexture.dispose();
  82900. if (disableDepthRender)
  82901. this._scene.disableDepthRenderer();
  82902. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  82903. _super.prototype.dispose.call(this);
  82904. };
  82905. // Private Methods
  82906. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  82907. var _this = this;
  82908. var size = 16;
  82909. 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);
  82910. 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);
  82911. this._blurHPostProcess.onActivateObservable.add(function () {
  82912. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  82913. _this._blurHPostProcess.kernel = size * dw;
  82914. });
  82915. this._blurVPostProcess.onActivateObservable.add(function () {
  82916. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  82917. _this._blurVPostProcess.kernel = size * dw;
  82918. });
  82919. };
  82920. /** @hidden */
  82921. SSAORenderingPipeline.prototype._rebuild = function () {
  82922. this._firstUpdate = true;
  82923. _super.prototype._rebuild.call(this);
  82924. };
  82925. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  82926. var _this = this;
  82927. var numSamples = 16;
  82928. var sampleSphere = [
  82929. 0.5381, 0.1856, -0.4319,
  82930. 0.1379, 0.2486, 0.4430,
  82931. 0.3371, 0.5679, -0.0057,
  82932. -0.6999, -0.0451, -0.0019,
  82933. 0.0689, -0.1598, -0.8547,
  82934. 0.0560, 0.0069, -0.1843,
  82935. -0.0146, 0.1402, 0.0762,
  82936. 0.0100, -0.1924, -0.0344,
  82937. -0.3577, -0.5301, -0.4358,
  82938. -0.3169, 0.1063, 0.0158,
  82939. 0.0103, -0.5869, 0.0046,
  82940. -0.0897, -0.4940, 0.3287,
  82941. 0.7119, -0.0154, -0.0918,
  82942. -0.0533, 0.0596, -0.5411,
  82943. 0.0352, -0.0631, 0.5460,
  82944. -0.4776, 0.2847, -0.0271
  82945. ];
  82946. var samplesFactor = 1.0 / numSamples;
  82947. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  82948. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  82949. "area", "fallOff", "base", "range", "viewport"
  82950. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  82951. this._ssaoPostProcess.onApply = function (effect) {
  82952. if (_this._firstUpdate) {
  82953. effect.setArray3("sampleSphere", sampleSphere);
  82954. effect.setFloat("samplesFactor", samplesFactor);
  82955. effect.setFloat("randTextureTiles", 4.0);
  82956. }
  82957. effect.setFloat("totalStrength", _this.totalStrength);
  82958. effect.setFloat("radius", _this.radius);
  82959. effect.setFloat("area", _this.area);
  82960. effect.setFloat("fallOff", _this.fallOff);
  82961. effect.setFloat("base", _this.base);
  82962. effect.setTexture("textureSampler", _this._depthTexture);
  82963. effect.setTexture("randomSampler", _this._randomTexture);
  82964. };
  82965. };
  82966. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  82967. var _this = this;
  82968. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  82969. this._ssaoCombinePostProcess.onApply = function (effect) {
  82970. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  82971. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  82972. };
  82973. };
  82974. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  82975. var size = 512;
  82976. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  82977. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  82978. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  82979. var context = this._randomTexture.getContext();
  82980. var rand = function (min, max) {
  82981. return Math.random() * (max - min) + min;
  82982. };
  82983. var randVector = BABYLON.Vector3.Zero();
  82984. for (var x = 0; x < size; x++) {
  82985. for (var y = 0; y < size; y++) {
  82986. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  82987. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  82988. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  82989. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  82990. context.fillRect(x, y, 1, 1);
  82991. }
  82992. }
  82993. this._randomTexture.update(false);
  82994. };
  82995. __decorate([
  82996. BABYLON.serialize()
  82997. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  82998. __decorate([
  82999. BABYLON.serialize()
  83000. ], SSAORenderingPipeline.prototype, "radius", void 0);
  83001. __decorate([
  83002. BABYLON.serialize()
  83003. ], SSAORenderingPipeline.prototype, "area", void 0);
  83004. __decorate([
  83005. BABYLON.serialize()
  83006. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  83007. __decorate([
  83008. BABYLON.serialize()
  83009. ], SSAORenderingPipeline.prototype, "base", void 0);
  83010. return SSAORenderingPipeline;
  83011. }(BABYLON.PostProcessRenderPipeline));
  83012. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  83013. })(BABYLON || (BABYLON = {}));
  83014. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  83015. var BABYLON;
  83016. (function (BABYLON) {
  83017. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  83018. __extends(SSAO2RenderingPipeline, _super);
  83019. /**
  83020. * @constructor
  83021. * @param {string} name - The rendering pipeline name
  83022. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  83023. * @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 }
  83024. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  83025. */
  83026. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  83027. var _this = _super.call(this, scene.getEngine(), name) || this;
  83028. // Members
  83029. /**
  83030. * The PassPostProcess id in the pipeline that contains the original scene color
  83031. */
  83032. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  83033. /**
  83034. * The SSAO PostProcess id in the pipeline
  83035. */
  83036. _this.SSAORenderEffect = "SSAORenderEffect";
  83037. /**
  83038. * The horizontal blur PostProcess id in the pipeline
  83039. */
  83040. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  83041. /**
  83042. * The vertical blur PostProcess id in the pipeline
  83043. */
  83044. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  83045. /**
  83046. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  83047. */
  83048. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  83049. /**
  83050. * The output strength of the SSAO post-process. Default value is 1.0.
  83051. */
  83052. _this.totalStrength = 1.0;
  83053. /**
  83054. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  83055. */
  83056. _this.maxZ = 100.0;
  83057. /**
  83058. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  83059. */
  83060. _this.minZAspect = 0.2;
  83061. _this._samples = 8;
  83062. _this._textureSamples = 1;
  83063. /**
  83064. * Are we using bilateral blur ?
  83065. */
  83066. _this._expensiveBlur = true;
  83067. /**
  83068. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  83069. */
  83070. _this.radius = 2.0;
  83071. /**
  83072. * The base color of the SSAO post-process
  83073. * The final result is "base + ssao" between [0, 1]
  83074. */
  83075. _this.base = 0;
  83076. _this._firstUpdate = true;
  83077. _this._bits = new Uint32Array(1);
  83078. _this._scene = scene;
  83079. _this._ratio = ratio;
  83080. if (!_this.isSupported) {
  83081. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  83082. return _this;
  83083. }
  83084. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  83085. var blurRatio = _this._ratio.blurRatio || ratio;
  83086. // Set up assets
  83087. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  83088. _this._createRandomTexture();
  83089. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  83090. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  83091. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  83092. _this._originalColorPostProcess.samples = _this.textureSamples;
  83093. _this._createSSAOPostProcess(1.0);
  83094. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  83095. _this._createSSAOCombinePostProcess(blurRatio);
  83096. // Set up pipeline
  83097. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  83098. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  83099. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  83100. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  83101. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  83102. // Finish
  83103. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83104. if (cameras)
  83105. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  83106. return _this;
  83107. }
  83108. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  83109. get: function () {
  83110. return this._samples;
  83111. },
  83112. /**
  83113. * Number of samples used for the SSAO calculations. Default value is 8
  83114. */
  83115. set: function (n) {
  83116. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  83117. this._samples = n;
  83118. this._sampleSphere = this._generateHemisphere();
  83119. this._firstUpdate = true;
  83120. },
  83121. enumerable: true,
  83122. configurable: true
  83123. });
  83124. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  83125. get: function () {
  83126. return this._textureSamples;
  83127. },
  83128. /**
  83129. * Number of samples to use for antialiasing
  83130. */
  83131. set: function (n) {
  83132. this._textureSamples = n;
  83133. this._originalColorPostProcess.samples = n;
  83134. this._blurHPostProcess.samples = n;
  83135. this._blurVPostProcess.samples = n;
  83136. this._ssaoPostProcess.samples = n;
  83137. this._ssaoCombinePostProcess.samples = n;
  83138. },
  83139. enumerable: true,
  83140. configurable: true
  83141. });
  83142. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  83143. get: function () {
  83144. return this._expensiveBlur;
  83145. },
  83146. set: function (b) {
  83147. 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"]);
  83148. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  83149. this._expensiveBlur = b;
  83150. this._firstUpdate = true;
  83151. },
  83152. enumerable: true,
  83153. configurable: true
  83154. });
  83155. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  83156. /**
  83157. * Support test.
  83158. */
  83159. get: function () {
  83160. var engine = BABYLON.Engine.LastCreatedEngine;
  83161. if (!engine) {
  83162. return false;
  83163. }
  83164. return engine.getCaps().drawBuffersExtension;
  83165. },
  83166. enumerable: true,
  83167. configurable: true
  83168. });
  83169. // Public Methods
  83170. /**
  83171. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  83172. */
  83173. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  83174. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  83175. for (var i = 0; i < this._scene.cameras.length; i++) {
  83176. var camera = this._scene.cameras[i];
  83177. this._originalColorPostProcess.dispose(camera);
  83178. this._ssaoPostProcess.dispose(camera);
  83179. this._blurHPostProcess.dispose(camera);
  83180. this._blurVPostProcess.dispose(camera);
  83181. this._ssaoCombinePostProcess.dispose(camera);
  83182. }
  83183. this._randomTexture.dispose();
  83184. if (disableGeometryBufferRenderer)
  83185. this._scene.disableGeometryBufferRenderer();
  83186. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  83187. _super.prototype.dispose.call(this);
  83188. };
  83189. // Private Methods
  83190. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  83191. var _this = this;
  83192. this._samplerOffsets = [];
  83193. var expensive = this.expensiveBlur;
  83194. for (var i = -8; i < 8; i++) {
  83195. this._samplerOffsets.push(i * 2 + 0.5);
  83196. }
  83197. 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");
  83198. this._blurHPostProcess.onApply = function (effect) {
  83199. if (!_this._scene.activeCamera) {
  83200. return;
  83201. }
  83202. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  83203. effect.setFloat("near", _this._scene.activeCamera.minZ);
  83204. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  83205. effect.setFloat("radius", _this.radius);
  83206. effect.setTexture("depthSampler", _this._depthTexture);
  83207. if (_this._firstUpdate) {
  83208. effect.setArray("samplerOffsets", _this._samplerOffsets);
  83209. }
  83210. };
  83211. 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");
  83212. this._blurVPostProcess.onApply = function (effect) {
  83213. if (!_this._scene.activeCamera) {
  83214. return;
  83215. }
  83216. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  83217. effect.setFloat("near", _this._scene.activeCamera.minZ);
  83218. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  83219. effect.setFloat("radius", _this.radius);
  83220. effect.setTexture("depthSampler", _this._depthTexture);
  83221. if (_this._firstUpdate) {
  83222. effect.setArray("samplerOffsets", _this._samplerOffsets);
  83223. _this._firstUpdate = false;
  83224. }
  83225. };
  83226. this._blurHPostProcess.samples = this.textureSamples;
  83227. this._blurVPostProcess.samples = this.textureSamples;
  83228. };
  83229. /** @hidden */
  83230. SSAO2RenderingPipeline.prototype._rebuild = function () {
  83231. this._firstUpdate = true;
  83232. _super.prototype._rebuild.call(this);
  83233. };
  83234. //Van der Corput radical inverse
  83235. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  83236. this._bits[0] = i;
  83237. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  83238. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  83239. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  83240. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  83241. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  83242. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  83243. };
  83244. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  83245. return [i / n, this._radicalInverse_VdC(i)];
  83246. };
  83247. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  83248. var phi = v * 2.0 * Math.PI;
  83249. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  83250. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  83251. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  83252. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  83253. };
  83254. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  83255. var numSamples = this.samples;
  83256. var result = [];
  83257. var vector;
  83258. var i = 0;
  83259. while (i < numSamples) {
  83260. if (numSamples < 16) {
  83261. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  83262. }
  83263. else {
  83264. var rand = this._hammersley(i, numSamples);
  83265. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  83266. }
  83267. result.push(vector.x, vector.y, vector.z);
  83268. i++;
  83269. }
  83270. return result;
  83271. };
  83272. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  83273. var _this = this;
  83274. var numSamples = this.samples;
  83275. this._sampleSphere = this._generateHemisphere();
  83276. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  83277. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  83278. "base", "range", "projection", "near", "far", "texelSize",
  83279. "xViewport", "yViewport", "maxZ", "minZAspect"
  83280. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  83281. this._ssaoPostProcess.onApply = function (effect) {
  83282. if (_this._firstUpdate) {
  83283. effect.setArray3("sampleSphere", _this._sampleSphere);
  83284. effect.setFloat("randTextureTiles", 32.0);
  83285. }
  83286. if (!_this._scene.activeCamera) {
  83287. return;
  83288. }
  83289. effect.setFloat("samplesFactor", 1 / _this.samples);
  83290. effect.setFloat("totalStrength", _this.totalStrength);
  83291. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  83292. effect.setFloat("radius", _this.radius);
  83293. effect.setFloat("maxZ", _this.maxZ);
  83294. effect.setFloat("minZAspect", _this.minZAspect);
  83295. effect.setFloat("base", _this.base);
  83296. effect.setFloat("near", _this._scene.activeCamera.minZ);
  83297. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  83298. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  83299. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  83300. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  83301. effect.setTexture("textureSampler", _this._depthTexture);
  83302. effect.setTexture("normalSampler", _this._normalTexture);
  83303. effect.setTexture("randomSampler", _this._randomTexture);
  83304. };
  83305. this._ssaoPostProcess.samples = this.textureSamples;
  83306. };
  83307. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  83308. var _this = this;
  83309. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  83310. this._ssaoCombinePostProcess.onApply = function (effect) {
  83311. var viewport = _this._scene.activeCamera.viewport;
  83312. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  83313. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  83314. };
  83315. this._ssaoCombinePostProcess.samples = this.textureSamples;
  83316. };
  83317. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  83318. var size = 128;
  83319. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  83320. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  83321. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  83322. var context = this._randomTexture.getContext();
  83323. var rand = function (min, max) {
  83324. return Math.random() * (max - min) + min;
  83325. };
  83326. var randVector = BABYLON.Vector3.Zero();
  83327. for (var x = 0; x < size; x++) {
  83328. for (var y = 0; y < size; y++) {
  83329. randVector.x = rand(0.0, 1.0);
  83330. randVector.y = rand(0.0, 1.0);
  83331. randVector.z = 0.0;
  83332. randVector.normalize();
  83333. randVector.scaleInPlace(255);
  83334. randVector.x = Math.floor(randVector.x);
  83335. randVector.y = Math.floor(randVector.y);
  83336. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  83337. context.fillRect(x, y, 1, 1);
  83338. }
  83339. }
  83340. this._randomTexture.update(false);
  83341. };
  83342. /**
  83343. * Serialize the rendering pipeline (Used when exporting)
  83344. * @returns the serialized object
  83345. */
  83346. SSAO2RenderingPipeline.prototype.serialize = function () {
  83347. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  83348. serializationObject.customType = "SSAO2RenderingPipeline";
  83349. return serializationObject;
  83350. };
  83351. /**
  83352. * Parse the serialized pipeline
  83353. * @param source Source pipeline.
  83354. * @param scene The scene to load the pipeline to.
  83355. * @param rootUrl The URL of the serialized pipeline.
  83356. * @returns An instantiated pipeline from the serialized object.
  83357. */
  83358. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  83359. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  83360. };
  83361. __decorate([
  83362. BABYLON.serialize()
  83363. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  83364. __decorate([
  83365. BABYLON.serialize()
  83366. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  83367. __decorate([
  83368. BABYLON.serialize()
  83369. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  83370. __decorate([
  83371. BABYLON.serialize("samples")
  83372. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  83373. __decorate([
  83374. BABYLON.serialize("textureSamples")
  83375. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  83376. __decorate([
  83377. BABYLON.serialize()
  83378. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  83379. __decorate([
  83380. BABYLON.serialize("expensiveBlur")
  83381. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  83382. __decorate([
  83383. BABYLON.serialize()
  83384. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  83385. __decorate([
  83386. BABYLON.serialize()
  83387. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  83388. return SSAO2RenderingPipeline;
  83389. }(BABYLON.PostProcessRenderPipeline));
  83390. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  83391. })(BABYLON || (BABYLON = {}));
  83392. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  83393. // BABYLON.JS Chromatic Aberration GLSL Shader
  83394. // Author: Olivier Guyot
  83395. // Separates very slightly R, G and B colors on the edges of the screen
  83396. // Inspired by Francois Tarlier & Martins Upitis
  83397. var BABYLON;
  83398. (function (BABYLON) {
  83399. var LensRenderingPipeline = /** @class */ (function (_super) {
  83400. __extends(LensRenderingPipeline, _super);
  83401. /**
  83402. * @constructor
  83403. *
  83404. * Effect parameters are as follow:
  83405. * {
  83406. * chromatic_aberration: number; // from 0 to x (1 for realism)
  83407. * edge_blur: number; // from 0 to x (1 for realism)
  83408. * distortion: number; // from 0 to x (1 for realism)
  83409. * grain_amount: number; // from 0 to 1
  83410. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  83411. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  83412. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  83413. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  83414. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  83415. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  83416. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  83417. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  83418. * }
  83419. * Note: if an effect parameter is unset, effect is disabled
  83420. *
  83421. * @param {string} name - The rendering pipeline name
  83422. * @param {object} parameters - An object containing all parameters (see above)
  83423. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  83424. * @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)
  83425. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  83426. */
  83427. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  83428. if (ratio === void 0) { ratio = 1.0; }
  83429. var _this = _super.call(this, scene.getEngine(), name) || this;
  83430. // Lens effects can be of the following:
  83431. // - chromatic aberration (slight shift of RGB colors)
  83432. // - blur on the edge of the lens
  83433. // - lens distortion
  83434. // - depth-of-field blur & highlights enhancing
  83435. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  83436. // - grain effect (noise or custom texture)
  83437. // Two additional texture samplers are needed:
  83438. // - depth map (for depth-of-field)
  83439. // - grain texture
  83440. /**
  83441. * The chromatic aberration PostProcess id in the pipeline
  83442. */
  83443. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  83444. /**
  83445. * The highlights enhancing PostProcess id in the pipeline
  83446. */
  83447. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  83448. /**
  83449. * The depth-of-field PostProcess id in the pipeline
  83450. */
  83451. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  83452. _this._scene = scene;
  83453. // Fetch texture samplers
  83454. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  83455. if (parameters.grain_texture) {
  83456. _this._grainTexture = parameters.grain_texture;
  83457. }
  83458. else {
  83459. _this._createGrainTexture();
  83460. }
  83461. // save parameters
  83462. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  83463. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  83464. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  83465. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  83466. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  83467. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  83468. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  83469. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  83470. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  83471. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  83472. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  83473. // Create effects
  83474. _this._createChromaticAberrationPostProcess(ratio);
  83475. _this._createHighlightsPostProcess(ratio);
  83476. _this._createDepthOfFieldPostProcess(ratio / 4);
  83477. // Set up pipeline
  83478. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  83479. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  83480. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  83481. if (_this._highlightsGain === -1) {
  83482. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  83483. }
  83484. // Finish
  83485. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83486. if (cameras) {
  83487. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  83488. }
  83489. return _this;
  83490. }
  83491. // public methods (self explanatory)
  83492. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  83493. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  83494. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  83495. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  83496. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  83497. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  83498. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  83499. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  83500. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  83501. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  83502. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  83503. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  83504. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  83505. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  83506. };
  83507. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  83508. this._highlightsPostProcess.updateEffect();
  83509. };
  83510. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  83511. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  83512. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  83513. this._highlightsGain = amount;
  83514. };
  83515. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  83516. if (this._highlightsGain === -1) {
  83517. this._highlightsGain = 1.0;
  83518. }
  83519. this._highlightsThreshold = amount;
  83520. };
  83521. LensRenderingPipeline.prototype.disableHighlights = function () {
  83522. this._highlightsGain = -1;
  83523. };
  83524. /**
  83525. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  83526. */
  83527. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  83528. if (disableDepthRender === void 0) { disableDepthRender = false; }
  83529. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  83530. this._chromaticAberrationPostProcess = null;
  83531. this._highlightsPostProcess = null;
  83532. this._depthOfFieldPostProcess = null;
  83533. this._grainTexture.dispose();
  83534. if (disableDepthRender)
  83535. this._scene.disableDepthRenderer();
  83536. };
  83537. // colors shifting and distortion
  83538. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  83539. var _this = this;
  83540. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  83541. [], // samplers
  83542. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  83543. this._chromaticAberrationPostProcess.onApply = function (effect) {
  83544. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  83545. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  83546. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  83547. effect.setFloat('radialIntensity', 1);
  83548. effect.setFloat2('direction', 17, 17);
  83549. effect.setFloat2('centerPosition', 0.5, 0.5);
  83550. };
  83551. };
  83552. // highlights enhancing
  83553. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  83554. var _this = this;
  83555. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  83556. [], // samplers
  83557. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  83558. this._highlightsPostProcess.onApply = function (effect) {
  83559. effect.setFloat('gain', _this._highlightsGain);
  83560. effect.setFloat('threshold', _this._highlightsThreshold);
  83561. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  83562. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  83563. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  83564. };
  83565. };
  83566. // colors shifting and distortion
  83567. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  83568. var _this = this;
  83569. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  83570. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  83571. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  83572. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  83573. this._depthOfFieldPostProcess.onApply = function (effect) {
  83574. effect.setTexture("depthSampler", _this._depthTexture);
  83575. effect.setTexture("grainSampler", _this._grainTexture);
  83576. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  83577. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  83578. effect.setFloat('grain_amount', _this._grainAmount);
  83579. effect.setBool('blur_noise', _this._blurNoise);
  83580. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  83581. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  83582. effect.setFloat('distortion', _this._distortion);
  83583. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  83584. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  83585. effect.setFloat('aperture', _this._dofAperture);
  83586. effect.setFloat('darken', _this._dofDarken);
  83587. effect.setFloat('edge_blur', _this._edgeBlur);
  83588. effect.setBool('highlights', (_this._highlightsGain !== -1));
  83589. if (_this._scene.activeCamera) {
  83590. effect.setFloat('near', _this._scene.activeCamera.minZ);
  83591. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  83592. }
  83593. };
  83594. };
  83595. // creates a black and white random noise texture, 512x512
  83596. LensRenderingPipeline.prototype._createGrainTexture = function () {
  83597. var size = 512;
  83598. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83599. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  83600. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  83601. var context = this._grainTexture.getContext();
  83602. var rand = function (min, max) {
  83603. return Math.random() * (max - min) + min;
  83604. };
  83605. var value;
  83606. for (var x = 0; x < size; x++) {
  83607. for (var y = 0; y < size; y++) {
  83608. value = Math.floor(rand(0.42, 0.58) * 255);
  83609. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  83610. context.fillRect(x, y, 1, 1);
  83611. }
  83612. }
  83613. this._grainTexture.update(false);
  83614. };
  83615. return LensRenderingPipeline;
  83616. }(BABYLON.PostProcessRenderPipeline));
  83617. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  83618. })(BABYLON || (BABYLON = {}));
  83619. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  83620. var BABYLON;
  83621. (function (BABYLON) {
  83622. /**
  83623. * Standard rendering pipeline
  83624. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  83625. * @see https://doc.babylonjs.com/how_to/using_standard_rendering_pipeline
  83626. */
  83627. var StandardRenderingPipeline = /** @class */ (function (_super) {
  83628. __extends(StandardRenderingPipeline, _super);
  83629. /**
  83630. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  83631. * @constructor
  83632. * @param {string} name - The rendering pipeline name
  83633. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  83634. * @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)
  83635. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  83636. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  83637. */
  83638. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  83639. if (originalPostProcess === void 0) { originalPostProcess = null; }
  83640. var _this = _super.call(this, scene.getEngine(), name) || this;
  83641. /**
  83642. * Post-process used to down scale an image x4
  83643. */
  83644. _this.downSampleX4PostProcess = null;
  83645. /**
  83646. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  83647. */
  83648. _this.brightPassPostProcess = null;
  83649. /**
  83650. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  83651. */
  83652. _this.blurHPostProcesses = [];
  83653. /**
  83654. * Post-process array storing all the vertical blur post-processes used by the pipeline
  83655. */
  83656. _this.blurVPostProcesses = [];
  83657. /**
  83658. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  83659. */
  83660. _this.textureAdderPostProcess = null;
  83661. /**
  83662. * Post-process used to create volumetric lighting effect
  83663. */
  83664. _this.volumetricLightPostProcess = null;
  83665. /**
  83666. * Post-process used to smooth the previous volumetric light post-process on the X axis
  83667. */
  83668. _this.volumetricLightSmoothXPostProcess = null;
  83669. /**
  83670. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  83671. */
  83672. _this.volumetricLightSmoothYPostProcess = null;
  83673. /**
  83674. * Post-process used to merge the volumetric light effect and the real scene color
  83675. */
  83676. _this.volumetricLightMergePostProces = null;
  83677. /**
  83678. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  83679. */
  83680. _this.volumetricLightFinalPostProcess = null;
  83681. /**
  83682. * Base post-process used to calculate the average luminance of the final image for HDR
  83683. */
  83684. _this.luminancePostProcess = null;
  83685. /**
  83686. * Post-processes used to create down sample post-processes in order to get
  83687. * the average luminance of the final image for HDR
  83688. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  83689. */
  83690. _this.luminanceDownSamplePostProcesses = [];
  83691. /**
  83692. * Post-process used to create a HDR effect (light adaptation)
  83693. */
  83694. _this.hdrPostProcess = null;
  83695. /**
  83696. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  83697. */
  83698. _this.textureAdderFinalPostProcess = null;
  83699. /**
  83700. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  83701. */
  83702. _this.lensFlareFinalPostProcess = null;
  83703. /**
  83704. * Post-process used to merge the final HDR post-process and the real scene color
  83705. */
  83706. _this.hdrFinalPostProcess = null;
  83707. /**
  83708. * Post-process used to create a lens flare effect
  83709. */
  83710. _this.lensFlarePostProcess = null;
  83711. /**
  83712. * Post-process that merges the result of the lens flare post-process and the real scene color
  83713. */
  83714. _this.lensFlareComposePostProcess = null;
  83715. /**
  83716. * Post-process used to create a motion blur effect
  83717. */
  83718. _this.motionBlurPostProcess = null;
  83719. /**
  83720. * Post-process used to create a depth of field effect
  83721. */
  83722. _this.depthOfFieldPostProcess = null;
  83723. /**
  83724. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  83725. */
  83726. _this.fxaaPostProcess = null;
  83727. // Values
  83728. /**
  83729. * Represents the brightness threshold in order to configure the illuminated surfaces
  83730. */
  83731. _this.brightThreshold = 1.0;
  83732. /**
  83733. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  83734. */
  83735. _this.blurWidth = 512.0;
  83736. /**
  83737. * Sets if the blur for highlighted surfaces must be only horizontal
  83738. */
  83739. _this.horizontalBlur = false;
  83740. /**
  83741. * Sets the overall exposure used by the pipeline
  83742. */
  83743. _this.exposure = 1.0;
  83744. /**
  83745. * Texture used typically to simulate "dirty" on camera lens
  83746. */
  83747. _this.lensTexture = null;
  83748. /**
  83749. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  83750. */
  83751. _this.volumetricLightCoefficient = 0.2;
  83752. /**
  83753. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  83754. */
  83755. _this.volumetricLightPower = 4.0;
  83756. /**
  83757. * Used the set the blur intensity to smooth the volumetric lights
  83758. */
  83759. _this.volumetricLightBlurScale = 64.0;
  83760. /**
  83761. * Light (spot or directional) used to generate the volumetric lights rays
  83762. * The source light must have a shadow generate so the pipeline can get its
  83763. * depth map
  83764. */
  83765. _this.sourceLight = null;
  83766. /**
  83767. * For eye adaptation, represents the minimum luminance the eye can see
  83768. */
  83769. _this.hdrMinimumLuminance = 1.0;
  83770. /**
  83771. * For eye adaptation, represents the decrease luminance speed
  83772. */
  83773. _this.hdrDecreaseRate = 0.5;
  83774. /**
  83775. * For eye adaptation, represents the increase luminance speed
  83776. */
  83777. _this.hdrIncreaseRate = 0.5;
  83778. /**
  83779. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  83780. */
  83781. _this.lensColorTexture = null;
  83782. /**
  83783. * The overall strengh for the lens flare effect
  83784. */
  83785. _this.lensFlareStrength = 20.0;
  83786. /**
  83787. * Dispersion coefficient for lens flare ghosts
  83788. */
  83789. _this.lensFlareGhostDispersal = 1.4;
  83790. /**
  83791. * Main lens flare halo width
  83792. */
  83793. _this.lensFlareHaloWidth = 0.7;
  83794. /**
  83795. * Based on the lens distortion effect, defines how much the lens flare result
  83796. * is distorted
  83797. */
  83798. _this.lensFlareDistortionStrength = 16.0;
  83799. /**
  83800. * Lens star texture must be used to simulate rays on the flares and is available
  83801. * in the documentation
  83802. */
  83803. _this.lensStarTexture = null;
  83804. /**
  83805. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  83806. * flare effect by taking account of the dirt texture
  83807. */
  83808. _this.lensFlareDirtTexture = null;
  83809. /**
  83810. * Represents the focal length for the depth of field effect
  83811. */
  83812. _this.depthOfFieldDistance = 10.0;
  83813. /**
  83814. * Represents the blur intensity for the blurred part of the depth of field effect
  83815. */
  83816. _this.depthOfFieldBlurWidth = 64.0;
  83817. /**
  83818. * For motion blur, defines how much the image is blurred by the movement
  83819. */
  83820. _this.motionStrength = 1.0;
  83821. /**
  83822. * List of animations for the pipeline (IAnimatable implementation)
  83823. */
  83824. _this.animations = [];
  83825. _this._currentDepthOfFieldSource = null;
  83826. _this._hdrCurrentLuminance = 1.0;
  83827. // Getters and setters
  83828. _this._bloomEnabled = false;
  83829. _this._depthOfFieldEnabled = false;
  83830. _this._vlsEnabled = false;
  83831. _this._lensFlareEnabled = false;
  83832. _this._hdrEnabled = false;
  83833. _this._motionBlurEnabled = false;
  83834. _this._fxaaEnabled = false;
  83835. _this._motionBlurSamples = 64.0;
  83836. _this._volumetricLightStepsCount = 50.0;
  83837. _this._samples = 1;
  83838. _this._cameras = cameras || [];
  83839. // Initialize
  83840. _this._scene = scene;
  83841. _this._basePostProcess = originalPostProcess;
  83842. _this._ratio = ratio;
  83843. // Misc
  83844. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83845. // Finish
  83846. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83847. _this._buildPipeline();
  83848. return _this;
  83849. }
  83850. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  83851. /**
  83852. * Specifies if the bloom pipeline is enabled
  83853. */
  83854. get: function () {
  83855. return this._bloomEnabled;
  83856. },
  83857. set: function (enabled) {
  83858. if (this._bloomEnabled === enabled) {
  83859. return;
  83860. }
  83861. this._bloomEnabled = enabled;
  83862. this._buildPipeline();
  83863. },
  83864. enumerable: true,
  83865. configurable: true
  83866. });
  83867. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  83868. /**
  83869. * Specifies if the depth of field pipeline is enabed
  83870. */
  83871. get: function () {
  83872. return this._depthOfFieldEnabled;
  83873. },
  83874. set: function (enabled) {
  83875. if (this._depthOfFieldEnabled === enabled) {
  83876. return;
  83877. }
  83878. this._depthOfFieldEnabled = enabled;
  83879. this._buildPipeline();
  83880. },
  83881. enumerable: true,
  83882. configurable: true
  83883. });
  83884. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  83885. /**
  83886. * Specifies if the lens flare pipeline is enabed
  83887. */
  83888. get: function () {
  83889. return this._lensFlareEnabled;
  83890. },
  83891. set: function (enabled) {
  83892. if (this._lensFlareEnabled === enabled) {
  83893. return;
  83894. }
  83895. this._lensFlareEnabled = enabled;
  83896. this._buildPipeline();
  83897. },
  83898. enumerable: true,
  83899. configurable: true
  83900. });
  83901. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  83902. /**
  83903. * Specifies if the HDR pipeline is enabled
  83904. */
  83905. get: function () {
  83906. return this._hdrEnabled;
  83907. },
  83908. set: function (enabled) {
  83909. if (this._hdrEnabled === enabled) {
  83910. return;
  83911. }
  83912. this._hdrEnabled = enabled;
  83913. this._buildPipeline();
  83914. },
  83915. enumerable: true,
  83916. configurable: true
  83917. });
  83918. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  83919. /**
  83920. * Specifies if the volumetric lights scattering effect is enabled
  83921. */
  83922. get: function () {
  83923. return this._vlsEnabled;
  83924. },
  83925. set: function (enabled) {
  83926. if (this._vlsEnabled === enabled) {
  83927. return;
  83928. }
  83929. if (enabled) {
  83930. var geometry = this._scene.enableGeometryBufferRenderer();
  83931. if (!geometry) {
  83932. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  83933. return;
  83934. }
  83935. }
  83936. this._vlsEnabled = enabled;
  83937. this._buildPipeline();
  83938. },
  83939. enumerable: true,
  83940. configurable: true
  83941. });
  83942. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  83943. /**
  83944. * Specifies if the motion blur effect is enabled
  83945. */
  83946. get: function () {
  83947. return this._motionBlurEnabled;
  83948. },
  83949. set: function (enabled) {
  83950. if (this._motionBlurEnabled === enabled) {
  83951. return;
  83952. }
  83953. this._motionBlurEnabled = enabled;
  83954. this._buildPipeline();
  83955. },
  83956. enumerable: true,
  83957. configurable: true
  83958. });
  83959. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  83960. /**
  83961. * Specifies if anti-aliasing is enabled
  83962. */
  83963. get: function () {
  83964. return this._fxaaEnabled;
  83965. },
  83966. set: function (enabled) {
  83967. if (this._fxaaEnabled === enabled) {
  83968. return;
  83969. }
  83970. this._fxaaEnabled = enabled;
  83971. this._buildPipeline();
  83972. },
  83973. enumerable: true,
  83974. configurable: true
  83975. });
  83976. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  83977. /**
  83978. * Specifies the number of steps used to calculate the volumetric lights
  83979. * Typically in interval [50, 200]
  83980. */
  83981. get: function () {
  83982. return this._volumetricLightStepsCount;
  83983. },
  83984. set: function (count) {
  83985. if (this.volumetricLightPostProcess) {
  83986. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  83987. }
  83988. this._volumetricLightStepsCount = count;
  83989. },
  83990. enumerable: true,
  83991. configurable: true
  83992. });
  83993. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  83994. /**
  83995. * Specifies the number of samples used for the motion blur effect
  83996. * Typically in interval [16, 64]
  83997. */
  83998. get: function () {
  83999. return this._motionBlurSamples;
  84000. },
  84001. set: function (samples) {
  84002. if (this.motionBlurPostProcess) {
  84003. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  84004. }
  84005. this._motionBlurSamples = samples;
  84006. },
  84007. enumerable: true,
  84008. configurable: true
  84009. });
  84010. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  84011. /**
  84012. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  84013. */
  84014. get: function () {
  84015. return this._samples;
  84016. },
  84017. set: function (sampleCount) {
  84018. if (this._samples === sampleCount) {
  84019. return;
  84020. }
  84021. this._samples = sampleCount;
  84022. this._buildPipeline();
  84023. },
  84024. enumerable: true,
  84025. configurable: true
  84026. });
  84027. StandardRenderingPipeline.prototype._buildPipeline = function () {
  84028. var _this = this;
  84029. var ratio = this._ratio;
  84030. var scene = this._scene;
  84031. this._disposePostProcesses();
  84032. this._reset();
  84033. // Create pass post-process
  84034. if (!this._basePostProcess) {
  84035. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  84036. this.originalPostProcess.onApply = function (effect) {
  84037. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  84038. };
  84039. }
  84040. else {
  84041. this.originalPostProcess = this._basePostProcess;
  84042. }
  84043. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  84044. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  84045. }
  84046. this._currentDepthOfFieldSource = this.originalPostProcess;
  84047. if (this._bloomEnabled) {
  84048. // Create down sample X4 post-process
  84049. this._createDownSampleX4PostProcess(scene, ratio / 2);
  84050. // Create bright pass post-process
  84051. this._createBrightPassPostProcess(scene, ratio / 2);
  84052. // Create gaussian blur post-processes (down sampling blurs)
  84053. this._createBlurPostProcesses(scene, ratio / 4, 1);
  84054. // Create texture adder post-process
  84055. this._createTextureAdderPostProcess(scene, ratio);
  84056. // Create depth-of-field source post-process
  84057. 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);
  84058. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  84059. }
  84060. if (this._vlsEnabled) {
  84061. // Create volumetric light
  84062. this._createVolumetricLightPostProcess(scene, ratio);
  84063. // Create volumetric light final post-process
  84064. 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);
  84065. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  84066. }
  84067. if (this._lensFlareEnabled) {
  84068. // Create lens flare post-process
  84069. this._createLensFlarePostProcess(scene, ratio);
  84070. // Create depth-of-field source post-process post lens-flare and disable it now
  84071. 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);
  84072. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  84073. }
  84074. if (this._hdrEnabled) {
  84075. // Create luminance
  84076. this._createLuminancePostProcesses(scene, this._floatTextureType);
  84077. // Create HDR
  84078. this._createHdrPostProcess(scene, ratio);
  84079. // Create depth-of-field source post-process post hdr and disable it now
  84080. 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);
  84081. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  84082. }
  84083. if (this._depthOfFieldEnabled) {
  84084. // Create gaussian blur used by depth-of-field
  84085. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  84086. // Create depth-of-field post-process
  84087. this._createDepthOfFieldPostProcess(scene, ratio);
  84088. }
  84089. if (this._motionBlurEnabled) {
  84090. // Create motion blur post-process
  84091. this._createMotionBlurPostProcess(scene, ratio);
  84092. }
  84093. if (this._fxaaEnabled) {
  84094. // Create fxaa post-process
  84095. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  84096. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  84097. }
  84098. if (this._cameras !== null) {
  84099. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  84100. }
  84101. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  84102. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  84103. }
  84104. };
  84105. // Down Sample X4 Post-Processs
  84106. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  84107. var _this = this;
  84108. var downSampleX4Offsets = new Array(32);
  84109. 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);
  84110. this.downSampleX4PostProcess.onApply = function (effect) {
  84111. var id = 0;
  84112. var width = _this.downSampleX4PostProcess.width;
  84113. var height = _this.downSampleX4PostProcess.height;
  84114. for (var i = -2; i < 2; i++) {
  84115. for (var j = -2; j < 2; j++) {
  84116. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  84117. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  84118. id += 2;
  84119. }
  84120. }
  84121. effect.setArray2("dsOffsets", downSampleX4Offsets);
  84122. };
  84123. // Add to pipeline
  84124. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  84125. };
  84126. // Brightpass Post-Process
  84127. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  84128. var _this = this;
  84129. var brightOffsets = new Array(8);
  84130. 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);
  84131. this.brightPassPostProcess.onApply = function (effect) {
  84132. var sU = (1.0 / _this.brightPassPostProcess.width);
  84133. var sV = (1.0 / _this.brightPassPostProcess.height);
  84134. brightOffsets[0] = -0.5 * sU;
  84135. brightOffsets[1] = 0.5 * sV;
  84136. brightOffsets[2] = 0.5 * sU;
  84137. brightOffsets[3] = 0.5 * sV;
  84138. brightOffsets[4] = -0.5 * sU;
  84139. brightOffsets[5] = -0.5 * sV;
  84140. brightOffsets[6] = 0.5 * sU;
  84141. brightOffsets[7] = -0.5 * sV;
  84142. effect.setArray2("dsOffsets", brightOffsets);
  84143. effect.setFloat("brightThreshold", _this.brightThreshold);
  84144. };
  84145. // Add to pipeline
  84146. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  84147. };
  84148. // Create blur H&V post-processes
  84149. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  84150. var _this = this;
  84151. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  84152. var engine = scene.getEngine();
  84153. 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);
  84154. 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);
  84155. blurX.onActivateObservable.add(function () {
  84156. var dw = blurX.width / engine.getRenderWidth();
  84157. blurX.kernel = _this[blurWidthKey] * dw;
  84158. });
  84159. blurY.onActivateObservable.add(function () {
  84160. var dw = blurY.height / engine.getRenderHeight();
  84161. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  84162. });
  84163. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  84164. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  84165. this.blurHPostProcesses.push(blurX);
  84166. this.blurVPostProcesses.push(blurY);
  84167. };
  84168. // Create texture adder post-process
  84169. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  84170. var _this = this;
  84171. 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);
  84172. this.textureAdderPostProcess.onApply = function (effect) {
  84173. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  84174. effect.setTexture("lensSampler", _this.lensTexture);
  84175. effect.setFloat("exposure", _this.exposure);
  84176. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  84177. };
  84178. // Add to pipeline
  84179. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  84180. };
  84181. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  84182. var _this = this;
  84183. var geometryRenderer = scene.enableGeometryBufferRenderer();
  84184. geometryRenderer.enablePosition = true;
  84185. var geometry = geometryRenderer.getGBuffer();
  84186. // Base post-process
  84187. 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));
  84188. var depthValues = BABYLON.Vector2.Zero();
  84189. this.volumetricLightPostProcess.onApply = function (effect) {
  84190. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  84191. var generator = _this.sourceLight.getShadowGenerator();
  84192. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  84193. effect.setTexture("positionSampler", geometry.textures[2]);
  84194. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  84195. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  84196. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  84197. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  84198. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  84199. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  84200. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  84201. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  84202. effect.setVector2("depthValues", depthValues);
  84203. }
  84204. };
  84205. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  84206. // Smooth
  84207. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  84208. // Merge
  84209. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  84210. this.volumetricLightMergePostProces.onApply = function (effect) {
  84211. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  84212. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  84213. };
  84214. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  84215. };
  84216. // Create luminance
  84217. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  84218. var _this = this;
  84219. // Create luminance
  84220. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  84221. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  84222. var offsets = [];
  84223. this.luminancePostProcess.onApply = function (effect) {
  84224. var sU = (1.0 / _this.luminancePostProcess.width);
  84225. var sV = (1.0 / _this.luminancePostProcess.height);
  84226. offsets[0] = -0.5 * sU;
  84227. offsets[1] = 0.5 * sV;
  84228. offsets[2] = 0.5 * sU;
  84229. offsets[3] = 0.5 * sV;
  84230. offsets[4] = -0.5 * sU;
  84231. offsets[5] = -0.5 * sV;
  84232. offsets[6] = 0.5 * sU;
  84233. offsets[7] = -0.5 * sV;
  84234. effect.setArray2("lumOffsets", offsets);
  84235. };
  84236. // Add to pipeline
  84237. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  84238. // Create down sample luminance
  84239. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  84240. var size = Math.pow(3, i);
  84241. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  84242. if (i === 0) {
  84243. defines += "#define FINAL_DOWN_SAMPLER";
  84244. }
  84245. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  84246. this.luminanceDownSamplePostProcesses.push(postProcess);
  84247. }
  84248. // Create callbacks and add effects
  84249. var lastLuminance = this.luminancePostProcess;
  84250. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  84251. var downSampleOffsets = new Array(18);
  84252. pp.onApply = function (effect) {
  84253. if (!lastLuminance) {
  84254. return;
  84255. }
  84256. var id = 0;
  84257. for (var x = -1; x < 2; x++) {
  84258. for (var y = -1; y < 2; y++) {
  84259. downSampleOffsets[id] = x / lastLuminance.width;
  84260. downSampleOffsets[id + 1] = y / lastLuminance.height;
  84261. id += 2;
  84262. }
  84263. }
  84264. effect.setArray2("dsOffsets", downSampleOffsets);
  84265. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  84266. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  84267. lastLuminance = _this.luminancePostProcess;
  84268. }
  84269. else {
  84270. lastLuminance = pp;
  84271. }
  84272. };
  84273. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  84274. pp.onAfterRender = function (effect) {
  84275. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  84276. 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);
  84277. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  84278. };
  84279. }
  84280. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  84281. });
  84282. };
  84283. // Create HDR post-process
  84284. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  84285. var _this = this;
  84286. 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);
  84287. var outputLiminance = 1;
  84288. var time = 0;
  84289. var lastTime = 0;
  84290. this.hdrPostProcess.onApply = function (effect) {
  84291. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  84292. time += scene.getEngine().getDeltaTime();
  84293. if (outputLiminance < 0) {
  84294. outputLiminance = _this._hdrCurrentLuminance;
  84295. }
  84296. else {
  84297. var dt = (lastTime - time) / 1000.0;
  84298. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  84299. outputLiminance += _this.hdrDecreaseRate * dt;
  84300. }
  84301. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  84302. outputLiminance -= _this.hdrIncreaseRate * dt;
  84303. }
  84304. else {
  84305. outputLiminance = _this._hdrCurrentLuminance;
  84306. }
  84307. }
  84308. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  84309. effect.setFloat("averageLuminance", outputLiminance);
  84310. lastTime = time;
  84311. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  84312. };
  84313. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  84314. };
  84315. // Create lens flare post-process
  84316. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  84317. var _this = this;
  84318. 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);
  84319. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  84320. this._createBlurPostProcesses(scene, ratio / 4, 2);
  84321. 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);
  84322. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  84323. var resolution = new BABYLON.Vector2(0, 0);
  84324. // Lens flare
  84325. this.lensFlarePostProcess.onApply = function (effect) {
  84326. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  84327. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  84328. effect.setFloat("strength", _this.lensFlareStrength);
  84329. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  84330. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  84331. // Shift
  84332. resolution.x = _this.lensFlarePostProcess.width;
  84333. resolution.y = _this.lensFlarePostProcess.height;
  84334. effect.setVector2("resolution", resolution);
  84335. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  84336. };
  84337. // Compose
  84338. 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);
  84339. 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);
  84340. this.lensFlareComposePostProcess.onApply = function (effect) {
  84341. if (!_this._scene.activeCamera) {
  84342. return;
  84343. }
  84344. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  84345. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  84346. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  84347. // Lens start rotation matrix
  84348. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  84349. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  84350. 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));
  84351. camRot *= 4.0;
  84352. 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);
  84353. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  84354. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  84355. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  84356. };
  84357. };
  84358. // Create depth-of-field post-process
  84359. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  84360. var _this = this;
  84361. 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);
  84362. this.depthOfFieldPostProcess.onApply = function (effect) {
  84363. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  84364. effect.setTexture("depthSampler", _this._getDepthTexture());
  84365. effect.setFloat("distance", _this.depthOfFieldDistance);
  84366. };
  84367. // Add to pipeline
  84368. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  84369. };
  84370. // Create motion blur post-process
  84371. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  84372. var _this = this;
  84373. 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);
  84374. var motionScale = 0;
  84375. var prevViewProjection = BABYLON.Matrix.Identity();
  84376. var invViewProjection = BABYLON.Matrix.Identity();
  84377. var viewProjection = BABYLON.Matrix.Identity();
  84378. var screenSize = BABYLON.Vector2.Zero();
  84379. this.motionBlurPostProcess.onApply = function (effect) {
  84380. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  84381. viewProjection.invertToRef(invViewProjection);
  84382. effect.setMatrix("inverseViewProjection", invViewProjection);
  84383. effect.setMatrix("prevViewProjection", prevViewProjection);
  84384. prevViewProjection = viewProjection;
  84385. screenSize.x = _this.motionBlurPostProcess.width;
  84386. screenSize.y = _this.motionBlurPostProcess.height;
  84387. effect.setVector2("screenSize", screenSize);
  84388. motionScale = scene.getEngine().getFps() / 60.0;
  84389. effect.setFloat("motionScale", motionScale);
  84390. effect.setFloat("motionStrength", _this.motionStrength);
  84391. effect.setTexture("depthSampler", _this._getDepthTexture());
  84392. };
  84393. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  84394. };
  84395. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  84396. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  84397. var renderer = this._scene.enableGeometryBufferRenderer();
  84398. return renderer.getGBuffer().textures[0];
  84399. }
  84400. return this._scene.enableDepthRenderer().getDepthMap();
  84401. };
  84402. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  84403. for (var i = 0; i < this._cameras.length; i++) {
  84404. var camera = this._cameras[i];
  84405. if (this.originalPostProcess) {
  84406. this.originalPostProcess.dispose(camera);
  84407. }
  84408. if (this.downSampleX4PostProcess) {
  84409. this.downSampleX4PostProcess.dispose(camera);
  84410. }
  84411. if (this.brightPassPostProcess) {
  84412. this.brightPassPostProcess.dispose(camera);
  84413. }
  84414. if (this.textureAdderPostProcess) {
  84415. this.textureAdderPostProcess.dispose(camera);
  84416. }
  84417. if (this.textureAdderFinalPostProcess) {
  84418. this.textureAdderFinalPostProcess.dispose(camera);
  84419. }
  84420. if (this.volumetricLightPostProcess) {
  84421. this.volumetricLightPostProcess.dispose(camera);
  84422. }
  84423. if (this.volumetricLightSmoothXPostProcess) {
  84424. this.volumetricLightSmoothXPostProcess.dispose(camera);
  84425. }
  84426. if (this.volumetricLightSmoothYPostProcess) {
  84427. this.volumetricLightSmoothYPostProcess.dispose(camera);
  84428. }
  84429. if (this.volumetricLightMergePostProces) {
  84430. this.volumetricLightMergePostProces.dispose(camera);
  84431. }
  84432. if (this.volumetricLightFinalPostProcess) {
  84433. this.volumetricLightFinalPostProcess.dispose(camera);
  84434. }
  84435. if (this.lensFlarePostProcess) {
  84436. this.lensFlarePostProcess.dispose(camera);
  84437. }
  84438. if (this.lensFlareComposePostProcess) {
  84439. this.lensFlareComposePostProcess.dispose(camera);
  84440. }
  84441. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  84442. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  84443. }
  84444. if (this.luminancePostProcess) {
  84445. this.luminancePostProcess.dispose(camera);
  84446. }
  84447. if (this.hdrPostProcess) {
  84448. this.hdrPostProcess.dispose(camera);
  84449. }
  84450. if (this.hdrFinalPostProcess) {
  84451. this.hdrFinalPostProcess.dispose(camera);
  84452. }
  84453. if (this.depthOfFieldPostProcess) {
  84454. this.depthOfFieldPostProcess.dispose(camera);
  84455. }
  84456. if (this.motionBlurPostProcess) {
  84457. this.motionBlurPostProcess.dispose(camera);
  84458. }
  84459. if (this.fxaaPostProcess) {
  84460. this.fxaaPostProcess.dispose(camera);
  84461. }
  84462. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  84463. this.blurHPostProcesses[j].dispose(camera);
  84464. }
  84465. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  84466. this.blurVPostProcesses[j].dispose(camera);
  84467. }
  84468. }
  84469. this.originalPostProcess = null;
  84470. this.downSampleX4PostProcess = null;
  84471. this.brightPassPostProcess = null;
  84472. this.textureAdderPostProcess = null;
  84473. this.textureAdderFinalPostProcess = null;
  84474. this.volumetricLightPostProcess = null;
  84475. this.volumetricLightSmoothXPostProcess = null;
  84476. this.volumetricLightSmoothYPostProcess = null;
  84477. this.volumetricLightMergePostProces = null;
  84478. this.volumetricLightFinalPostProcess = null;
  84479. this.lensFlarePostProcess = null;
  84480. this.lensFlareComposePostProcess = null;
  84481. this.luminancePostProcess = null;
  84482. this.hdrPostProcess = null;
  84483. this.hdrFinalPostProcess = null;
  84484. this.depthOfFieldPostProcess = null;
  84485. this.motionBlurPostProcess = null;
  84486. this.fxaaPostProcess = null;
  84487. this.luminanceDownSamplePostProcesses = [];
  84488. this.blurHPostProcesses = [];
  84489. this.blurVPostProcesses = [];
  84490. };
  84491. /**
  84492. * Dispose of the pipeline and stop all post processes
  84493. */
  84494. StandardRenderingPipeline.prototype.dispose = function () {
  84495. this._disposePostProcesses();
  84496. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  84497. _super.prototype.dispose.call(this);
  84498. };
  84499. /**
  84500. * Serialize the rendering pipeline (Used when exporting)
  84501. * @returns the serialized object
  84502. */
  84503. StandardRenderingPipeline.prototype.serialize = function () {
  84504. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84505. if (this.sourceLight) {
  84506. serializationObject.sourceLightId = this.sourceLight.id;
  84507. }
  84508. serializationObject.customType = "StandardRenderingPipeline";
  84509. return serializationObject;
  84510. };
  84511. /**
  84512. * Parse the serialized pipeline
  84513. * @param source Source pipeline.
  84514. * @param scene The scene to load the pipeline to.
  84515. * @param rootUrl The URL of the serialized pipeline.
  84516. * @returns An instantiated pipeline from the serialized object.
  84517. */
  84518. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  84519. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  84520. if (source.sourceLightId) {
  84521. p.sourceLight = scene.getLightByID(source.sourceLightId);
  84522. }
  84523. return p;
  84524. };
  84525. // Luminance steps
  84526. StandardRenderingPipeline.LuminanceSteps = 6;
  84527. __decorate([
  84528. BABYLON.serialize()
  84529. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  84530. __decorate([
  84531. BABYLON.serialize()
  84532. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  84533. __decorate([
  84534. BABYLON.serialize()
  84535. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  84536. __decorate([
  84537. BABYLON.serialize()
  84538. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  84539. __decorate([
  84540. BABYLON.serializeAsTexture("lensTexture")
  84541. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  84542. __decorate([
  84543. BABYLON.serialize()
  84544. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  84545. __decorate([
  84546. BABYLON.serialize()
  84547. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  84548. __decorate([
  84549. BABYLON.serialize()
  84550. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  84551. __decorate([
  84552. BABYLON.serialize()
  84553. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  84554. __decorate([
  84555. BABYLON.serialize()
  84556. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  84557. __decorate([
  84558. BABYLON.serialize()
  84559. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  84560. __decorate([
  84561. BABYLON.serializeAsTexture("lensColorTexture")
  84562. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  84563. __decorate([
  84564. BABYLON.serialize()
  84565. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  84566. __decorate([
  84567. BABYLON.serialize()
  84568. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  84569. __decorate([
  84570. BABYLON.serialize()
  84571. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  84572. __decorate([
  84573. BABYLON.serialize()
  84574. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  84575. __decorate([
  84576. BABYLON.serializeAsTexture("lensStarTexture")
  84577. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  84578. __decorate([
  84579. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  84580. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  84581. __decorate([
  84582. BABYLON.serialize()
  84583. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  84584. __decorate([
  84585. BABYLON.serialize()
  84586. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  84587. __decorate([
  84588. BABYLON.serialize()
  84589. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  84590. __decorate([
  84591. BABYLON.serialize()
  84592. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  84593. __decorate([
  84594. BABYLON.serialize()
  84595. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  84596. __decorate([
  84597. BABYLON.serialize()
  84598. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  84599. __decorate([
  84600. BABYLON.serialize()
  84601. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  84602. __decorate([
  84603. BABYLON.serialize()
  84604. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  84605. __decorate([
  84606. BABYLON.serialize()
  84607. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  84608. __decorate([
  84609. BABYLON.serialize()
  84610. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  84611. __decorate([
  84612. BABYLON.serialize()
  84613. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  84614. __decorate([
  84615. BABYLON.serialize()
  84616. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  84617. __decorate([
  84618. BABYLON.serialize()
  84619. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  84620. __decorate([
  84621. BABYLON.serialize()
  84622. ], StandardRenderingPipeline.prototype, "samples", null);
  84623. return StandardRenderingPipeline;
  84624. }(BABYLON.PostProcessRenderPipeline));
  84625. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  84626. })(BABYLON || (BABYLON = {}));
  84627. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  84628. var BABYLON;
  84629. (function (BABYLON) {
  84630. var FxaaPostProcess = /** @class */ (function (_super) {
  84631. __extends(FxaaPostProcess, _super);
  84632. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  84633. if (camera === void 0) { camera = null; }
  84634. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84635. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  84636. var defines = _this._getDefines();
  84637. _this.updateEffect(defines);
  84638. _this.onApplyObservable.add(function (effect) {
  84639. var texelSize = _this.texelSize;
  84640. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  84641. });
  84642. return _this;
  84643. }
  84644. FxaaPostProcess.prototype._getDefines = function () {
  84645. var engine = this.getEngine();
  84646. if (!engine) {
  84647. return null;
  84648. }
  84649. var glInfo = engine.getGlInfo();
  84650. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  84651. return "#define MALI 1\n";
  84652. }
  84653. return null;
  84654. };
  84655. return FxaaPostProcess;
  84656. }(BABYLON.PostProcess));
  84657. BABYLON.FxaaPostProcess = FxaaPostProcess;
  84658. })(BABYLON || (BABYLON = {}));
  84659. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  84660. var BABYLON;
  84661. (function (BABYLON) {
  84662. /**
  84663. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  84664. */
  84665. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  84666. __extends(ChromaticAberrationPostProcess, _super);
  84667. /**
  84668. * Creates a new instance ChromaticAberrationPostProcess
  84669. * @param name The name of the effect.
  84670. * @param screenWidth The width of the screen to apply the effect on.
  84671. * @param screenHeight The height of the screen to apply the effect on.
  84672. * @param options The required width/height ratio to downsize to before computing the render pass.
  84673. * @param camera The camera to apply the render pass to.
  84674. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84675. * @param engine The engine which the post process will be applied. (default: current engine)
  84676. * @param reusable If the post process can be reused on the same frame. (default: false)
  84677. * @param textureType Type of textures used when performing the post process. (default: 0)
  84678. * @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)
  84679. */
  84680. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84681. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84682. if (blockCompilation === void 0) { blockCompilation = false; }
  84683. 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;
  84684. /**
  84685. * The amount of seperation of rgb channels (default: 30)
  84686. */
  84687. _this.aberrationAmount = 30;
  84688. /**
  84689. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  84690. */
  84691. _this.radialIntensity = 0;
  84692. /**
  84693. * 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))
  84694. */
  84695. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  84696. /**
  84697. * 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))
  84698. */
  84699. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  84700. _this.onApplyObservable.add(function (effect) {
  84701. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  84702. effect.setFloat('screen_width', screenWidth);
  84703. effect.setFloat('screen_height', screenHeight);
  84704. effect.setFloat('radialIntensity', _this.radialIntensity);
  84705. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  84706. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  84707. });
  84708. return _this;
  84709. }
  84710. return ChromaticAberrationPostProcess;
  84711. }(BABYLON.PostProcess));
  84712. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  84713. })(BABYLON || (BABYLON = {}));
  84714. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  84715. var BABYLON;
  84716. (function (BABYLON) {
  84717. /**
  84718. * The GrainPostProcess adds noise to the image at mid luminance levels
  84719. */
  84720. var GrainPostProcess = /** @class */ (function (_super) {
  84721. __extends(GrainPostProcess, _super);
  84722. /**
  84723. * Creates a new instance of @see GrainPostProcess
  84724. * @param name The name of the effect.
  84725. * @param options The required width/height ratio to downsize to before computing the render pass.
  84726. * @param camera The camera to apply the render pass to.
  84727. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84728. * @param engine The engine which the post process will be applied. (default: current engine)
  84729. * @param reusable If the post process can be reused on the same frame. (default: false)
  84730. * @param textureType Type of textures used when performing the post process. (default: 0)
  84731. * @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)
  84732. */
  84733. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84734. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84735. if (blockCompilation === void 0) { blockCompilation = false; }
  84736. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  84737. /**
  84738. * The intensity of the grain added (default: 30)
  84739. */
  84740. _this.intensity = 30;
  84741. /**
  84742. * If the grain should be randomized on every frame
  84743. */
  84744. _this.animated = false;
  84745. _this.onApplyObservable.add(function (effect) {
  84746. effect.setFloat('intensity', _this.intensity);
  84747. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  84748. });
  84749. return _this;
  84750. }
  84751. return GrainPostProcess;
  84752. }(BABYLON.PostProcess));
  84753. BABYLON.GrainPostProcess = GrainPostProcess;
  84754. })(BABYLON || (BABYLON = {}));
  84755. //# sourceMappingURL=babylon.grainPostProcess.js.map
  84756. var BABYLON;
  84757. (function (BABYLON) {
  84758. /**
  84759. * The SharpenPostProcess applies a sharpen kernel to every pixel
  84760. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  84761. */
  84762. var SharpenPostProcess = /** @class */ (function (_super) {
  84763. __extends(SharpenPostProcess, _super);
  84764. /**
  84765. * Creates a new instance ConvolutionPostProcess
  84766. * @param name The name of the effect.
  84767. * @param options The required width/height ratio to downsize to before computing the render pass.
  84768. * @param camera The camera to apply the render pass to.
  84769. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84770. * @param engine The engine which the post process will be applied. (default: current engine)
  84771. * @param reusable If the post process can be reused on the same frame. (default: false)
  84772. * @param textureType Type of textures used when performing the post process. (default: 0)
  84773. * @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)
  84774. */
  84775. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  84776. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84777. if (blockCompilation === void 0) { blockCompilation = false; }
  84778. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  84779. /**
  84780. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  84781. */
  84782. _this.colorAmount = 1.0;
  84783. /**
  84784. * How much sharpness should be applied (default: 0.3)
  84785. */
  84786. _this.edgeAmount = 0.3;
  84787. _this.onApply = function (effect) {
  84788. effect.setFloat2("screenSize", _this.width, _this.height);
  84789. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  84790. };
  84791. return _this;
  84792. }
  84793. return SharpenPostProcess;
  84794. }(BABYLON.PostProcess));
  84795. BABYLON.SharpenPostProcess = SharpenPostProcess;
  84796. })(BABYLON || (BABYLON = {}));
  84797. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  84798. var BABYLON;
  84799. (function (BABYLON) {
  84800. /**
  84801. * The Blur Post Process which blurs an image based on a kernel and direction.
  84802. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  84803. */
  84804. var BlurPostProcess = /** @class */ (function (_super) {
  84805. __extends(BlurPostProcess, _super);
  84806. /**
  84807. * Creates a new instance BlurPostProcess
  84808. * @param name The name of the effect.
  84809. * @param direction The direction in which to blur the image.
  84810. * @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.
  84811. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  84812. * @param camera The camera to apply the render pass to.
  84813. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84814. * @param engine The engine which the post process will be applied. (default: current engine)
  84815. * @param reusable If the post process can be reused on the same frame. (default: false)
  84816. * @param textureType Type of textures used when performing the post process. (default: 0)
  84817. * @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)
  84818. */
  84819. function BlurPostProcess(name,
  84820. /** The direction in which to blur the image. */
  84821. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  84822. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  84823. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84824. if (defines === void 0) { defines = ""; }
  84825. if (blockCompilation === void 0) { blockCompilation = false; }
  84826. 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;
  84827. _this.direction = direction;
  84828. _this.blockCompilation = blockCompilation;
  84829. _this._packedFloat = false;
  84830. _this._staticDefines = "";
  84831. _this._staticDefines = defines;
  84832. _this.onApplyObservable.add(function (effect) {
  84833. if (_this._outputTexture) {
  84834. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  84835. }
  84836. else {
  84837. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  84838. }
  84839. });
  84840. _this.kernel = kernel;
  84841. return _this;
  84842. }
  84843. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  84844. /**
  84845. * Gets the length in pixels of the blur sample region
  84846. */
  84847. get: function () {
  84848. return this._idealKernel;
  84849. },
  84850. /**
  84851. * Sets the length in pixels of the blur sample region
  84852. */
  84853. set: function (v) {
  84854. if (this._idealKernel === v) {
  84855. return;
  84856. }
  84857. v = Math.max(v, 1);
  84858. this._idealKernel = v;
  84859. this._kernel = this._nearestBestKernel(v);
  84860. if (!this.blockCompilation) {
  84861. this._updateParameters();
  84862. }
  84863. },
  84864. enumerable: true,
  84865. configurable: true
  84866. });
  84867. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  84868. /**
  84869. * Gets wether or not the blur is unpacking/repacking floats
  84870. */
  84871. get: function () {
  84872. return this._packedFloat;
  84873. },
  84874. /**
  84875. * Sets wether or not the blur needs to unpack/repack floats
  84876. */
  84877. set: function (v) {
  84878. if (this._packedFloat === v) {
  84879. return;
  84880. }
  84881. this._packedFloat = v;
  84882. if (!this.blockCompilation) {
  84883. this._updateParameters();
  84884. }
  84885. },
  84886. enumerable: true,
  84887. configurable: true
  84888. });
  84889. /**
  84890. * Updates the effect with the current post process compile time values and recompiles the shader.
  84891. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  84892. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  84893. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  84894. * @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
  84895. * @param onCompiled Called when the shader has been compiled.
  84896. * @param onError Called if there is an error when compiling a shader.
  84897. */
  84898. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  84899. if (defines === void 0) { defines = null; }
  84900. if (uniforms === void 0) { uniforms = null; }
  84901. if (samplers === void 0) { samplers = null; }
  84902. this._updateParameters(onCompiled, onError);
  84903. };
  84904. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  84905. // Generate sampling offsets and weights
  84906. var N = this._kernel;
  84907. var centerIndex = (N - 1) / 2;
  84908. // Generate Gaussian sampling weights over kernel
  84909. var offsets = [];
  84910. var weights = [];
  84911. var totalWeight = 0;
  84912. for (var i = 0; i < N; i++) {
  84913. var u = i / (N - 1);
  84914. var w = this._gaussianWeight(u * 2.0 - 1);
  84915. offsets[i] = (i - centerIndex);
  84916. weights[i] = w;
  84917. totalWeight += w;
  84918. }
  84919. // Normalize weights
  84920. for (var i = 0; i < weights.length; i++) {
  84921. weights[i] /= totalWeight;
  84922. }
  84923. // Optimize: combine samples to take advantage of hardware linear sampling
  84924. // Walk from left to center, combining pairs (symmetrically)
  84925. var linearSamplingWeights = [];
  84926. var linearSamplingOffsets = [];
  84927. var linearSamplingMap = [];
  84928. for (var i = 0; i <= centerIndex; i += 2) {
  84929. var j = Math.min(i + 1, Math.floor(centerIndex));
  84930. var singleCenterSample = i === j;
  84931. if (singleCenterSample) {
  84932. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  84933. }
  84934. else {
  84935. var sharedCell = j === centerIndex;
  84936. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  84937. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  84938. if (offsetLinear === 0) {
  84939. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  84940. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  84941. }
  84942. else {
  84943. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  84944. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  84945. }
  84946. }
  84947. }
  84948. for (var i = 0; i < linearSamplingMap.length; i++) {
  84949. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  84950. linearSamplingWeights[i] = linearSamplingMap[i].w;
  84951. }
  84952. // Replace with optimized
  84953. offsets = linearSamplingOffsets;
  84954. weights = linearSamplingWeights;
  84955. // Generate shaders
  84956. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  84957. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  84958. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  84959. var defines = "";
  84960. defines += this._staticDefines;
  84961. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  84962. if (this._staticDefines.indexOf("DOF") != -1) {
  84963. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  84964. varyingCount--;
  84965. }
  84966. for (var i = 0; i < varyingCount; i++) {
  84967. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  84968. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  84969. }
  84970. var depCount = 0;
  84971. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  84972. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  84973. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  84974. depCount++;
  84975. }
  84976. if (this.packedFloat) {
  84977. defines += "#define PACKEDFLOAT 1";
  84978. }
  84979. this.blockCompilation = false;
  84980. _super.prototype.updateEffect.call(this, defines, null, null, {
  84981. varyingCount: varyingCount,
  84982. depCount: depCount
  84983. }, onCompiled, onError);
  84984. };
  84985. /**
  84986. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  84987. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  84988. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  84989. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  84990. * The gaps between physical kernels are compensated for in the weighting of the samples
  84991. * @param idealKernel Ideal blur kernel.
  84992. * @return Nearest best kernel.
  84993. */
  84994. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  84995. var v = Math.round(idealKernel);
  84996. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  84997. var k = _a[_i];
  84998. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  84999. return Math.max(k, 3);
  85000. }
  85001. }
  85002. return Math.max(v, 3);
  85003. };
  85004. /**
  85005. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  85006. * @param x The point on the Gaussian distribution to sample.
  85007. * @return the value of the Gaussian function at x.
  85008. */
  85009. BlurPostProcess.prototype._gaussianWeight = function (x) {
  85010. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  85011. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  85012. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  85013. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  85014. // truncated at around 1.3% of peak strength.
  85015. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  85016. var sigma = (1 / 3);
  85017. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  85018. var exponent = -((x * x) / (2.0 * sigma * sigma));
  85019. var weight = (1.0 / denominator) * Math.exp(exponent);
  85020. return weight;
  85021. };
  85022. /**
  85023. * Generates a string that can be used as a floating point number in GLSL.
  85024. * @param x Value to print.
  85025. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  85026. * @return GLSL float string.
  85027. */
  85028. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  85029. if (decimalFigures === void 0) { decimalFigures = 8; }
  85030. return x.toFixed(decimalFigures).replace(/0+$/, '');
  85031. };
  85032. return BlurPostProcess;
  85033. }(BABYLON.PostProcess));
  85034. BABYLON.BlurPostProcess = BlurPostProcess;
  85035. })(BABYLON || (BABYLON = {}));
  85036. //# sourceMappingURL=babylon.blurPostProcess.js.map
  85037. var BABYLON;
  85038. (function (BABYLON) {
  85039. /**
  85040. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  85041. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  85042. * based on samples that have a large difference in distance than the center pixel.
  85043. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  85044. */
  85045. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  85046. __extends(DepthOfFieldBlurPostProcess, _super);
  85047. /**
  85048. * Creates a new instance CircleOfConfusionPostProcess
  85049. * @param name The name of the effect.
  85050. * @param scene The scene the effect belongs to.
  85051. * @param direction The direction the blur should be applied.
  85052. * @param kernel The size of the kernel used to blur.
  85053. * @param options The required width/height ratio to downsize to before computing the render pass.
  85054. * @param camera The camera to apply the render pass to.
  85055. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  85056. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  85057. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85058. * @param engine The engine which the post process will be applied. (default: current engine)
  85059. * @param reusable If the post process can be reused on the same frame. (default: false)
  85060. * @param textureType Type of textures used when performing the post process. (default: 0)
  85061. * @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)
  85062. */
  85063. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  85064. if (imageToBlur === void 0) { imageToBlur = null; }
  85065. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85066. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85067. if (blockCompilation === void 0) { blockCompilation = false; }
  85068. 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;
  85069. _this.direction = direction;
  85070. _this.onApplyObservable.add(function (effect) {
  85071. if (imageToBlur != null) {
  85072. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  85073. }
  85074. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  85075. if (scene.activeCamera) {
  85076. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  85077. }
  85078. });
  85079. return _this;
  85080. }
  85081. return DepthOfFieldBlurPostProcess;
  85082. }(BABYLON.BlurPostProcess));
  85083. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  85084. })(BABYLON || (BABYLON = {}));
  85085. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  85086. var BABYLON;
  85087. (function (BABYLON) {
  85088. /**
  85089. * Options to be set when merging outputs from the default pipeline.
  85090. */
  85091. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  85092. function DepthOfFieldMergePostProcessOptions() {
  85093. }
  85094. return DepthOfFieldMergePostProcessOptions;
  85095. }());
  85096. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  85097. /**
  85098. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  85099. */
  85100. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  85101. __extends(DepthOfFieldMergePostProcess, _super);
  85102. /**
  85103. * Creates a new instance of DepthOfFieldMergePostProcess
  85104. * @param name The name of the effect.
  85105. * @param originalFromInput Post process which's input will be used for the merge.
  85106. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  85107. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  85108. * @param options The required width/height ratio to downsize to before computing the render pass.
  85109. * @param camera The camera to apply the render pass to.
  85110. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85111. * @param engine The engine which the post process will be applied. (default: current engine)
  85112. * @param reusable If the post process can be reused on the same frame. (default: false)
  85113. * @param textureType Type of textures used when performing the post process. (default: 0)
  85114. * @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)
  85115. */
  85116. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85117. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85118. if (blockCompilation === void 0) { blockCompilation = false; }
  85119. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  85120. _this.blurSteps = blurSteps;
  85121. _this.onApplyObservable.add(function (effect) {
  85122. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  85123. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  85124. blurSteps.forEach(function (step, index) {
  85125. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  85126. });
  85127. });
  85128. if (!blockCompilation) {
  85129. _this.updateEffect();
  85130. }
  85131. return _this;
  85132. }
  85133. /**
  85134. * Updates the effect with the current post process compile time values and recompiles the shader.
  85135. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  85136. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  85137. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  85138. * @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
  85139. * @param onCompiled Called when the shader has been compiled.
  85140. * @param onError Called if there is an error when compiling a shader.
  85141. */
  85142. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  85143. if (defines === void 0) { defines = null; }
  85144. if (uniforms === void 0) { uniforms = null; }
  85145. if (samplers === void 0) { samplers = null; }
  85146. if (!defines) {
  85147. defines = "";
  85148. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  85149. }
  85150. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  85151. };
  85152. return DepthOfFieldMergePostProcess;
  85153. }(BABYLON.PostProcess));
  85154. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  85155. })(BABYLON || (BABYLON = {}));
  85156. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  85157. var BABYLON;
  85158. (function (BABYLON) {
  85159. /**
  85160. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  85161. */
  85162. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  85163. __extends(CircleOfConfusionPostProcess, _super);
  85164. /**
  85165. * Creates a new instance CircleOfConfusionPostProcess
  85166. * @param name The name of the effect.
  85167. * @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.
  85168. * @param options The required width/height ratio to downsize to before computing the render pass.
  85169. * @param camera The camera to apply the render pass to.
  85170. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85171. * @param engine The engine which the post process will be applied. (default: current engine)
  85172. * @param reusable If the post process can be reused on the same frame. (default: false)
  85173. * @param textureType Type of textures used when performing the post process. (default: 0)
  85174. * @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)
  85175. */
  85176. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85177. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85178. if (blockCompilation === void 0) { blockCompilation = false; }
  85179. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  85180. /**
  85181. * 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.
  85182. */
  85183. _this.lensSize = 50;
  85184. /**
  85185. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  85186. */
  85187. _this.fStop = 1.4;
  85188. /**
  85189. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  85190. */
  85191. _this.focusDistance = 2000;
  85192. /**
  85193. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  85194. */
  85195. _this.focalLength = 50;
  85196. _this._depthTexture = null;
  85197. _this._depthTexture = depthTexture;
  85198. _this.onApplyObservable.add(function (effect) {
  85199. if (!_this._depthTexture) {
  85200. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  85201. return;
  85202. }
  85203. effect.setTexture("depthSampler", _this._depthTexture);
  85204. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  85205. var aperture = _this.lensSize / _this.fStop;
  85206. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  85207. effect.setFloat('focusDistance', _this.focusDistance);
  85208. effect.setFloat('cocPrecalculation', cocPrecalculation);
  85209. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  85210. });
  85211. return _this;
  85212. }
  85213. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  85214. /**
  85215. * 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.
  85216. */
  85217. set: function (value) {
  85218. this._depthTexture = value;
  85219. },
  85220. enumerable: true,
  85221. configurable: true
  85222. });
  85223. return CircleOfConfusionPostProcess;
  85224. }(BABYLON.PostProcess));
  85225. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  85226. })(BABYLON || (BABYLON = {}));
  85227. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  85228. var BABYLON;
  85229. (function (BABYLON) {
  85230. /**
  85231. * Specifies the level of max blur that should be applied when using the depth of field effect
  85232. */
  85233. var DepthOfFieldEffectBlurLevel;
  85234. (function (DepthOfFieldEffectBlurLevel) {
  85235. /**
  85236. * Subtle blur
  85237. */
  85238. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  85239. /**
  85240. * Medium blur
  85241. */
  85242. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  85243. /**
  85244. * Large blur
  85245. */
  85246. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  85247. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  85248. ;
  85249. /**
  85250. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  85251. */
  85252. var DepthOfFieldEffect = /** @class */ (function (_super) {
  85253. __extends(DepthOfFieldEffect, _super);
  85254. /**
  85255. * Creates a new instance DepthOfFieldEffect
  85256. * @param scene The scene the effect belongs to.
  85257. * @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.
  85258. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  85259. * @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)
  85260. */
  85261. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  85262. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  85263. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  85264. if (blockCompilation === void 0) { blockCompilation = false; }
  85265. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  85266. return _this._effects;
  85267. }, true) || this;
  85268. /**
  85269. * @hidden Internal post processes in depth of field effect
  85270. */
  85271. _this._effects = [];
  85272. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  85273. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  85274. // 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)
  85275. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  85276. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  85277. _this._depthOfFieldBlurY = [];
  85278. _this._depthOfFieldBlurX = [];
  85279. var blurCount = 1;
  85280. var kernelSize = 15;
  85281. switch (blurLevel) {
  85282. case DepthOfFieldEffectBlurLevel.High: {
  85283. blurCount = 3;
  85284. kernelSize = 51;
  85285. break;
  85286. }
  85287. case DepthOfFieldEffectBlurLevel.Medium: {
  85288. blurCount = 2;
  85289. kernelSize = 31;
  85290. break;
  85291. }
  85292. default: {
  85293. kernelSize = 15;
  85294. blurCount = 1;
  85295. break;
  85296. }
  85297. }
  85298. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  85299. var ratio = 1.0;
  85300. for (var i = 0; i < blurCount; i++) {
  85301. 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);
  85302. blurY.autoClear = false;
  85303. ratio = 0.75 / Math.pow(2, i);
  85304. 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);
  85305. blurX.autoClear = false;
  85306. _this._depthOfFieldBlurY.push(blurY);
  85307. _this._depthOfFieldBlurX.push(blurX);
  85308. }
  85309. // Set all post processes on the effect.
  85310. _this._effects = [_this._circleOfConfusion];
  85311. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  85312. _this._effects.push(_this._depthOfFieldBlurY[i]);
  85313. _this._effects.push(_this._depthOfFieldBlurX[i]);
  85314. }
  85315. // Merge blurred images with original image based on circleOfConfusion
  85316. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  85317. _this._dofMerge.autoClear = false;
  85318. _this._effects.push(_this._dofMerge);
  85319. return _this;
  85320. }
  85321. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  85322. get: function () {
  85323. return this._circleOfConfusion.focalLength;
  85324. },
  85325. /**
  85326. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  85327. */
  85328. set: function (value) {
  85329. this._circleOfConfusion.focalLength = value;
  85330. },
  85331. enumerable: true,
  85332. configurable: true
  85333. });
  85334. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  85335. get: function () {
  85336. return this._circleOfConfusion.fStop;
  85337. },
  85338. /**
  85339. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  85340. */
  85341. set: function (value) {
  85342. this._circleOfConfusion.fStop = value;
  85343. },
  85344. enumerable: true,
  85345. configurable: true
  85346. });
  85347. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  85348. get: function () {
  85349. return this._circleOfConfusion.focusDistance;
  85350. },
  85351. /**
  85352. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  85353. */
  85354. set: function (value) {
  85355. this._circleOfConfusion.focusDistance = value;
  85356. },
  85357. enumerable: true,
  85358. configurable: true
  85359. });
  85360. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  85361. get: function () {
  85362. return this._circleOfConfusion.lensSize;
  85363. },
  85364. /**
  85365. * 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.
  85366. */
  85367. set: function (value) {
  85368. this._circleOfConfusion.lensSize = value;
  85369. },
  85370. enumerable: true,
  85371. configurable: true
  85372. });
  85373. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  85374. /**
  85375. * 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.
  85376. */
  85377. set: function (value) {
  85378. this._circleOfConfusion.depthTexture = value;
  85379. },
  85380. enumerable: true,
  85381. configurable: true
  85382. });
  85383. /**
  85384. * Disposes each of the internal effects for a given camera.
  85385. * @param camera The camera to dispose the effect on.
  85386. */
  85387. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  85388. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85389. this._effects[effectIndex].dispose(camera);
  85390. }
  85391. };
  85392. /**
  85393. * @hidden Internal
  85394. */
  85395. DepthOfFieldEffect.prototype._updateEffects = function () {
  85396. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85397. this._effects[effectIndex].updateEffect();
  85398. }
  85399. };
  85400. /**
  85401. * Internal
  85402. * @returns if all the contained post processes are ready.
  85403. * @hidden
  85404. */
  85405. DepthOfFieldEffect.prototype._isReady = function () {
  85406. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85407. if (!this._effects[effectIndex].isReady()) {
  85408. return false;
  85409. }
  85410. }
  85411. return true;
  85412. };
  85413. return DepthOfFieldEffect;
  85414. }(BABYLON.PostProcessRenderEffect));
  85415. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  85416. })(BABYLON || (BABYLON = {}));
  85417. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  85418. var BABYLON;
  85419. (function (BABYLON) {
  85420. /**
  85421. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  85422. */
  85423. var BloomMergePostProcess = /** @class */ (function (_super) {
  85424. __extends(BloomMergePostProcess, _super);
  85425. /**
  85426. * Creates a new instance of @see BloomMergePostProcess
  85427. * @param name The name of the effect.
  85428. * @param originalFromInput Post process which's input will be used for the merge.
  85429. * @param blurred Blurred highlights post process which's output will be used.
  85430. * @param weight Weight of the bloom to be added to the original input.
  85431. * @param options The required width/height ratio to downsize to before computing the render pass.
  85432. * @param camera The camera to apply the render pass to.
  85433. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85434. * @param engine The engine which the post process will be applied. (default: current engine)
  85435. * @param reusable If the post process can be reused on the same frame. (default: false)
  85436. * @param textureType Type of textures used when performing the post process. (default: 0)
  85437. * @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)
  85438. */
  85439. function BloomMergePostProcess(name, originalFromInput, blurred,
  85440. /** Weight of the bloom to be added to the original input. */
  85441. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85442. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85443. if (blockCompilation === void 0) { blockCompilation = false; }
  85444. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  85445. _this.weight = weight;
  85446. _this.onApplyObservable.add(function (effect) {
  85447. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  85448. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  85449. effect.setFloat("bloomWeight", _this.weight);
  85450. });
  85451. if (!blockCompilation) {
  85452. _this.updateEffect();
  85453. }
  85454. return _this;
  85455. }
  85456. return BloomMergePostProcess;
  85457. }(BABYLON.PostProcess));
  85458. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  85459. })(BABYLON || (BABYLON = {}));
  85460. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  85461. var BABYLON;
  85462. (function (BABYLON) {
  85463. /**
  85464. * 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.
  85465. */
  85466. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  85467. __extends(ExtractHighlightsPostProcess, _super);
  85468. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85469. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85470. if (blockCompilation === void 0) { blockCompilation = false; }
  85471. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  85472. /**
  85473. * The luminance threshold, pixels below this value will be set to black.
  85474. */
  85475. _this.threshold = 0.9;
  85476. /** @hidden */
  85477. _this._exposure = 1;
  85478. /**
  85479. * Post process which has the input texture to be used when performing highlight extraction
  85480. * @hidden
  85481. */
  85482. _this._inputPostProcess = null;
  85483. _this.onApplyObservable.add(function (effect) {
  85484. if (_this._inputPostProcess) {
  85485. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  85486. }
  85487. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  85488. effect.setFloat('exposure', _this._exposure);
  85489. });
  85490. return _this;
  85491. }
  85492. return ExtractHighlightsPostProcess;
  85493. }(BABYLON.PostProcess));
  85494. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  85495. })(BABYLON || (BABYLON = {}));
  85496. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  85497. var BABYLON;
  85498. (function (BABYLON) {
  85499. /**
  85500. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  85501. */
  85502. var BloomEffect = /** @class */ (function (_super) {
  85503. __extends(BloomEffect, _super);
  85504. /**
  85505. * Creates a new instance of @see BloomEffect
  85506. * @param scene The scene the effect belongs to.
  85507. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  85508. * @param bloomKernel The size of the kernel to be used when applying the blur.
  85509. * @param bloomWeight The the strength of bloom.
  85510. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  85511. * @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)
  85512. */
  85513. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  85514. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  85515. if (blockCompilation === void 0) { blockCompilation = false; }
  85516. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  85517. return _this._effects;
  85518. }, true) || this;
  85519. _this.bloomScale = bloomScale;
  85520. /**
  85521. * @hidden Internal
  85522. */
  85523. _this._effects = [];
  85524. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  85525. _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);
  85526. _this._blurX.alwaysForcePOT = true;
  85527. _this._blurX.autoClear = false;
  85528. _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);
  85529. _this._blurY.alwaysForcePOT = true;
  85530. _this._blurY.autoClear = false;
  85531. _this.kernel = bloomKernel;
  85532. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  85533. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  85534. _this._merge.autoClear = false;
  85535. _this._effects.push(_this._merge);
  85536. return _this;
  85537. }
  85538. Object.defineProperty(BloomEffect.prototype, "threshold", {
  85539. /**
  85540. * The luminance threshold to find bright areas of the image to bloom.
  85541. */
  85542. get: function () {
  85543. return this._downscale.threshold;
  85544. },
  85545. set: function (value) {
  85546. this._downscale.threshold = value;
  85547. },
  85548. enumerable: true,
  85549. configurable: true
  85550. });
  85551. Object.defineProperty(BloomEffect.prototype, "weight", {
  85552. /**
  85553. * The strength of the bloom.
  85554. */
  85555. get: function () {
  85556. return this._merge.weight;
  85557. },
  85558. set: function (value) {
  85559. this._merge.weight = value;
  85560. },
  85561. enumerable: true,
  85562. configurable: true
  85563. });
  85564. Object.defineProperty(BloomEffect.prototype, "kernel", {
  85565. /**
  85566. * Specifies the size of the bloom blur kernel, relative to the final output size
  85567. */
  85568. get: function () {
  85569. return this._blurX.kernel / this.bloomScale;
  85570. },
  85571. set: function (value) {
  85572. this._blurX.kernel = value * this.bloomScale;
  85573. this._blurY.kernel = value * this.bloomScale;
  85574. },
  85575. enumerable: true,
  85576. configurable: true
  85577. });
  85578. /**
  85579. * Disposes each of the internal effects for a given camera.
  85580. * @param camera The camera to dispose the effect on.
  85581. */
  85582. BloomEffect.prototype.disposeEffects = function (camera) {
  85583. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85584. this._effects[effectIndex].dispose(camera);
  85585. }
  85586. };
  85587. /**
  85588. * @hidden Internal
  85589. */
  85590. BloomEffect.prototype._updateEffects = function () {
  85591. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85592. this._effects[effectIndex].updateEffect();
  85593. }
  85594. };
  85595. /**
  85596. * Internal
  85597. * @returns if all the contained post processes are ready.
  85598. * @hidden
  85599. */
  85600. BloomEffect.prototype._isReady = function () {
  85601. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  85602. if (!this._effects[effectIndex].isReady()) {
  85603. return false;
  85604. }
  85605. }
  85606. return true;
  85607. };
  85608. return BloomEffect;
  85609. }(BABYLON.PostProcessRenderEffect));
  85610. BABYLON.BloomEffect = BloomEffect;
  85611. })(BABYLON || (BABYLON = {}));
  85612. //# sourceMappingURL=babylon.bloomEffect.js.map
  85613. var BABYLON;
  85614. (function (BABYLON) {
  85615. /**
  85616. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  85617. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  85618. */
  85619. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  85620. __extends(DefaultRenderingPipeline, _super);
  85621. /**
  85622. * @constructor
  85623. * @param {string} name - The rendering pipeline name (default: "")
  85624. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  85625. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  85626. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  85627. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  85628. */
  85629. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  85630. if (name === void 0) { name = ""; }
  85631. if (hdr === void 0) { hdr = true; }
  85632. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  85633. if (automaticBuild === void 0) { automaticBuild = true; }
  85634. var _this = _super.call(this, scene.getEngine(), name) || this;
  85635. _this._camerasToBeAttached = [];
  85636. /**
  85637. * ID of the sharpen post process,
  85638. */
  85639. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  85640. /**
  85641. * @ignore
  85642. * ID of the image processing post process;
  85643. */
  85644. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  85645. /**
  85646. * @ignore
  85647. * ID of the Fast Approximate Anti-Aliasing post process;
  85648. */
  85649. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  85650. /**
  85651. * ID of the chromatic aberration post process,
  85652. */
  85653. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  85654. /**
  85655. * ID of the grain post process
  85656. */
  85657. _this.GrainPostProcessId = "GrainPostProcessEffect";
  85658. /**
  85659. * Glow post process which adds a glow to emmisive areas of the image
  85660. */
  85661. _this._glowLayer = null;
  85662. /**
  85663. * Animations which can be used to tweak settings over a period of time
  85664. */
  85665. _this.animations = [];
  85666. _this._imageProcessingConfigurationObserver = null;
  85667. // Values
  85668. _this._sharpenEnabled = false;
  85669. _this._bloomEnabled = false;
  85670. _this._depthOfFieldEnabled = false;
  85671. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  85672. _this._fxaaEnabled = false;
  85673. _this._imageProcessingEnabled = true;
  85674. _this._bloomScale = 0.5;
  85675. _this._chromaticAberrationEnabled = false;
  85676. _this._grainEnabled = false;
  85677. _this._buildAllowed = true;
  85678. _this._resizeObserver = null;
  85679. _this._hardwareScaleLevel = 1.0;
  85680. _this._bloomKernel = 64;
  85681. /**
  85682. * Specifies the weight of the bloom in the final rendering
  85683. */
  85684. _this._bloomWeight = 0.15;
  85685. /**
  85686. * Specifies the luma threshold for the area that will be blurred by the bloom
  85687. */
  85688. _this._bloomThreshold = 0.9;
  85689. _this._samples = 1;
  85690. _this._hasCleared = false;
  85691. _this._prevPostProcess = null;
  85692. _this._prevPrevPostProcess = null;
  85693. _this._depthOfFieldSceneObserver = null;
  85694. _this._cameras = cameras || scene.cameras;
  85695. _this._cameras = _this._cameras.slice();
  85696. _this._camerasToBeAttached = _this._cameras.slice();
  85697. _this._buildAllowed = automaticBuild;
  85698. // Initialize
  85699. _this._scene = scene;
  85700. var caps = _this._scene.getEngine().getCaps();
  85701. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  85702. // Misc
  85703. if (_this._hdr) {
  85704. if (caps.textureHalfFloatRender) {
  85705. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85706. }
  85707. else if (caps.textureFloatRender) {
  85708. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85709. }
  85710. }
  85711. else {
  85712. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85713. }
  85714. // Attach
  85715. scene.postProcessRenderPipelineManager.addPipeline(_this);
  85716. var engine = _this._scene.getEngine();
  85717. // Create post processes before hand so they can be modified before enabled.
  85718. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  85719. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  85720. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  85721. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  85722. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  85723. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  85724. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  85725. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  85726. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  85727. _this._resizeObserver = engine.onResizeObservable.add(function () {
  85728. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  85729. _this.bloomKernel = _this.bloomKernel;
  85730. });
  85731. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  85732. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  85733. });
  85734. _this._buildPipeline();
  85735. return _this;
  85736. }
  85737. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  85738. get: function () {
  85739. return this._sharpenEnabled;
  85740. },
  85741. /**
  85742. * Enable or disable the sharpen process from the pipeline
  85743. */
  85744. set: function (enabled) {
  85745. if (this._sharpenEnabled === enabled) {
  85746. return;
  85747. }
  85748. this._sharpenEnabled = enabled;
  85749. this._buildPipeline();
  85750. },
  85751. enumerable: true,
  85752. configurable: true
  85753. });
  85754. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  85755. /**
  85756. * Specifies the size of the bloom blur kernel, relative to the final output size
  85757. */
  85758. get: function () {
  85759. return this._bloomKernel;
  85760. },
  85761. set: function (value) {
  85762. this._bloomKernel = value;
  85763. this.bloom.kernel = value / this._hardwareScaleLevel;
  85764. },
  85765. enumerable: true,
  85766. configurable: true
  85767. });
  85768. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  85769. get: function () {
  85770. return this._bloomWeight;
  85771. },
  85772. /**
  85773. * The strength of the bloom.
  85774. */
  85775. set: function (value) {
  85776. if (this._bloomWeight === value) {
  85777. return;
  85778. }
  85779. this.bloom.weight = value;
  85780. this._bloomWeight = value;
  85781. },
  85782. enumerable: true,
  85783. configurable: true
  85784. });
  85785. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  85786. get: function () {
  85787. return this._bloomThreshold;
  85788. },
  85789. /**
  85790. * The strength of the bloom.
  85791. */
  85792. set: function (value) {
  85793. if (this._bloomThreshold === value) {
  85794. return;
  85795. }
  85796. this.bloom.threshold = value;
  85797. this._bloomThreshold = value;
  85798. },
  85799. enumerable: true,
  85800. configurable: true
  85801. });
  85802. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  85803. get: function () {
  85804. return this._bloomScale;
  85805. },
  85806. /**
  85807. * The scale of the bloom, lower value will provide better performance.
  85808. */
  85809. set: function (value) {
  85810. if (this._bloomScale === value) {
  85811. return;
  85812. }
  85813. this._bloomScale = value;
  85814. // recreate bloom and dispose old as this setting is not dynamic
  85815. this._rebuildBloom();
  85816. this._buildPipeline();
  85817. },
  85818. enumerable: true,
  85819. configurable: true
  85820. });
  85821. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  85822. get: function () {
  85823. return this._bloomEnabled;
  85824. },
  85825. /**
  85826. * Enable or disable the bloom from the pipeline
  85827. */
  85828. set: function (enabled) {
  85829. if (this._bloomEnabled === enabled) {
  85830. return;
  85831. }
  85832. this._bloomEnabled = enabled;
  85833. this._buildPipeline();
  85834. },
  85835. enumerable: true,
  85836. configurable: true
  85837. });
  85838. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  85839. // recreate bloom and dispose old as this setting is not dynamic
  85840. var oldBloom = this.bloom;
  85841. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  85842. this.bloom.threshold = oldBloom.threshold;
  85843. for (var i = 0; i < this._cameras.length; i++) {
  85844. oldBloom.disposeEffects(this._cameras[i]);
  85845. }
  85846. };
  85847. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  85848. /**
  85849. * If the depth of field is enabled.
  85850. */
  85851. get: function () {
  85852. return this._depthOfFieldEnabled;
  85853. },
  85854. set: function (enabled) {
  85855. if (this._depthOfFieldEnabled === enabled) {
  85856. return;
  85857. }
  85858. this._depthOfFieldEnabled = enabled;
  85859. this._buildPipeline();
  85860. },
  85861. enumerable: true,
  85862. configurable: true
  85863. });
  85864. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  85865. /**
  85866. * Blur level of the depth of field effect. (Higher blur will effect performance)
  85867. */
  85868. get: function () {
  85869. return this._depthOfFieldBlurLevel;
  85870. },
  85871. set: function (value) {
  85872. if (this._depthOfFieldBlurLevel === value) {
  85873. return;
  85874. }
  85875. this._depthOfFieldBlurLevel = value;
  85876. // recreate dof and dispose old as this setting is not dynamic
  85877. var oldDof = this.depthOfField;
  85878. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  85879. this.depthOfField.focalLength = oldDof.focalLength;
  85880. this.depthOfField.focusDistance = oldDof.focusDistance;
  85881. this.depthOfField.fStop = oldDof.fStop;
  85882. this.depthOfField.lensSize = oldDof.lensSize;
  85883. for (var i = 0; i < this._cameras.length; i++) {
  85884. oldDof.disposeEffects(this._cameras[i]);
  85885. }
  85886. this._buildPipeline();
  85887. },
  85888. enumerable: true,
  85889. configurable: true
  85890. });
  85891. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  85892. get: function () {
  85893. return this._fxaaEnabled;
  85894. },
  85895. /**
  85896. * If the anti aliasing is enabled.
  85897. */
  85898. set: function (enabled) {
  85899. if (this._fxaaEnabled === enabled) {
  85900. return;
  85901. }
  85902. this._fxaaEnabled = enabled;
  85903. this._buildPipeline();
  85904. },
  85905. enumerable: true,
  85906. configurable: true
  85907. });
  85908. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  85909. get: function () {
  85910. return this._samples;
  85911. },
  85912. /**
  85913. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  85914. */
  85915. set: function (sampleCount) {
  85916. if (this._samples === sampleCount) {
  85917. return;
  85918. }
  85919. this._samples = sampleCount;
  85920. this._buildPipeline();
  85921. },
  85922. enumerable: true,
  85923. configurable: true
  85924. });
  85925. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  85926. get: function () {
  85927. return this._imageProcessingEnabled;
  85928. },
  85929. /**
  85930. * If image processing is enabled.
  85931. */
  85932. set: function (enabled) {
  85933. if (this._imageProcessingEnabled === enabled) {
  85934. return;
  85935. }
  85936. this._imageProcessingEnabled = enabled;
  85937. this._buildPipeline();
  85938. },
  85939. enumerable: true,
  85940. configurable: true
  85941. });
  85942. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  85943. get: function () {
  85944. return this._glowLayer == null;
  85945. },
  85946. /**
  85947. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  85948. */
  85949. set: function (enabled) {
  85950. if (enabled && !this._glowLayer) {
  85951. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  85952. }
  85953. else if (!enabled && this._glowLayer) {
  85954. this._glowLayer.dispose();
  85955. this._glowLayer = null;
  85956. }
  85957. },
  85958. enumerable: true,
  85959. configurable: true
  85960. });
  85961. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  85962. get: function () {
  85963. return this._chromaticAberrationEnabled;
  85964. },
  85965. /**
  85966. * Enable or disable the chromaticAberration process from the pipeline
  85967. */
  85968. set: function (enabled) {
  85969. if (this._chromaticAberrationEnabled === enabled) {
  85970. return;
  85971. }
  85972. this._chromaticAberrationEnabled = enabled;
  85973. this._buildPipeline();
  85974. },
  85975. enumerable: true,
  85976. configurable: true
  85977. });
  85978. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  85979. get: function () {
  85980. return this._grainEnabled;
  85981. },
  85982. /**
  85983. * Enable or disable the grain process from the pipeline
  85984. */
  85985. set: function (enabled) {
  85986. if (this._grainEnabled === enabled) {
  85987. return;
  85988. }
  85989. this._grainEnabled = enabled;
  85990. this._buildPipeline();
  85991. },
  85992. enumerable: true,
  85993. configurable: true
  85994. });
  85995. /**
  85996. * Force the compilation of the entire pipeline.
  85997. */
  85998. DefaultRenderingPipeline.prototype.prepare = function () {
  85999. var previousState = this._buildAllowed;
  86000. this._buildAllowed = true;
  86001. this._buildPipeline();
  86002. this._buildAllowed = previousState;
  86003. };
  86004. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  86005. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  86006. if (this._hasCleared) {
  86007. postProcess.autoClear = false;
  86008. }
  86009. else {
  86010. postProcess.autoClear = true;
  86011. this._scene.autoClear = false;
  86012. this._hasCleared = true;
  86013. }
  86014. if (!skipTextureSharing) {
  86015. if (this._prevPrevPostProcess) {
  86016. postProcess.shareOutputWith(this._prevPrevPostProcess);
  86017. }
  86018. else {
  86019. postProcess.useOwnOutput();
  86020. }
  86021. if (this._prevPostProcess) {
  86022. this._prevPrevPostProcess = this._prevPostProcess;
  86023. }
  86024. this._prevPostProcess = postProcess;
  86025. }
  86026. };
  86027. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  86028. var _this = this;
  86029. if (!this._buildAllowed) {
  86030. return;
  86031. }
  86032. this._scene.autoClear = true;
  86033. var engine = this._scene.getEngine();
  86034. this._disposePostProcesses();
  86035. if (this._cameras !== null) {
  86036. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  86037. // get back cameras to be used to reattach pipeline
  86038. this._cameras = this._camerasToBeAttached.slice();
  86039. }
  86040. this._reset();
  86041. this._prevPostProcess = null;
  86042. this._prevPrevPostProcess = null;
  86043. this._hasCleared = false;
  86044. if (this.depthOfFieldEnabled) {
  86045. // Multi camera suport
  86046. if (this._cameras.length > 1) {
  86047. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  86048. var camera = _a[_i];
  86049. var depthRenderer = this._scene.enableDepthRenderer(camera);
  86050. depthRenderer.useOnlyInActiveCamera = true;
  86051. }
  86052. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  86053. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  86054. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  86055. }
  86056. });
  86057. }
  86058. else {
  86059. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  86060. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  86061. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  86062. }
  86063. if (!this.depthOfField._isReady()) {
  86064. this.depthOfField._updateEffects();
  86065. }
  86066. this.addEffect(this.depthOfField);
  86067. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  86068. }
  86069. else {
  86070. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  86071. }
  86072. if (this.bloomEnabled) {
  86073. if (!this.bloom._isReady()) {
  86074. this.bloom._updateEffects();
  86075. }
  86076. this.addEffect(this.bloom);
  86077. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  86078. }
  86079. if (this._imageProcessingEnabled) {
  86080. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  86081. if (this._hdr) {
  86082. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  86083. this._setAutoClearAndTextureSharing(this.imageProcessing);
  86084. }
  86085. else {
  86086. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  86087. }
  86088. }
  86089. if (this.sharpenEnabled) {
  86090. if (!this.sharpen.isReady()) {
  86091. this.sharpen.updateEffect();
  86092. }
  86093. this.addEffect(this._sharpenEffect);
  86094. this._setAutoClearAndTextureSharing(this.sharpen);
  86095. }
  86096. if (this.grainEnabled) {
  86097. if (!this.grain.isReady()) {
  86098. this.grain.updateEffect();
  86099. }
  86100. this.addEffect(this._grainEffect);
  86101. this._setAutoClearAndTextureSharing(this.grain);
  86102. }
  86103. if (this.chromaticAberrationEnabled) {
  86104. if (!this.chromaticAberration.isReady()) {
  86105. this.chromaticAberration.updateEffect();
  86106. }
  86107. this.addEffect(this._chromaticAberrationEffect);
  86108. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  86109. }
  86110. if (this.fxaaEnabled) {
  86111. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  86112. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  86113. this._setAutoClearAndTextureSharing(this.fxaa, true);
  86114. }
  86115. if (this._cameras !== null) {
  86116. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  86117. }
  86118. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  86119. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  86120. }
  86121. };
  86122. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  86123. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  86124. for (var i = 0; i < this._cameras.length; i++) {
  86125. var camera = this._cameras[i];
  86126. if (this.imageProcessing) {
  86127. this.imageProcessing.dispose(camera);
  86128. }
  86129. if (this.fxaa) {
  86130. this.fxaa.dispose(camera);
  86131. }
  86132. // These are created in the constructor and should not be disposed on every pipeline change
  86133. if (disposeNonRecreated) {
  86134. if (this.sharpen) {
  86135. this.sharpen.dispose(camera);
  86136. }
  86137. if (this.depthOfField) {
  86138. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  86139. this.depthOfField.disposeEffects(camera);
  86140. }
  86141. if (this.bloom) {
  86142. this.bloom.disposeEffects(camera);
  86143. }
  86144. if (this.chromaticAberration) {
  86145. this.chromaticAberration.dispose(camera);
  86146. }
  86147. if (this.grain) {
  86148. this.grain.dispose(camera);
  86149. }
  86150. if (this._glowLayer) {
  86151. this._glowLayer.dispose();
  86152. }
  86153. }
  86154. }
  86155. this.imageProcessing = null;
  86156. this.fxaa = null;
  86157. if (disposeNonRecreated) {
  86158. this.sharpen = null;
  86159. this._sharpenEffect = null;
  86160. this.depthOfField = null;
  86161. this.bloom = null;
  86162. this.chromaticAberration = null;
  86163. this._chromaticAberrationEffect = null;
  86164. this.grain = null;
  86165. this._grainEffect = null;
  86166. this._glowLayer = null;
  86167. }
  86168. };
  86169. /**
  86170. * Adds a camera to the pipeline
  86171. * @param camera the camera to be added
  86172. */
  86173. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  86174. this._camerasToBeAttached.push(camera);
  86175. this._buildPipeline();
  86176. };
  86177. /**
  86178. * Removes a camera from the pipeline
  86179. * @param camera the camera to remove
  86180. */
  86181. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  86182. var index = this._camerasToBeAttached.indexOf(camera);
  86183. this._camerasToBeAttached.splice(index, 1);
  86184. this._buildPipeline();
  86185. };
  86186. /**
  86187. * Dispose of the pipeline and stop all post processes
  86188. */
  86189. DefaultRenderingPipeline.prototype.dispose = function () {
  86190. this._disposePostProcesses(true);
  86191. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  86192. this._scene.autoClear = true;
  86193. if (this._resizeObserver) {
  86194. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  86195. this._resizeObserver = null;
  86196. }
  86197. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  86198. _super.prototype.dispose.call(this);
  86199. };
  86200. /**
  86201. * Serialize the rendering pipeline (Used when exporting)
  86202. * @returns the serialized object
  86203. */
  86204. DefaultRenderingPipeline.prototype.serialize = function () {
  86205. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  86206. serializationObject.customType = "DefaultRenderingPipeline";
  86207. return serializationObject;
  86208. };
  86209. /**
  86210. * Parse the serialized pipeline
  86211. * @param source Source pipeline.
  86212. * @param scene The scene to load the pipeline to.
  86213. * @param rootUrl The URL of the serialized pipeline.
  86214. * @returns An instantiated pipeline from the serialized object.
  86215. */
  86216. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  86217. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  86218. };
  86219. __decorate([
  86220. BABYLON.serialize()
  86221. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  86222. __decorate([
  86223. BABYLON.serialize()
  86224. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  86225. __decorate([
  86226. BABYLON.serialize()
  86227. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  86228. __decorate([
  86229. BABYLON.serialize()
  86230. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  86231. __decorate([
  86232. BABYLON.serialize()
  86233. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  86234. __decorate([
  86235. BABYLON.serialize()
  86236. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  86237. __decorate([
  86238. BABYLON.serialize()
  86239. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  86240. __decorate([
  86241. BABYLON.serialize()
  86242. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  86243. __decorate([
  86244. BABYLON.serialize()
  86245. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  86246. __decorate([
  86247. BABYLON.serialize()
  86248. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  86249. __decorate([
  86250. BABYLON.serialize()
  86251. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  86252. __decorate([
  86253. BABYLON.serialize()
  86254. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  86255. __decorate([
  86256. BABYLON.serialize()
  86257. ], DefaultRenderingPipeline.prototype, "samples", null);
  86258. __decorate([
  86259. BABYLON.serialize()
  86260. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  86261. __decorate([
  86262. BABYLON.serialize()
  86263. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  86264. __decorate([
  86265. BABYLON.serialize()
  86266. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  86267. __decorate([
  86268. BABYLON.serialize()
  86269. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  86270. return DefaultRenderingPipeline;
  86271. }(BABYLON.PostProcessRenderPipeline));
  86272. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  86273. })(BABYLON || (BABYLON = {}));
  86274. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  86275. var BABYLON;
  86276. (function (BABYLON) {
  86277. /**
  86278. * @hidden
  86279. */
  86280. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  86281. __extends(ImageProcessingConfigurationDefines, _super);
  86282. function ImageProcessingConfigurationDefines() {
  86283. var _this = _super.call(this) || this;
  86284. _this.IMAGEPROCESSING = false;
  86285. _this.VIGNETTE = false;
  86286. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  86287. _this.VIGNETTEBLENDMODEOPAQUE = false;
  86288. _this.TONEMAPPING = false;
  86289. _this.TONEMAPPING_ACES = false;
  86290. _this.CONTRAST = false;
  86291. _this.COLORCURVES = false;
  86292. _this.COLORGRADING = false;
  86293. _this.COLORGRADING3D = false;
  86294. _this.SAMPLER3DGREENDEPTH = false;
  86295. _this.SAMPLER3DBGRMAP = false;
  86296. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  86297. _this.EXPOSURE = false;
  86298. _this.rebuild();
  86299. return _this;
  86300. }
  86301. return ImageProcessingConfigurationDefines;
  86302. }(BABYLON.MaterialDefines));
  86303. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  86304. /**
  86305. * This groups together the common properties used for image processing either in direct forward pass
  86306. * or through post processing effect depending on the use of the image processing pipeline in your scene
  86307. * or not.
  86308. */
  86309. var ImageProcessingConfiguration = /** @class */ (function () {
  86310. function ImageProcessingConfiguration() {
  86311. /**
  86312. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  86313. */
  86314. this.colorCurves = new BABYLON.ColorCurves();
  86315. this._colorCurvesEnabled = false;
  86316. this._colorGradingEnabled = false;
  86317. this._colorGradingWithGreenDepth = true;
  86318. this._colorGradingBGR = true;
  86319. /** @hidden */
  86320. this._exposure = 1.0;
  86321. this._toneMappingEnabled = false;
  86322. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  86323. this._contrast = 1.0;
  86324. /**
  86325. * Vignette stretch size.
  86326. */
  86327. this.vignetteStretch = 0;
  86328. /**
  86329. * Vignette centre X Offset.
  86330. */
  86331. this.vignetteCentreX = 0;
  86332. /**
  86333. * Vignette centre Y Offset.
  86334. */
  86335. this.vignetteCentreY = 0;
  86336. /**
  86337. * Vignette weight or intensity of the vignette effect.
  86338. */
  86339. this.vignetteWeight = 1.5;
  86340. /**
  86341. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  86342. * if vignetteEnabled is set to true.
  86343. */
  86344. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  86345. /**
  86346. * Camera field of view used by the Vignette effect.
  86347. */
  86348. this.vignetteCameraFov = 0.5;
  86349. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  86350. this._vignetteEnabled = false;
  86351. this._applyByPostProcess = false;
  86352. this._isEnabled = true;
  86353. /**
  86354. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  86355. */
  86356. this.onUpdateParameters = new BABYLON.Observable();
  86357. }
  86358. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  86359. /**
  86360. * Gets wether the color curves effect is enabled.
  86361. */
  86362. get: function () {
  86363. return this._colorCurvesEnabled;
  86364. },
  86365. /**
  86366. * Sets wether the color curves effect is enabled.
  86367. */
  86368. set: function (value) {
  86369. if (this._colorCurvesEnabled === value) {
  86370. return;
  86371. }
  86372. this._colorCurvesEnabled = value;
  86373. this._updateParameters();
  86374. },
  86375. enumerable: true,
  86376. configurable: true
  86377. });
  86378. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  86379. /**
  86380. * Gets wether the color grading effect is enabled.
  86381. */
  86382. get: function () {
  86383. return this._colorGradingEnabled;
  86384. },
  86385. /**
  86386. * Sets wether the color grading effect is enabled.
  86387. */
  86388. set: function (value) {
  86389. if (this._colorGradingEnabled === value) {
  86390. return;
  86391. }
  86392. this._colorGradingEnabled = value;
  86393. this._updateParameters();
  86394. },
  86395. enumerable: true,
  86396. configurable: true
  86397. });
  86398. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  86399. /**
  86400. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  86401. */
  86402. get: function () {
  86403. return this._colorGradingWithGreenDepth;
  86404. },
  86405. /**
  86406. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  86407. */
  86408. set: function (value) {
  86409. if (this._colorGradingWithGreenDepth === value) {
  86410. return;
  86411. }
  86412. this._colorGradingWithGreenDepth = value;
  86413. this._updateParameters();
  86414. },
  86415. enumerable: true,
  86416. configurable: true
  86417. });
  86418. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  86419. /**
  86420. * Gets wether the color grading texture contains BGR values.
  86421. */
  86422. get: function () {
  86423. return this._colorGradingBGR;
  86424. },
  86425. /**
  86426. * Sets wether the color grading texture contains BGR values.
  86427. */
  86428. set: function (value) {
  86429. if (this._colorGradingBGR === value) {
  86430. return;
  86431. }
  86432. this._colorGradingBGR = value;
  86433. this._updateParameters();
  86434. },
  86435. enumerable: true,
  86436. configurable: true
  86437. });
  86438. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  86439. /**
  86440. * Gets the Exposure used in the effect.
  86441. */
  86442. get: function () {
  86443. return this._exposure;
  86444. },
  86445. /**
  86446. * Sets the Exposure used in the effect.
  86447. */
  86448. set: function (value) {
  86449. if (this._exposure === value) {
  86450. return;
  86451. }
  86452. this._exposure = value;
  86453. this._updateParameters();
  86454. },
  86455. enumerable: true,
  86456. configurable: true
  86457. });
  86458. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  86459. /**
  86460. * Gets wether the tone mapping effect is enabled.
  86461. */
  86462. get: function () {
  86463. return this._toneMappingEnabled;
  86464. },
  86465. /**
  86466. * Sets wether the tone mapping effect is enabled.
  86467. */
  86468. set: function (value) {
  86469. if (this._toneMappingEnabled === value) {
  86470. return;
  86471. }
  86472. this._toneMappingEnabled = value;
  86473. this._updateParameters();
  86474. },
  86475. enumerable: true,
  86476. configurable: true
  86477. });
  86478. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  86479. /**
  86480. * Gets the type of tone mapping effect.
  86481. */
  86482. get: function () {
  86483. return this._toneMappingType;
  86484. },
  86485. /**
  86486. * Sets the type of tone mapping effect used in BabylonJS.
  86487. */
  86488. set: function (value) {
  86489. if (this._toneMappingType === value) {
  86490. return;
  86491. }
  86492. this._toneMappingType = value;
  86493. this._updateParameters();
  86494. },
  86495. enumerable: true,
  86496. configurable: true
  86497. });
  86498. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  86499. /**
  86500. * Gets the contrast used in the effect.
  86501. */
  86502. get: function () {
  86503. return this._contrast;
  86504. },
  86505. /**
  86506. * Sets the contrast used in the effect.
  86507. */
  86508. set: function (value) {
  86509. if (this._contrast === value) {
  86510. return;
  86511. }
  86512. this._contrast = value;
  86513. this._updateParameters();
  86514. },
  86515. enumerable: true,
  86516. configurable: true
  86517. });
  86518. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  86519. /**
  86520. * Gets the vignette blend mode allowing different kind of effect.
  86521. */
  86522. get: function () {
  86523. return this._vignetteBlendMode;
  86524. },
  86525. /**
  86526. * Sets the vignette blend mode allowing different kind of effect.
  86527. */
  86528. set: function (value) {
  86529. if (this._vignetteBlendMode === value) {
  86530. return;
  86531. }
  86532. this._vignetteBlendMode = value;
  86533. this._updateParameters();
  86534. },
  86535. enumerable: true,
  86536. configurable: true
  86537. });
  86538. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  86539. /**
  86540. * Gets wether the vignette effect is enabled.
  86541. */
  86542. get: function () {
  86543. return this._vignetteEnabled;
  86544. },
  86545. /**
  86546. * Sets wether the vignette effect is enabled.
  86547. */
  86548. set: function (value) {
  86549. if (this._vignetteEnabled === value) {
  86550. return;
  86551. }
  86552. this._vignetteEnabled = value;
  86553. this._updateParameters();
  86554. },
  86555. enumerable: true,
  86556. configurable: true
  86557. });
  86558. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  86559. /**
  86560. * Gets wether the image processing is applied through a post process or not.
  86561. */
  86562. get: function () {
  86563. return this._applyByPostProcess;
  86564. },
  86565. /**
  86566. * Sets wether the image processing is applied through a post process or not.
  86567. */
  86568. set: function (value) {
  86569. if (this._applyByPostProcess === value) {
  86570. return;
  86571. }
  86572. this._applyByPostProcess = value;
  86573. this._updateParameters();
  86574. },
  86575. enumerable: true,
  86576. configurable: true
  86577. });
  86578. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  86579. /**
  86580. * Gets wether the image processing is enabled or not.
  86581. */
  86582. get: function () {
  86583. return this._isEnabled;
  86584. },
  86585. /**
  86586. * Sets wether the image processing is enabled or not.
  86587. */
  86588. set: function (value) {
  86589. if (this._isEnabled === value) {
  86590. return;
  86591. }
  86592. this._isEnabled = value;
  86593. this._updateParameters();
  86594. },
  86595. enumerable: true,
  86596. configurable: true
  86597. });
  86598. /**
  86599. * Method called each time the image processing information changes requires to recompile the effect.
  86600. */
  86601. ImageProcessingConfiguration.prototype._updateParameters = function () {
  86602. this.onUpdateParameters.notifyObservers(this);
  86603. };
  86604. /**
  86605. * Gets the current class name.
  86606. * @return "ImageProcessingConfiguration"
  86607. */
  86608. ImageProcessingConfiguration.prototype.getClassName = function () {
  86609. return "ImageProcessingConfiguration";
  86610. };
  86611. /**
  86612. * Prepare the list of uniforms associated with the Image Processing effects.
  86613. * @param uniforms The list of uniforms used in the effect
  86614. * @param defines the list of defines currently in use
  86615. */
  86616. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  86617. if (defines.EXPOSURE) {
  86618. uniforms.push("exposureLinear");
  86619. }
  86620. if (defines.CONTRAST) {
  86621. uniforms.push("contrast");
  86622. }
  86623. if (defines.COLORGRADING) {
  86624. uniforms.push("colorTransformSettings");
  86625. }
  86626. if (defines.VIGNETTE) {
  86627. uniforms.push("vInverseScreenSize");
  86628. uniforms.push("vignetteSettings1");
  86629. uniforms.push("vignetteSettings2");
  86630. }
  86631. if (defines.COLORCURVES) {
  86632. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  86633. }
  86634. };
  86635. /**
  86636. * Prepare the list of samplers associated with the Image Processing effects.
  86637. * @param samplersList The list of uniforms used in the effect
  86638. * @param defines the list of defines currently in use
  86639. */
  86640. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  86641. if (defines.COLORGRADING) {
  86642. samplersList.push("txColorTransform");
  86643. }
  86644. };
  86645. /**
  86646. * Prepare the list of defines associated to the shader.
  86647. * @param defines the list of defines to complete
  86648. * @param forPostProcess Define if we are currently in post process mode or not
  86649. */
  86650. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  86651. if (forPostProcess === void 0) { forPostProcess = false; }
  86652. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  86653. defines.VIGNETTE = false;
  86654. defines.TONEMAPPING = false;
  86655. defines.TONEMAPPING_ACES = false;
  86656. defines.CONTRAST = false;
  86657. defines.EXPOSURE = false;
  86658. defines.COLORCURVES = false;
  86659. defines.COLORGRADING = false;
  86660. defines.COLORGRADING3D = false;
  86661. defines.IMAGEPROCESSING = false;
  86662. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  86663. return;
  86664. }
  86665. defines.VIGNETTE = this.vignetteEnabled;
  86666. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  86667. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  86668. defines.TONEMAPPING = this.toneMappingEnabled;
  86669. switch (this._toneMappingType) {
  86670. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  86671. defines.TONEMAPPING_ACES = true;
  86672. break;
  86673. }
  86674. defines.CONTRAST = (this.contrast !== 1.0);
  86675. defines.EXPOSURE = (this.exposure !== 1.0);
  86676. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  86677. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  86678. if (defines.COLORGRADING) {
  86679. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  86680. }
  86681. else {
  86682. defines.COLORGRADING3D = false;
  86683. }
  86684. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  86685. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  86686. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  86687. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  86688. };
  86689. /**
  86690. * Returns true if all the image processing information are ready.
  86691. * @returns True if ready, otherwise, false
  86692. */
  86693. ImageProcessingConfiguration.prototype.isReady = function () {
  86694. // Color Grading texure can not be none blocking.
  86695. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  86696. };
  86697. /**
  86698. * Binds the image processing to the shader.
  86699. * @param effect The effect to bind to
  86700. * @param aspectRatio Define the current aspect ratio of the effect
  86701. */
  86702. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  86703. if (aspectRatio === void 0) { aspectRatio = 1; }
  86704. // Color Curves
  86705. if (this._colorCurvesEnabled && this.colorCurves) {
  86706. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  86707. }
  86708. // Vignette
  86709. if (this._vignetteEnabled) {
  86710. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  86711. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  86712. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  86713. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  86714. var vignetteScaleX = vignetteScaleY * aspectRatio;
  86715. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  86716. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  86717. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  86718. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  86719. var vignettePower = -2.0 * this.vignetteWeight;
  86720. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  86721. }
  86722. // Exposure
  86723. effect.setFloat("exposureLinear", this.exposure);
  86724. // Contrast
  86725. effect.setFloat("contrast", this.contrast);
  86726. // Color transform settings
  86727. if (this.colorGradingTexture) {
  86728. effect.setTexture("txColorTransform", this.colorGradingTexture);
  86729. var textureSize = this.colorGradingTexture.getSize().height;
  86730. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  86731. 0.5 / textureSize, // textureOffset
  86732. textureSize, // textureSize
  86733. this.colorGradingTexture.level // weight
  86734. );
  86735. }
  86736. };
  86737. /**
  86738. * Clones the current image processing instance.
  86739. * @return The cloned image processing
  86740. */
  86741. ImageProcessingConfiguration.prototype.clone = function () {
  86742. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  86743. };
  86744. /**
  86745. * Serializes the current image processing instance to a json representation.
  86746. * @return a JSON representation
  86747. */
  86748. ImageProcessingConfiguration.prototype.serialize = function () {
  86749. return BABYLON.SerializationHelper.Serialize(this);
  86750. };
  86751. /**
  86752. * Parses the image processing from a json representation.
  86753. * @param source the JSON source to parse
  86754. * @return The parsed image processing
  86755. */
  86756. ImageProcessingConfiguration.Parse = function (source) {
  86757. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  86758. };
  86759. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  86760. /**
  86761. * Used to apply the vignette as a mix with the pixel color.
  86762. */
  86763. get: function () {
  86764. return this._VIGNETTEMODE_MULTIPLY;
  86765. },
  86766. enumerable: true,
  86767. configurable: true
  86768. });
  86769. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  86770. /**
  86771. * Used to apply the vignette as a replacement of the pixel color.
  86772. */
  86773. get: function () {
  86774. return this._VIGNETTEMODE_OPAQUE;
  86775. },
  86776. enumerable: true,
  86777. configurable: true
  86778. });
  86779. /**
  86780. * Default tone mapping applied in BabylonJS.
  86781. */
  86782. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  86783. /**
  86784. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  86785. * to other engines rendering to increase portability.
  86786. */
  86787. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  86788. // Static constants associated to the image processing.
  86789. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  86790. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  86791. __decorate([
  86792. BABYLON.serializeAsColorCurves()
  86793. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  86794. __decorate([
  86795. BABYLON.serialize()
  86796. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  86797. __decorate([
  86798. BABYLON.serializeAsTexture()
  86799. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  86800. __decorate([
  86801. BABYLON.serialize()
  86802. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  86803. __decorate([
  86804. BABYLON.serialize()
  86805. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  86806. __decorate([
  86807. BABYLON.serialize()
  86808. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  86809. __decorate([
  86810. BABYLON.serialize()
  86811. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  86812. __decorate([
  86813. BABYLON.serialize()
  86814. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  86815. __decorate([
  86816. BABYLON.serialize()
  86817. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  86818. __decorate([
  86819. BABYLON.serialize()
  86820. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  86821. __decorate([
  86822. BABYLON.serialize()
  86823. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  86824. __decorate([
  86825. BABYLON.serialize()
  86826. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  86827. __decorate([
  86828. BABYLON.serialize()
  86829. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  86830. __decorate([
  86831. BABYLON.serialize()
  86832. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  86833. __decorate([
  86834. BABYLON.serializeAsColor4()
  86835. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  86836. __decorate([
  86837. BABYLON.serialize()
  86838. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  86839. __decorate([
  86840. BABYLON.serialize()
  86841. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  86842. __decorate([
  86843. BABYLON.serialize()
  86844. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  86845. __decorate([
  86846. BABYLON.serialize()
  86847. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  86848. __decorate([
  86849. BABYLON.serialize()
  86850. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  86851. return ImageProcessingConfiguration;
  86852. }());
  86853. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  86854. })(BABYLON || (BABYLON = {}));
  86855. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  86856. var BABYLON;
  86857. (function (BABYLON) {
  86858. /**
  86859. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  86860. * It can help converting any input color in a desired output one. This can then be used to create effects
  86861. * from sepia, black and white to sixties or futuristic rendering...
  86862. *
  86863. * The only supported format is currently 3dl.
  86864. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table
  86865. */
  86866. var ColorGradingTexture = /** @class */ (function (_super) {
  86867. __extends(ColorGradingTexture, _super);
  86868. /**
  86869. * Instantiates a ColorGradingTexture from the following parameters.
  86870. *
  86871. * @param url The location of the color gradind data (currently only supporting 3dl)
  86872. * @param scene The scene the texture will be used in
  86873. */
  86874. function ColorGradingTexture(url, scene) {
  86875. var _this = _super.call(this, scene) || this;
  86876. if (!url) {
  86877. return _this;
  86878. }
  86879. _this._engine = scene.getEngine();
  86880. _this._textureMatrix = BABYLON.Matrix.Identity();
  86881. _this.name = url;
  86882. _this.url = url;
  86883. _this.hasAlpha = false;
  86884. _this.isCube = false;
  86885. _this.is3D = _this._engine.webGLVersion > 1;
  86886. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86887. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86888. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86889. _this.anisotropicFilteringLevel = 1;
  86890. _this._texture = _this._getFromCache(url, true);
  86891. if (!_this._texture) {
  86892. if (!scene.useDelayedTextureLoading) {
  86893. _this.loadTexture();
  86894. }
  86895. else {
  86896. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  86897. }
  86898. }
  86899. return _this;
  86900. }
  86901. /**
  86902. * Returns the texture matrix used in most of the material.
  86903. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  86904. */
  86905. ColorGradingTexture.prototype.getTextureMatrix = function () {
  86906. return this._textureMatrix;
  86907. };
  86908. /**
  86909. * Occurs when the file being loaded is a .3dl LUT file.
  86910. */
  86911. ColorGradingTexture.prototype.load3dlTexture = function () {
  86912. var engine = this._engine;
  86913. var texture;
  86914. if (engine.webGLVersion === 1) {
  86915. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86916. }
  86917. else {
  86918. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86919. }
  86920. this._texture = texture;
  86921. var callback = function (text) {
  86922. if (typeof text !== "string") {
  86923. return;
  86924. }
  86925. var data = null;
  86926. var tempData = null;
  86927. var line;
  86928. var lines = text.split('\n');
  86929. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  86930. var maxColor = 0;
  86931. for (var i = 0; i < lines.length; i++) {
  86932. line = lines[i];
  86933. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  86934. continue;
  86935. if (line.indexOf('#') === 0)
  86936. continue;
  86937. var words = line.split(" ");
  86938. if (size === 0) {
  86939. // Number of space + one
  86940. size = words.length;
  86941. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  86942. tempData = new Float32Array(size * size * size * 4);
  86943. continue;
  86944. }
  86945. if (size != 0) {
  86946. var r = Math.max(parseInt(words[0]), 0);
  86947. var g = Math.max(parseInt(words[1]), 0);
  86948. var b = Math.max(parseInt(words[2]), 0);
  86949. maxColor = Math.max(r, maxColor);
  86950. maxColor = Math.max(g, maxColor);
  86951. maxColor = Math.max(b, maxColor);
  86952. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  86953. if (tempData) {
  86954. tempData[pixelStorageIndex + 0] = r;
  86955. tempData[pixelStorageIndex + 1] = g;
  86956. tempData[pixelStorageIndex + 2] = b;
  86957. }
  86958. pixelIndexSlice++;
  86959. if (pixelIndexSlice % size == 0) {
  86960. pixelIndexH++;
  86961. pixelIndexSlice = 0;
  86962. if (pixelIndexH % size == 0) {
  86963. pixelIndexW++;
  86964. pixelIndexH = 0;
  86965. }
  86966. }
  86967. }
  86968. }
  86969. if (tempData && data) {
  86970. for (var i = 0; i < tempData.length; i++) {
  86971. if (i > 0 && (i + 1) % 4 === 0) {
  86972. data[i] = 255;
  86973. }
  86974. else {
  86975. var value = tempData[i];
  86976. data[i] = (value / maxColor * 255);
  86977. }
  86978. }
  86979. }
  86980. if (texture.is3D) {
  86981. texture.updateSize(size, size, size);
  86982. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  86983. }
  86984. else {
  86985. texture.updateSize(size * size, size);
  86986. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  86987. }
  86988. };
  86989. var scene = this.getScene();
  86990. if (scene) {
  86991. scene._loadFile(this.url, callback);
  86992. }
  86993. else {
  86994. this._engine._loadFile(this.url, callback);
  86995. }
  86996. return this._texture;
  86997. };
  86998. /**
  86999. * Starts the loading process of the texture.
  87000. */
  87001. ColorGradingTexture.prototype.loadTexture = function () {
  87002. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  87003. this.load3dlTexture();
  87004. }
  87005. };
  87006. /**
  87007. * Clones the color gradind texture.
  87008. */
  87009. ColorGradingTexture.prototype.clone = function () {
  87010. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  87011. // Base texture
  87012. newTexture.level = this.level;
  87013. return newTexture;
  87014. };
  87015. /**
  87016. * Called during delayed load for textures.
  87017. */
  87018. ColorGradingTexture.prototype.delayLoad = function () {
  87019. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  87020. return;
  87021. }
  87022. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  87023. this._texture = this._getFromCache(this.url, true);
  87024. if (!this._texture) {
  87025. this.loadTexture();
  87026. }
  87027. };
  87028. /**
  87029. * Parses a color grading texture serialized by Babylon.
  87030. * @param parsedTexture The texture information being parsedTexture
  87031. * @param scene The scene to load the texture in
  87032. * @param rootUrl The root url of the data assets to load
  87033. * @return A color gradind texture
  87034. */
  87035. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  87036. var texture = null;
  87037. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  87038. texture = new ColorGradingTexture(parsedTexture.name, scene);
  87039. texture.name = parsedTexture.name;
  87040. texture.level = parsedTexture.level;
  87041. }
  87042. return texture;
  87043. };
  87044. /**
  87045. * Serializes the LUT texture to json format.
  87046. */
  87047. ColorGradingTexture.prototype.serialize = function () {
  87048. if (!this.name) {
  87049. return null;
  87050. }
  87051. var serializationObject = {};
  87052. serializationObject.name = this.name;
  87053. serializationObject.level = this.level;
  87054. serializationObject.customType = "BABYLON.ColorGradingTexture";
  87055. return serializationObject;
  87056. };
  87057. /**
  87058. * Empty line regex stored for GC.
  87059. */
  87060. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  87061. return ColorGradingTexture;
  87062. }(BABYLON.BaseTexture));
  87063. BABYLON.ColorGradingTexture = ColorGradingTexture;
  87064. })(BABYLON || (BABYLON = {}));
  87065. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  87066. var BABYLON;
  87067. (function (BABYLON) {
  87068. /**
  87069. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  87070. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  87071. * 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;
  87072. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  87073. */
  87074. var ColorCurves = /** @class */ (function () {
  87075. function ColorCurves() {
  87076. this._dirty = true;
  87077. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  87078. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  87079. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  87080. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  87081. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  87082. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  87083. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  87084. this._globalHue = 30;
  87085. this._globalDensity = 0;
  87086. this._globalSaturation = 0;
  87087. this._globalExposure = 0;
  87088. this._highlightsHue = 30;
  87089. this._highlightsDensity = 0;
  87090. this._highlightsSaturation = 0;
  87091. this._highlightsExposure = 0;
  87092. this._midtonesHue = 30;
  87093. this._midtonesDensity = 0;
  87094. this._midtonesSaturation = 0;
  87095. this._midtonesExposure = 0;
  87096. this._shadowsHue = 30;
  87097. this._shadowsDensity = 0;
  87098. this._shadowsSaturation = 0;
  87099. this._shadowsExposure = 0;
  87100. }
  87101. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  87102. /**
  87103. * Gets the global Hue value.
  87104. * 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).
  87105. */
  87106. get: function () {
  87107. return this._globalHue;
  87108. },
  87109. /**
  87110. * Sets the global Hue value.
  87111. * 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).
  87112. */
  87113. set: function (value) {
  87114. this._globalHue = value;
  87115. this._dirty = true;
  87116. },
  87117. enumerable: true,
  87118. configurable: true
  87119. });
  87120. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  87121. /**
  87122. * Gets the global Density value.
  87123. * 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.
  87124. * Values less than zero provide a filter of opposite hue.
  87125. */
  87126. get: function () {
  87127. return this._globalDensity;
  87128. },
  87129. /**
  87130. * Sets the global Density value.
  87131. * 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.
  87132. * Values less than zero provide a filter of opposite hue.
  87133. */
  87134. set: function (value) {
  87135. this._globalDensity = value;
  87136. this._dirty = true;
  87137. },
  87138. enumerable: true,
  87139. configurable: true
  87140. });
  87141. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  87142. /**
  87143. * Gets the global Saturation value.
  87144. * 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.
  87145. */
  87146. get: function () {
  87147. return this._globalSaturation;
  87148. },
  87149. /**
  87150. * Sets the global Saturation value.
  87151. * 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.
  87152. */
  87153. set: function (value) {
  87154. this._globalSaturation = value;
  87155. this._dirty = true;
  87156. },
  87157. enumerable: true,
  87158. configurable: true
  87159. });
  87160. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  87161. /**
  87162. * Gets the global Exposure value.
  87163. * 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.
  87164. */
  87165. get: function () {
  87166. return this._globalExposure;
  87167. },
  87168. /**
  87169. * Sets the global Exposure value.
  87170. * 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.
  87171. */
  87172. set: function (value) {
  87173. this._globalExposure = value;
  87174. this._dirty = true;
  87175. },
  87176. enumerable: true,
  87177. configurable: true
  87178. });
  87179. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  87180. /**
  87181. * Gets the highlights Hue value.
  87182. * 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).
  87183. */
  87184. get: function () {
  87185. return this._highlightsHue;
  87186. },
  87187. /**
  87188. * Sets the highlights Hue value.
  87189. * 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).
  87190. */
  87191. set: function (value) {
  87192. this._highlightsHue = value;
  87193. this._dirty = true;
  87194. },
  87195. enumerable: true,
  87196. configurable: true
  87197. });
  87198. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  87199. /**
  87200. * Gets the highlights Density value.
  87201. * 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.
  87202. * Values less than zero provide a filter of opposite hue.
  87203. */
  87204. get: function () {
  87205. return this._highlightsDensity;
  87206. },
  87207. /**
  87208. * Sets the highlights Density value.
  87209. * 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.
  87210. * Values less than zero provide a filter of opposite hue.
  87211. */
  87212. set: function (value) {
  87213. this._highlightsDensity = value;
  87214. this._dirty = true;
  87215. },
  87216. enumerable: true,
  87217. configurable: true
  87218. });
  87219. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  87220. /**
  87221. * Gets the highlights Saturation value.
  87222. * 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.
  87223. */
  87224. get: function () {
  87225. return this._highlightsSaturation;
  87226. },
  87227. /**
  87228. * Sets the highlights Saturation value.
  87229. * 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.
  87230. */
  87231. set: function (value) {
  87232. this._highlightsSaturation = value;
  87233. this._dirty = true;
  87234. },
  87235. enumerable: true,
  87236. configurable: true
  87237. });
  87238. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  87239. /**
  87240. * Gets the highlights Exposure value.
  87241. * 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.
  87242. */
  87243. get: function () {
  87244. return this._highlightsExposure;
  87245. },
  87246. /**
  87247. * Sets the highlights Exposure value.
  87248. * 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.
  87249. */
  87250. set: function (value) {
  87251. this._highlightsExposure = value;
  87252. this._dirty = true;
  87253. },
  87254. enumerable: true,
  87255. configurable: true
  87256. });
  87257. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  87258. /**
  87259. * Gets the midtones Hue value.
  87260. * 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).
  87261. */
  87262. get: function () {
  87263. return this._midtonesHue;
  87264. },
  87265. /**
  87266. * Sets the midtones Hue value.
  87267. * 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).
  87268. */
  87269. set: function (value) {
  87270. this._midtonesHue = value;
  87271. this._dirty = true;
  87272. },
  87273. enumerable: true,
  87274. configurable: true
  87275. });
  87276. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  87277. /**
  87278. * Gets the midtones Density value.
  87279. * 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.
  87280. * Values less than zero provide a filter of opposite hue.
  87281. */
  87282. get: function () {
  87283. return this._midtonesDensity;
  87284. },
  87285. /**
  87286. * Sets the midtones Density value.
  87287. * 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.
  87288. * Values less than zero provide a filter of opposite hue.
  87289. */
  87290. set: function (value) {
  87291. this._midtonesDensity = value;
  87292. this._dirty = true;
  87293. },
  87294. enumerable: true,
  87295. configurable: true
  87296. });
  87297. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  87298. /**
  87299. * Gets the midtones Saturation value.
  87300. * 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.
  87301. */
  87302. get: function () {
  87303. return this._midtonesSaturation;
  87304. },
  87305. /**
  87306. * Sets the midtones Saturation value.
  87307. * 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.
  87308. */
  87309. set: function (value) {
  87310. this._midtonesSaturation = value;
  87311. this._dirty = true;
  87312. },
  87313. enumerable: true,
  87314. configurable: true
  87315. });
  87316. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  87317. /**
  87318. * Gets the midtones Exposure value.
  87319. * 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.
  87320. */
  87321. get: function () {
  87322. return this._midtonesExposure;
  87323. },
  87324. /**
  87325. * Sets the midtones Exposure value.
  87326. * 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.
  87327. */
  87328. set: function (value) {
  87329. this._midtonesExposure = value;
  87330. this._dirty = true;
  87331. },
  87332. enumerable: true,
  87333. configurable: true
  87334. });
  87335. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  87336. /**
  87337. * Gets the shadows Hue value.
  87338. * 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).
  87339. */
  87340. get: function () {
  87341. return this._shadowsHue;
  87342. },
  87343. /**
  87344. * Sets the shadows Hue value.
  87345. * 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).
  87346. */
  87347. set: function (value) {
  87348. this._shadowsHue = value;
  87349. this._dirty = true;
  87350. },
  87351. enumerable: true,
  87352. configurable: true
  87353. });
  87354. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  87355. /**
  87356. * Gets the shadows Density value.
  87357. * 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.
  87358. * Values less than zero provide a filter of opposite hue.
  87359. */
  87360. get: function () {
  87361. return this._shadowsDensity;
  87362. },
  87363. /**
  87364. * Sets the shadows Density value.
  87365. * 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.
  87366. * Values less than zero provide a filter of opposite hue.
  87367. */
  87368. set: function (value) {
  87369. this._shadowsDensity = value;
  87370. this._dirty = true;
  87371. },
  87372. enumerable: true,
  87373. configurable: true
  87374. });
  87375. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  87376. /**
  87377. * Gets the shadows Saturation value.
  87378. * 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.
  87379. */
  87380. get: function () {
  87381. return this._shadowsSaturation;
  87382. },
  87383. /**
  87384. * Sets the shadows Saturation value.
  87385. * 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.
  87386. */
  87387. set: function (value) {
  87388. this._shadowsSaturation = value;
  87389. this._dirty = true;
  87390. },
  87391. enumerable: true,
  87392. configurable: true
  87393. });
  87394. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  87395. /**
  87396. * Gets the shadows Exposure value.
  87397. * 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.
  87398. */
  87399. get: function () {
  87400. return this._shadowsExposure;
  87401. },
  87402. /**
  87403. * Sets the shadows Exposure value.
  87404. * 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.
  87405. */
  87406. set: function (value) {
  87407. this._shadowsExposure = value;
  87408. this._dirty = true;
  87409. },
  87410. enumerable: true,
  87411. configurable: true
  87412. });
  87413. /**
  87414. * Returns the class name
  87415. * @returns The class name
  87416. */
  87417. ColorCurves.prototype.getClassName = function () {
  87418. return "ColorCurves";
  87419. };
  87420. /**
  87421. * Binds the color curves to the shader.
  87422. * @param colorCurves The color curve to bind
  87423. * @param effect The effect to bind to
  87424. * @param positiveUniform The positive uniform shader parameter
  87425. * @param neutralUniform The neutral uniform shader parameter
  87426. * @param negativeUniform The negative uniform shader parameter
  87427. */
  87428. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  87429. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  87430. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  87431. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  87432. if (colorCurves._dirty) {
  87433. colorCurves._dirty = false;
  87434. // Fill in global info.
  87435. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  87436. // Compute highlights info.
  87437. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  87438. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  87439. // Compute midtones info.
  87440. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  87441. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  87442. // Compute shadows info.
  87443. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  87444. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  87445. // Compute deltas (neutral is midtones).
  87446. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  87447. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  87448. }
  87449. if (effect) {
  87450. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  87451. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  87452. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  87453. }
  87454. };
  87455. /**
  87456. * Prepare the list of uniforms associated with the ColorCurves effects.
  87457. * @param uniformsList The list of uniforms used in the effect
  87458. */
  87459. ColorCurves.PrepareUniforms = function (uniformsList) {
  87460. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  87461. };
  87462. /**
  87463. * Returns color grading data based on a hue, density, saturation and exposure value.
  87464. * @param filterHue The hue of the color filter.
  87465. * @param filterDensity The density of the color filter.
  87466. * @param saturation The saturation.
  87467. * @param exposure The exposure.
  87468. * @param result The result data container.
  87469. */
  87470. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  87471. if (hue == null) {
  87472. return;
  87473. }
  87474. hue = ColorCurves.clamp(hue, 0, 360);
  87475. density = ColorCurves.clamp(density, -100, 100);
  87476. saturation = ColorCurves.clamp(saturation, -100, 100);
  87477. exposure = ColorCurves.clamp(exposure, -100, 100);
  87478. // Remap the slider/config filter density with non-linear mapping and also scale by half
  87479. // so that the maximum filter density is only 50% control. This provides fine control
  87480. // for small values and reasonable range.
  87481. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  87482. density *= 0.5;
  87483. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  87484. if (density < 0) {
  87485. density *= -1;
  87486. hue = (hue + 180) % 360;
  87487. }
  87488. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  87489. result.scaleToRef(2, result);
  87490. result.a = 1 + 0.01 * saturation;
  87491. };
  87492. /**
  87493. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  87494. * @param value The input slider value in range [-100,100].
  87495. * @returns Adjusted value.
  87496. */
  87497. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  87498. value /= 100;
  87499. var x = Math.abs(value);
  87500. x = Math.pow(x, 2);
  87501. if (value < 0) {
  87502. x *= -1;
  87503. }
  87504. x *= 100;
  87505. return x;
  87506. };
  87507. /**
  87508. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  87509. * @param hue The hue (H) input.
  87510. * @param saturation The saturation (S) input.
  87511. * @param brightness The brightness (B) input.
  87512. * @result An RGBA color represented as Vector4.
  87513. */
  87514. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  87515. var h = ColorCurves.clamp(hue, 0, 360);
  87516. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  87517. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  87518. if (s === 0) {
  87519. result.r = v;
  87520. result.g = v;
  87521. result.b = v;
  87522. }
  87523. else {
  87524. // sector 0 to 5
  87525. h /= 60;
  87526. var i = Math.floor(h);
  87527. // fractional part of h
  87528. var f = h - i;
  87529. var p = v * (1 - s);
  87530. var q = v * (1 - s * f);
  87531. var t = v * (1 - s * (1 - f));
  87532. switch (i) {
  87533. case 0:
  87534. result.r = v;
  87535. result.g = t;
  87536. result.b = p;
  87537. break;
  87538. case 1:
  87539. result.r = q;
  87540. result.g = v;
  87541. result.b = p;
  87542. break;
  87543. case 2:
  87544. result.r = p;
  87545. result.g = v;
  87546. result.b = t;
  87547. break;
  87548. case 3:
  87549. result.r = p;
  87550. result.g = q;
  87551. result.b = v;
  87552. break;
  87553. case 4:
  87554. result.r = t;
  87555. result.g = p;
  87556. result.b = v;
  87557. break;
  87558. default: // case 5:
  87559. result.r = v;
  87560. result.g = p;
  87561. result.b = q;
  87562. break;
  87563. }
  87564. }
  87565. result.a = 1;
  87566. };
  87567. /**
  87568. * Returns a value clamped between min and max
  87569. * @param value The value to clamp
  87570. * @param min The minimum of value
  87571. * @param max The maximum of value
  87572. * @returns The clamped value.
  87573. */
  87574. ColorCurves.clamp = function (value, min, max) {
  87575. return Math.min(Math.max(value, min), max);
  87576. };
  87577. /**
  87578. * Clones the current color curve instance.
  87579. * @return The cloned curves
  87580. */
  87581. ColorCurves.prototype.clone = function () {
  87582. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  87583. };
  87584. /**
  87585. * Serializes the current color curve instance to a json representation.
  87586. * @return a JSON representation
  87587. */
  87588. ColorCurves.prototype.serialize = function () {
  87589. return BABYLON.SerializationHelper.Serialize(this);
  87590. };
  87591. /**
  87592. * Parses the color curve from a json representation.
  87593. * @param source the JSON source to parse
  87594. * @return The parsed curves
  87595. */
  87596. ColorCurves.Parse = function (source) {
  87597. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  87598. };
  87599. __decorate([
  87600. BABYLON.serialize()
  87601. ], ColorCurves.prototype, "_globalHue", void 0);
  87602. __decorate([
  87603. BABYLON.serialize()
  87604. ], ColorCurves.prototype, "_globalDensity", void 0);
  87605. __decorate([
  87606. BABYLON.serialize()
  87607. ], ColorCurves.prototype, "_globalSaturation", void 0);
  87608. __decorate([
  87609. BABYLON.serialize()
  87610. ], ColorCurves.prototype, "_globalExposure", void 0);
  87611. __decorate([
  87612. BABYLON.serialize()
  87613. ], ColorCurves.prototype, "_highlightsHue", void 0);
  87614. __decorate([
  87615. BABYLON.serialize()
  87616. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  87617. __decorate([
  87618. BABYLON.serialize()
  87619. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  87620. __decorate([
  87621. BABYLON.serialize()
  87622. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  87623. __decorate([
  87624. BABYLON.serialize()
  87625. ], ColorCurves.prototype, "_midtonesHue", void 0);
  87626. __decorate([
  87627. BABYLON.serialize()
  87628. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  87629. __decorate([
  87630. BABYLON.serialize()
  87631. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  87632. __decorate([
  87633. BABYLON.serialize()
  87634. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  87635. return ColorCurves;
  87636. }());
  87637. BABYLON.ColorCurves = ColorCurves;
  87638. })(BABYLON || (BABYLON = {}));
  87639. //# sourceMappingURL=babylon.colorCurves.js.map
  87640. var BABYLON;
  87641. (function (BABYLON) {
  87642. /**
  87643. * Post process which applies a refractin texture
  87644. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  87645. */
  87646. var RefractionPostProcess = /** @class */ (function (_super) {
  87647. __extends(RefractionPostProcess, _super);
  87648. /**
  87649. * Initializes the RefractionPostProcess
  87650. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  87651. * @param name The name of the effect.
  87652. * @param refractionTextureUrl Url of the refraction texture to use
  87653. * @param color the base color of the refraction (used to taint the rendering)
  87654. * @param depth simulated refraction depth
  87655. * @param colorLevel the coefficient of the base color (0 to remove base color tainting)
  87656. * @param camera The camera to apply the render pass to.
  87657. * @param options The required width/height ratio to downsize to before computing the render pass.
  87658. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87659. * @param engine The engine which the post process will be applied. (default: current engine)
  87660. * @param reusable If the post process can be reused on the same frame. (default: false)
  87661. */
  87662. function RefractionPostProcess(name, refractionTextureUrl,
  87663. /** the base color of the refraction (used to taint the rendering) */
  87664. color,
  87665. /** simulated refraction depth */
  87666. depth,
  87667. /** the coefficient of the base color (0 to remove base color tainting) */
  87668. colorLevel, options, camera, samplingMode, engine, reusable) {
  87669. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  87670. _this.color = color;
  87671. _this.depth = depth;
  87672. _this.colorLevel = colorLevel;
  87673. _this._ownRefractionTexture = true;
  87674. _this.onActivateObservable.add(function (cam) {
  87675. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  87676. });
  87677. _this.onApplyObservable.add(function (effect) {
  87678. effect.setColor3("baseColor", _this.color);
  87679. effect.setFloat("depth", _this.depth);
  87680. effect.setFloat("colorLevel", _this.colorLevel);
  87681. effect.setTexture("refractionSampler", _this._refTexture);
  87682. });
  87683. return _this;
  87684. }
  87685. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  87686. /**
  87687. * Gets or sets the refraction texture
  87688. * Please note that you are responsible for disposing the texture if you set it manually
  87689. */
  87690. get: function () {
  87691. return this._refTexture;
  87692. },
  87693. set: function (value) {
  87694. if (this._refTexture && this._ownRefractionTexture) {
  87695. this._refTexture.dispose();
  87696. }
  87697. this._refTexture = value;
  87698. this._ownRefractionTexture = false;
  87699. },
  87700. enumerable: true,
  87701. configurable: true
  87702. });
  87703. // Methods
  87704. /**
  87705. * Disposes of the post process
  87706. * @param camera Camera to dispose post process on
  87707. */
  87708. RefractionPostProcess.prototype.dispose = function (camera) {
  87709. if (this._refTexture && this._ownRefractionTexture) {
  87710. this._refTexture.dispose();
  87711. this._refTexture = null;
  87712. }
  87713. _super.prototype.dispose.call(this, camera);
  87714. };
  87715. return RefractionPostProcess;
  87716. }(BABYLON.PostProcess));
  87717. BABYLON.RefractionPostProcess = RefractionPostProcess;
  87718. })(BABYLON || (BABYLON = {}));
  87719. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  87720. var BABYLON;
  87721. (function (BABYLON) {
  87722. /**
  87723. * Post process used to render in black and white
  87724. */
  87725. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  87726. __extends(BlackAndWhitePostProcess, _super);
  87727. /**
  87728. * Creates a black and white post process
  87729. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#black-and-white
  87730. * @param name The name of the effect.
  87731. * @param options The required width/height ratio to downsize to before computing the render pass.
  87732. * @param camera The camera to apply the render pass to.
  87733. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87734. * @param engine The engine which the post process will be applied. (default: current engine)
  87735. * @param reusable If the post process can be reused on the same frame. (default: false)
  87736. */
  87737. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  87738. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  87739. /**
  87740. * Linear about to convert he result to black and white (default: 1)
  87741. */
  87742. _this.degree = 1;
  87743. _this.onApplyObservable.add(function (effect) {
  87744. effect.setFloat("degree", _this.degree);
  87745. });
  87746. return _this;
  87747. }
  87748. return BlackAndWhitePostProcess;
  87749. }(BABYLON.PostProcess));
  87750. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  87751. })(BABYLON || (BABYLON = {}));
  87752. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  87753. var BABYLON;
  87754. (function (BABYLON) {
  87755. /**
  87756. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  87757. * input texture to perform effects such as edge detection or sharpening
  87758. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  87759. */
  87760. var ConvolutionPostProcess = /** @class */ (function (_super) {
  87761. __extends(ConvolutionPostProcess, _super);
  87762. /**
  87763. * Creates a new instance ConvolutionPostProcess
  87764. * @param name The name of the effect.
  87765. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  87766. * @param options The required width/height ratio to downsize to before computing the render pass.
  87767. * @param camera The camera to apply the render pass to.
  87768. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87769. * @param engine The engine which the post process will be applied. (default: current engine)
  87770. * @param reusable If the post process can be reused on the same frame. (default: false)
  87771. * @param textureType Type of textures used when performing the post process. (default: 0)
  87772. */
  87773. function ConvolutionPostProcess(name,
  87774. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  87775. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  87776. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  87777. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  87778. _this.kernel = kernel;
  87779. _this.onApply = function (effect) {
  87780. effect.setFloat2("screenSize", _this.width, _this.height);
  87781. effect.setArray("kernel", _this.kernel);
  87782. };
  87783. return _this;
  87784. }
  87785. // Statics
  87786. /**
  87787. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87788. */
  87789. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  87790. /**
  87791. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87792. */
  87793. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  87794. /**
  87795. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87796. */
  87797. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  87798. /**
  87799. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87800. */
  87801. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  87802. /**
  87803. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87804. */
  87805. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  87806. /**
  87807. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  87808. */
  87809. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  87810. return ConvolutionPostProcess;
  87811. }(BABYLON.PostProcess));
  87812. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  87813. })(BABYLON || (BABYLON = {}));
  87814. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  87815. var BABYLON;
  87816. (function (BABYLON) {
  87817. /**
  87818. * Applies a kernel filter to the image
  87819. */
  87820. var FilterPostProcess = /** @class */ (function (_super) {
  87821. __extends(FilterPostProcess, _super);
  87822. /**
  87823. *
  87824. * @param name The name of the effect.
  87825. * @param kernelMatrix The matrix to be applied to the image
  87826. * @param options The required width/height ratio to downsize to before computing the render pass.
  87827. * @param camera The camera to apply the render pass to.
  87828. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  87829. * @param engine The engine which the post process will be applied. (default: current engine)
  87830. * @param reusable If the post process can be reused on the same frame. (default: false)
  87831. */
  87832. function FilterPostProcess(name,
  87833. /** The matrix to be applied to the image */
  87834. kernelMatrix, options, camera, samplingMode, engine, reusable) {
  87835. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  87836. _this.kernelMatrix = kernelMatrix;
  87837. _this.onApply = function (effect) {
  87838. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  87839. };
  87840. return _this;
  87841. }
  87842. return FilterPostProcess;
  87843. }(BABYLON.PostProcess));
  87844. BABYLON.FilterPostProcess = FilterPostProcess;
  87845. })(BABYLON || (BABYLON = {}));
  87846. //# sourceMappingURL=babylon.filterPostProcess.js.map
  87847. var BABYLON;
  87848. (function (BABYLON) {
  87849. /**
  87850. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  87851. */
  87852. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  87853. __extends(VolumetricLightScatteringPostProcess, _super);
  87854. /**
  87855. * @constructor
  87856. * @param {string} name - The post-process name
  87857. * @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)
  87858. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  87859. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  87860. * @param {number} samples - The post-process quality, default 100
  87861. * @param {number} samplingMode - The post-process filtering mode
  87862. * @param {BABYLON.Engine} engine - The babylon engine
  87863. * @param {boolean} reusable - If the post-process is reusable
  87864. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  87865. */
  87866. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  87867. if (samples === void 0) { samples = 100; }
  87868. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87869. 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;
  87870. _this._screenCoordinates = BABYLON.Vector2.Zero();
  87871. /**
  87872. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  87873. */
  87874. _this.customMeshPosition = BABYLON.Vector3.Zero();
  87875. /**
  87876. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  87877. */
  87878. _this.useCustomMeshPosition = false;
  87879. /**
  87880. * If the post-process should inverse the light scattering direction
  87881. */
  87882. _this.invert = true;
  87883. /**
  87884. * Array containing the excluded meshes not rendered in the internal pass
  87885. */
  87886. _this.excludedMeshes = new Array();
  87887. /**
  87888. * Controls the overall intensity of the post-process
  87889. */
  87890. _this.exposure = 0.3;
  87891. /**
  87892. * Dissipates each sample's contribution in range [0, 1]
  87893. */
  87894. _this.decay = 0.96815;
  87895. /**
  87896. * Controls the overall intensity of each sample
  87897. */
  87898. _this.weight = 0.58767;
  87899. /**
  87900. * Controls the density of each sample
  87901. */
  87902. _this.density = 0.926;
  87903. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  87904. engine = scene.getEngine();
  87905. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  87906. // Configure mesh
  87907. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  87908. // Configure
  87909. _this._createPass(scene, ratio.passRatio || ratio);
  87910. _this.onActivate = function (camera) {
  87911. if (!_this.isSupported) {
  87912. _this.dispose(camera);
  87913. }
  87914. _this.onActivate = null;
  87915. };
  87916. _this.onApplyObservable.add(function (effect) {
  87917. _this._updateMeshScreenCoordinates(scene);
  87918. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  87919. effect.setFloat("exposure", _this.exposure);
  87920. effect.setFloat("decay", _this.decay);
  87921. effect.setFloat("weight", _this.weight);
  87922. effect.setFloat("density", _this.density);
  87923. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  87924. });
  87925. return _this;
  87926. }
  87927. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  87928. /**
  87929. * @hidden
  87930. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  87931. */
  87932. get: function () {
  87933. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  87934. return false;
  87935. },
  87936. set: function (useDiffuseColor) {
  87937. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  87938. },
  87939. enumerable: true,
  87940. configurable: true
  87941. });
  87942. /**
  87943. * Returns the string "VolumetricLightScatteringPostProcess"
  87944. * @returns "VolumetricLightScatteringPostProcess"
  87945. */
  87946. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  87947. return "VolumetricLightScatteringPostProcess";
  87948. };
  87949. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  87950. var mesh = subMesh.getMesh();
  87951. // Render this.mesh as default
  87952. if (mesh === this.mesh && mesh.material) {
  87953. return mesh.material.isReady(mesh);
  87954. }
  87955. var defines = [];
  87956. var attribs = [BABYLON.VertexBuffer.PositionKind];
  87957. var material = subMesh.getMaterial();
  87958. // Alpha test
  87959. if (material) {
  87960. if (material.needAlphaTesting()) {
  87961. defines.push("#define ALPHATEST");
  87962. }
  87963. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  87964. attribs.push(BABYLON.VertexBuffer.UVKind);
  87965. defines.push("#define UV1");
  87966. }
  87967. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  87968. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  87969. defines.push("#define UV2");
  87970. }
  87971. }
  87972. // Bones
  87973. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  87974. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  87975. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  87976. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  87977. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  87978. }
  87979. else {
  87980. defines.push("#define NUM_BONE_INFLUENCERS 0");
  87981. }
  87982. // Instances
  87983. if (useInstances) {
  87984. defines.push("#define INSTANCES");
  87985. attribs.push("world0");
  87986. attribs.push("world1");
  87987. attribs.push("world2");
  87988. attribs.push("world3");
  87989. }
  87990. // Get correct effect
  87991. var join = defines.join("\n");
  87992. if (this._cachedDefines !== join) {
  87993. this._cachedDefines = join;
  87994. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  87995. }
  87996. return this._volumetricLightScatteringPass.isReady();
  87997. };
  87998. /**
  87999. * Sets the new light position for light scattering effect
  88000. * @param position The new custom light position
  88001. */
  88002. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  88003. this.customMeshPosition = position;
  88004. };
  88005. /**
  88006. * Returns the light position for light scattering effect
  88007. * @return {BABYLON.Vector3} The custom light position
  88008. */
  88009. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  88010. return this.customMeshPosition;
  88011. };
  88012. /**
  88013. * Disposes the internal assets and detaches the post-process from the camera
  88014. */
  88015. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  88016. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  88017. if (rttIndex !== -1) {
  88018. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  88019. }
  88020. this._volumetricLightScatteringRTT.dispose();
  88021. _super.prototype.dispose.call(this, camera);
  88022. };
  88023. /**
  88024. * Returns the render target texture used by the post-process
  88025. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  88026. */
  88027. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  88028. return this._volumetricLightScatteringRTT;
  88029. };
  88030. // Private methods
  88031. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  88032. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  88033. return true;
  88034. }
  88035. return false;
  88036. };
  88037. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  88038. var _this = this;
  88039. var engine = scene.getEngine();
  88040. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  88041. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88042. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88043. this._volumetricLightScatteringRTT.renderList = null;
  88044. this._volumetricLightScatteringRTT.renderParticles = false;
  88045. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  88046. var camera = this.getCamera();
  88047. if (camera) {
  88048. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  88049. }
  88050. else {
  88051. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  88052. }
  88053. // Custom render function for submeshes
  88054. var renderSubMesh = function (subMesh) {
  88055. var mesh = subMesh.getRenderingMesh();
  88056. if (_this._meshExcluded(mesh)) {
  88057. return;
  88058. }
  88059. var material = subMesh.getMaterial();
  88060. if (!material) {
  88061. return;
  88062. }
  88063. var scene = mesh.getScene();
  88064. var engine = scene.getEngine();
  88065. // Culling
  88066. engine.setState(material.backFaceCulling);
  88067. // Managing instances
  88068. var batch = mesh._getInstancesRenderList(subMesh._id);
  88069. if (batch.mustReturn) {
  88070. return;
  88071. }
  88072. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  88073. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  88074. var effect = _this._volumetricLightScatteringPass;
  88075. if (mesh === _this.mesh) {
  88076. if (subMesh.effect) {
  88077. effect = subMesh.effect;
  88078. }
  88079. else {
  88080. effect = material.getEffect();
  88081. }
  88082. }
  88083. engine.enableEffect(effect);
  88084. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  88085. if (mesh === _this.mesh) {
  88086. material.bind(mesh.getWorldMatrix(), mesh);
  88087. }
  88088. else {
  88089. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  88090. // Alpha test
  88091. if (material && material.needAlphaTesting()) {
  88092. var alphaTexture = material.getAlphaTestTexture();
  88093. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  88094. if (alphaTexture) {
  88095. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  88096. }
  88097. }
  88098. // Bones
  88099. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  88100. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  88101. }
  88102. }
  88103. // Draw
  88104. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  88105. }
  88106. };
  88107. // Render target texture callbacks
  88108. var savedSceneClearColor;
  88109. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  88110. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  88111. savedSceneClearColor = scene.clearColor;
  88112. scene.clearColor = sceneClearColor;
  88113. });
  88114. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  88115. scene.clearColor = savedSceneClearColor;
  88116. });
  88117. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  88118. var engine = scene.getEngine();
  88119. var index;
  88120. if (depthOnlySubMeshes.length) {
  88121. engine.setColorWrite(false);
  88122. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  88123. renderSubMesh(depthOnlySubMeshes.data[index]);
  88124. }
  88125. engine.setColorWrite(true);
  88126. }
  88127. for (index = 0; index < opaqueSubMeshes.length; index++) {
  88128. renderSubMesh(opaqueSubMeshes.data[index]);
  88129. }
  88130. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  88131. renderSubMesh(alphaTestSubMeshes.data[index]);
  88132. }
  88133. if (transparentSubMeshes.length) {
  88134. // Sort sub meshes
  88135. for (index = 0; index < transparentSubMeshes.length; index++) {
  88136. var submesh = transparentSubMeshes.data[index];
  88137. var boundingInfo = submesh.getBoundingInfo();
  88138. if (boundingInfo && scene.activeCamera) {
  88139. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  88140. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  88141. }
  88142. }
  88143. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  88144. sortedArray.sort(function (a, b) {
  88145. // Alpha index first
  88146. if (a._alphaIndex > b._alphaIndex) {
  88147. return 1;
  88148. }
  88149. if (a._alphaIndex < b._alphaIndex) {
  88150. return -1;
  88151. }
  88152. // Then distance to camera
  88153. if (a._distanceToCamera < b._distanceToCamera) {
  88154. return 1;
  88155. }
  88156. if (a._distanceToCamera > b._distanceToCamera) {
  88157. return -1;
  88158. }
  88159. return 0;
  88160. });
  88161. // Render sub meshes
  88162. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  88163. for (index = 0; index < sortedArray.length; index++) {
  88164. renderSubMesh(sortedArray[index]);
  88165. }
  88166. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88167. }
  88168. };
  88169. };
  88170. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  88171. var transform = scene.getTransformMatrix();
  88172. var meshPosition;
  88173. if (this.useCustomMeshPosition) {
  88174. meshPosition = this.customMeshPosition;
  88175. }
  88176. else if (this.attachedNode) {
  88177. meshPosition = this.attachedNode.position;
  88178. }
  88179. else {
  88180. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  88181. }
  88182. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  88183. this._screenCoordinates.x = pos.x / this._viewPort.width;
  88184. this._screenCoordinates.y = pos.y / this._viewPort.height;
  88185. if (this.invert)
  88186. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  88187. };
  88188. // Static methods
  88189. /**
  88190. * Creates a default mesh for the Volumeric Light Scattering post-process
  88191. * @param name The mesh name
  88192. * @param scene The scene where to create the mesh
  88193. * @return {BABYLON.Mesh} the default mesh
  88194. */
  88195. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  88196. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  88197. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  88198. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  88199. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  88200. mesh.material = material;
  88201. return mesh;
  88202. };
  88203. __decorate([
  88204. BABYLON.serializeAsVector3()
  88205. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  88206. __decorate([
  88207. BABYLON.serialize()
  88208. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  88209. __decorate([
  88210. BABYLON.serialize()
  88211. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  88212. __decorate([
  88213. BABYLON.serializeAsMeshReference()
  88214. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  88215. __decorate([
  88216. BABYLON.serialize()
  88217. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  88218. __decorate([
  88219. BABYLON.serialize()
  88220. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  88221. __decorate([
  88222. BABYLON.serialize()
  88223. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  88224. __decorate([
  88225. BABYLON.serialize()
  88226. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  88227. __decorate([
  88228. BABYLON.serialize()
  88229. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  88230. return VolumetricLightScatteringPostProcess;
  88231. }(BABYLON.PostProcess));
  88232. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  88233. })(BABYLON || (BABYLON = {}));
  88234. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  88235. var BABYLON;
  88236. (function (BABYLON) {
  88237. /**
  88238. *
  88239. * This post-process allows the modification of rendered colors by using
  88240. * a 'look-up table' (LUT). This effect is also called Color Grading.
  88241. *
  88242. * The object needs to be provided an url to a texture containing the color
  88243. * look-up table: the texture must be 256 pixels wide and 16 pixels high.
  88244. * Use an image editing software to tweak the LUT to match your needs.
  88245. *
  88246. * For an example of a color LUT, see here:
  88247. * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  88248. * For explanations on color grading, see here:
  88249. * @see http://udn.epicgames.com/Three/ColorGrading.html
  88250. *
  88251. */
  88252. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  88253. __extends(ColorCorrectionPostProcess, _super);
  88254. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  88255. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  88256. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  88257. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  88258. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88259. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88260. _this.onApply = function (effect) {
  88261. effect.setTexture("colorTable", _this._colorTableTexture);
  88262. };
  88263. return _this;
  88264. }
  88265. return ColorCorrectionPostProcess;
  88266. }(BABYLON.PostProcess));
  88267. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  88268. })(BABYLON || (BABYLON = {}));
  88269. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  88270. var BABYLON;
  88271. (function (BABYLON) {
  88272. /** Defines operator used for tonemapping */
  88273. var TonemappingOperator;
  88274. (function (TonemappingOperator) {
  88275. /** Hable */
  88276. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  88277. /** Reinhard */
  88278. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  88279. /** HejiDawson */
  88280. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  88281. /** Photographic */
  88282. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  88283. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  88284. ;
  88285. /**
  88286. * Defines a post process to apply tone mapping
  88287. */
  88288. var TonemapPostProcess = /** @class */ (function (_super) {
  88289. __extends(TonemapPostProcess, _super);
  88290. /**
  88291. * Creates a new TonemapPostProcess
  88292. * @param name defines the name of the postprocess
  88293. * @param _operator defines the operator to use
  88294. * @param exposureAdjustment defines the required exposure adjustement
  88295. * @param camera defines the camera to use (can be null)
  88296. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  88297. * @param engine defines the hosting engine (can be ignore if camera is set)
  88298. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  88299. */
  88300. function TonemapPostProcess(name, _operator,
  88301. /** Defines the required exposure adjustement */
  88302. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  88303. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  88304. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88305. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  88306. _this._operator = _operator;
  88307. _this.exposureAdjustment = exposureAdjustment;
  88308. var defines = "#define ";
  88309. if (_this._operator === TonemappingOperator.Hable)
  88310. defines += "HABLE_TONEMAPPING";
  88311. else if (_this._operator === TonemappingOperator.Reinhard)
  88312. defines += "REINHARD_TONEMAPPING";
  88313. else if (_this._operator === TonemappingOperator.HejiDawson)
  88314. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  88315. else if (_this._operator === TonemappingOperator.Photographic)
  88316. defines += "PHOTOGRAPHIC_TONEMAPPING";
  88317. //sadly a second call to create the effect.
  88318. _this.updateEffect(defines);
  88319. _this.onApply = function (effect) {
  88320. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  88321. };
  88322. return _this;
  88323. }
  88324. return TonemapPostProcess;
  88325. }(BABYLON.PostProcess));
  88326. BABYLON.TonemapPostProcess = TonemapPostProcess;
  88327. })(BABYLON || (BABYLON = {}));
  88328. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  88329. var BABYLON;
  88330. (function (BABYLON) {
  88331. /**
  88332. * DisplayPassPostProcess which produces an output the same as it's input
  88333. */
  88334. var DisplayPassPostProcess = /** @class */ (function (_super) {
  88335. __extends(DisplayPassPostProcess, _super);
  88336. /**
  88337. * Creates the DisplayPassPostProcess
  88338. * @param name The name of the effect.
  88339. * @param options The required width/height ratio to downsize to before computing the render pass.
  88340. * @param camera The camera to apply the render pass to.
  88341. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88342. * @param engine The engine which the post process will be applied. (default: current engine)
  88343. * @param reusable If the post process can be reused on the same frame. (default: false)
  88344. */
  88345. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  88346. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  88347. }
  88348. return DisplayPassPostProcess;
  88349. }(BABYLON.PostProcess));
  88350. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  88351. })(BABYLON || (BABYLON = {}));
  88352. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  88353. var BABYLON;
  88354. (function (BABYLON) {
  88355. /**
  88356. * Extracts highlights from the image
  88357. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  88358. */
  88359. var HighlightsPostProcess = /** @class */ (function (_super) {
  88360. __extends(HighlightsPostProcess, _super);
  88361. /**
  88362. * Extracts highlights from the image
  88363. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  88364. * @param name The name of the effect.
  88365. * @param options The required width/height ratio to downsize to before computing the render pass.
  88366. * @param camera The camera to apply the render pass to.
  88367. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88368. * @param engine The engine which the post process will be applied. (default: current engine)
  88369. * @param reusable If the post process can be reused on the same frame. (default: false)
  88370. * @param textureType Type of texture for the post process (default: Engine.TEXTURETYPE_UNSIGNED_INT)
  88371. */
  88372. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  88373. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88374. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  88375. }
  88376. return HighlightsPostProcess;
  88377. }(BABYLON.PostProcess));
  88378. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  88379. })(BABYLON || (BABYLON = {}));
  88380. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  88381. var BABYLON;
  88382. (function (BABYLON) {
  88383. /**
  88384. * ImageProcessingPostProcess
  88385. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#imageprocessing
  88386. */
  88387. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  88388. __extends(ImageProcessingPostProcess, _super);
  88389. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  88390. if (camera === void 0) { camera = null; }
  88391. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88392. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  88393. _this._fromLinearSpace = true;
  88394. /**
  88395. * Defines cache preventing GC.
  88396. */
  88397. _this._defines = {
  88398. IMAGEPROCESSING: false,
  88399. VIGNETTE: false,
  88400. VIGNETTEBLENDMODEMULTIPLY: false,
  88401. VIGNETTEBLENDMODEOPAQUE: false,
  88402. TONEMAPPING: false,
  88403. TONEMAPPING_ACES: false,
  88404. CONTRAST: false,
  88405. COLORCURVES: false,
  88406. COLORGRADING: false,
  88407. COLORGRADING3D: false,
  88408. FROMLINEARSPACE: false,
  88409. SAMPLER3DGREENDEPTH: false,
  88410. SAMPLER3DBGRMAP: false,
  88411. IMAGEPROCESSINGPOSTPROCESS: false,
  88412. EXPOSURE: false,
  88413. };
  88414. // Setup the configuration as forced by the constructor. This would then not force the
  88415. // scene materials output in linear space and let untouched the default forward pass.
  88416. if (imageProcessingConfiguration) {
  88417. imageProcessingConfiguration.applyByPostProcess = true;
  88418. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  88419. // This will cause the shader to be compiled
  88420. _this.fromLinearSpace = false;
  88421. }
  88422. // Setup the default processing configuration to the scene.
  88423. else {
  88424. _this._attachImageProcessingConfiguration(null, true);
  88425. _this.imageProcessingConfiguration.applyByPostProcess = true;
  88426. }
  88427. _this.onApply = function (effect) {
  88428. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  88429. };
  88430. return _this;
  88431. }
  88432. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  88433. /**
  88434. * Gets the image processing configuration used either in this material.
  88435. */
  88436. get: function () {
  88437. return this._imageProcessingConfiguration;
  88438. },
  88439. /**
  88440. * Sets the Default image processing configuration used either in the this material.
  88441. *
  88442. * If sets to null, the scene one is in use.
  88443. */
  88444. set: function (value) {
  88445. this._attachImageProcessingConfiguration(value);
  88446. },
  88447. enumerable: true,
  88448. configurable: true
  88449. });
  88450. /**
  88451. * Attaches a new image processing configuration to the PBR Material.
  88452. * @param configuration
  88453. */
  88454. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  88455. var _this = this;
  88456. if (doNotBuild === void 0) { doNotBuild = false; }
  88457. if (configuration === this._imageProcessingConfiguration) {
  88458. return;
  88459. }
  88460. // Detaches observer.
  88461. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88462. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88463. }
  88464. // Pick the scene configuration if needed.
  88465. if (!configuration) {
  88466. var scene = null;
  88467. var engine = this.getEngine();
  88468. var camera = this.getCamera();
  88469. if (camera) {
  88470. scene = camera.getScene();
  88471. }
  88472. else if (engine && engine.scenes) {
  88473. var scenes = engine.scenes;
  88474. scene = scenes[scenes.length - 1];
  88475. }
  88476. else {
  88477. scene = BABYLON.Engine.LastCreatedScene;
  88478. }
  88479. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  88480. }
  88481. else {
  88482. this._imageProcessingConfiguration = configuration;
  88483. }
  88484. // Attaches observer.
  88485. if (this._imageProcessingConfiguration) {
  88486. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  88487. _this._updateParameters();
  88488. });
  88489. }
  88490. // Ensure the effect will be rebuilt.
  88491. if (!doNotBuild) {
  88492. this._updateParameters();
  88493. }
  88494. };
  88495. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  88496. /**
  88497. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  88498. */
  88499. get: function () {
  88500. return this.imageProcessingConfiguration.colorCurves;
  88501. },
  88502. /**
  88503. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  88504. */
  88505. set: function (value) {
  88506. this.imageProcessingConfiguration.colorCurves = value;
  88507. },
  88508. enumerable: true,
  88509. configurable: true
  88510. });
  88511. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  88512. /**
  88513. * Gets wether the color curves effect is enabled.
  88514. */
  88515. get: function () {
  88516. return this.imageProcessingConfiguration.colorCurvesEnabled;
  88517. },
  88518. /**
  88519. * Sets wether the color curves effect is enabled.
  88520. */
  88521. set: function (value) {
  88522. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  88523. },
  88524. enumerable: true,
  88525. configurable: true
  88526. });
  88527. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  88528. /**
  88529. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  88530. */
  88531. get: function () {
  88532. return this.imageProcessingConfiguration.colorGradingTexture;
  88533. },
  88534. /**
  88535. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  88536. */
  88537. set: function (value) {
  88538. this.imageProcessingConfiguration.colorGradingTexture = value;
  88539. },
  88540. enumerable: true,
  88541. configurable: true
  88542. });
  88543. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  88544. /**
  88545. * Gets wether the color grading effect is enabled.
  88546. */
  88547. get: function () {
  88548. return this.imageProcessingConfiguration.colorGradingEnabled;
  88549. },
  88550. /**
  88551. * Gets wether the color grading effect is enabled.
  88552. */
  88553. set: function (value) {
  88554. this.imageProcessingConfiguration.colorGradingEnabled = value;
  88555. },
  88556. enumerable: true,
  88557. configurable: true
  88558. });
  88559. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  88560. /**
  88561. * Gets exposure used in the effect.
  88562. */
  88563. get: function () {
  88564. return this.imageProcessingConfiguration.exposure;
  88565. },
  88566. /**
  88567. * Sets exposure used in the effect.
  88568. */
  88569. set: function (value) {
  88570. this.imageProcessingConfiguration.exposure = value;
  88571. },
  88572. enumerable: true,
  88573. configurable: true
  88574. });
  88575. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  88576. /**
  88577. * Gets wether tonemapping is enabled or not.
  88578. */
  88579. get: function () {
  88580. return this._imageProcessingConfiguration.toneMappingEnabled;
  88581. },
  88582. /**
  88583. * Sets wether tonemapping is enabled or not
  88584. */
  88585. set: function (value) {
  88586. this._imageProcessingConfiguration.toneMappingEnabled = value;
  88587. },
  88588. enumerable: true,
  88589. configurable: true
  88590. });
  88591. ;
  88592. ;
  88593. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  88594. /**
  88595. * Gets contrast used in the effect.
  88596. */
  88597. get: function () {
  88598. return this.imageProcessingConfiguration.contrast;
  88599. },
  88600. /**
  88601. * Sets contrast used in the effect.
  88602. */
  88603. set: function (value) {
  88604. this.imageProcessingConfiguration.contrast = value;
  88605. },
  88606. enumerable: true,
  88607. configurable: true
  88608. });
  88609. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  88610. /**
  88611. * Gets Vignette stretch size.
  88612. */
  88613. get: function () {
  88614. return this.imageProcessingConfiguration.vignetteStretch;
  88615. },
  88616. /**
  88617. * Sets Vignette stretch size.
  88618. */
  88619. set: function (value) {
  88620. this.imageProcessingConfiguration.vignetteStretch = value;
  88621. },
  88622. enumerable: true,
  88623. configurable: true
  88624. });
  88625. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  88626. /**
  88627. * Gets Vignette centre X Offset.
  88628. */
  88629. get: function () {
  88630. return this.imageProcessingConfiguration.vignetteCentreX;
  88631. },
  88632. /**
  88633. * Sets Vignette centre X Offset.
  88634. */
  88635. set: function (value) {
  88636. this.imageProcessingConfiguration.vignetteCentreX = value;
  88637. },
  88638. enumerable: true,
  88639. configurable: true
  88640. });
  88641. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  88642. /**
  88643. * Gets Vignette centre Y Offset.
  88644. */
  88645. get: function () {
  88646. return this.imageProcessingConfiguration.vignetteCentreY;
  88647. },
  88648. /**
  88649. * Sets Vignette centre Y Offset.
  88650. */
  88651. set: function (value) {
  88652. this.imageProcessingConfiguration.vignetteCentreY = value;
  88653. },
  88654. enumerable: true,
  88655. configurable: true
  88656. });
  88657. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  88658. /**
  88659. * Gets Vignette weight or intensity of the vignette effect.
  88660. */
  88661. get: function () {
  88662. return this.imageProcessingConfiguration.vignetteWeight;
  88663. },
  88664. /**
  88665. * Sets Vignette weight or intensity of the vignette effect.
  88666. */
  88667. set: function (value) {
  88668. this.imageProcessingConfiguration.vignetteWeight = value;
  88669. },
  88670. enumerable: true,
  88671. configurable: true
  88672. });
  88673. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  88674. /**
  88675. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  88676. * if vignetteEnabled is set to true.
  88677. */
  88678. get: function () {
  88679. return this.imageProcessingConfiguration.vignetteColor;
  88680. },
  88681. /**
  88682. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  88683. * if vignetteEnabled is set to true.
  88684. */
  88685. set: function (value) {
  88686. this.imageProcessingConfiguration.vignetteColor = value;
  88687. },
  88688. enumerable: true,
  88689. configurable: true
  88690. });
  88691. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  88692. /**
  88693. * Gets Camera field of view used by the Vignette effect.
  88694. */
  88695. get: function () {
  88696. return this.imageProcessingConfiguration.vignetteCameraFov;
  88697. },
  88698. /**
  88699. * Sets Camera field of view used by the Vignette effect.
  88700. */
  88701. set: function (value) {
  88702. this.imageProcessingConfiguration.vignetteCameraFov = value;
  88703. },
  88704. enumerable: true,
  88705. configurable: true
  88706. });
  88707. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  88708. /**
  88709. * Gets the vignette blend mode allowing different kind of effect.
  88710. */
  88711. get: function () {
  88712. return this.imageProcessingConfiguration.vignetteBlendMode;
  88713. },
  88714. /**
  88715. * Sets the vignette blend mode allowing different kind of effect.
  88716. */
  88717. set: function (value) {
  88718. this.imageProcessingConfiguration.vignetteBlendMode = value;
  88719. },
  88720. enumerable: true,
  88721. configurable: true
  88722. });
  88723. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  88724. /**
  88725. * Gets wether the vignette effect is enabled.
  88726. */
  88727. get: function () {
  88728. return this.imageProcessingConfiguration.vignetteEnabled;
  88729. },
  88730. /**
  88731. * Sets wether the vignette effect is enabled.
  88732. */
  88733. set: function (value) {
  88734. this.imageProcessingConfiguration.vignetteEnabled = value;
  88735. },
  88736. enumerable: true,
  88737. configurable: true
  88738. });
  88739. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  88740. /**
  88741. * Gets wether the input of the processing is in Gamma or Linear Space.
  88742. */
  88743. get: function () {
  88744. return this._fromLinearSpace;
  88745. },
  88746. /**
  88747. * Sets wether the input of the processing is in Gamma or Linear Space.
  88748. */
  88749. set: function (value) {
  88750. if (this._fromLinearSpace === value) {
  88751. return;
  88752. }
  88753. this._fromLinearSpace = value;
  88754. this._updateParameters();
  88755. },
  88756. enumerable: true,
  88757. configurable: true
  88758. });
  88759. /**
  88760. * "ImageProcessingPostProcess"
  88761. * @returns "ImageProcessingPostProcess"
  88762. */
  88763. ImageProcessingPostProcess.prototype.getClassName = function () {
  88764. return "ImageProcessingPostProcess";
  88765. };
  88766. ImageProcessingPostProcess.prototype._updateParameters = function () {
  88767. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  88768. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  88769. var defines = "";
  88770. for (var define in this._defines) {
  88771. if (this._defines[define]) {
  88772. defines += "#define " + define + ";\r\n";
  88773. }
  88774. }
  88775. var samplers = ["textureSampler"];
  88776. var uniforms = ["scale"];
  88777. if (BABYLON.ImageProcessingConfiguration) {
  88778. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  88779. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  88780. }
  88781. this.updateEffect(defines, uniforms, samplers);
  88782. };
  88783. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  88784. _super.prototype.dispose.call(this, camera);
  88785. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88786. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88787. }
  88788. if (this._imageProcessingConfiguration) {
  88789. this.imageProcessingConfiguration.applyByPostProcess = false;
  88790. }
  88791. };
  88792. __decorate([
  88793. BABYLON.serialize()
  88794. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  88795. return ImageProcessingPostProcess;
  88796. }(BABYLON.PostProcess));
  88797. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  88798. })(BABYLON || (BABYLON = {}));
  88799. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  88800. var BABYLON;
  88801. (function (BABYLON) {
  88802. /**
  88803. * Class used to store bone information
  88804. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  88805. */
  88806. var Bone = /** @class */ (function (_super) {
  88807. __extends(Bone, _super);
  88808. /**
  88809. * Create a new bone
  88810. * @param name defines the bone name
  88811. * @param skeleton defines the parent skeleton
  88812. * @param parentBone defines the parent (can be null if the bone is the root)
  88813. * @param localMatrix defines the local matrix
  88814. * @param restPose defines the rest pose matrix
  88815. * @param baseMatrix defines the base matrix
  88816. * @param index defines index of the bone in the hiearchy
  88817. */
  88818. function Bone(
  88819. /**
  88820. * defines the bone name
  88821. */
  88822. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  88823. if (parentBone === void 0) { parentBone = null; }
  88824. if (localMatrix === void 0) { localMatrix = null; }
  88825. if (restPose === void 0) { restPose = null; }
  88826. if (baseMatrix === void 0) { baseMatrix = null; }
  88827. if (index === void 0) { index = null; }
  88828. var _this = _super.call(this, name, skeleton.getScene()) || this;
  88829. _this.name = name;
  88830. /**
  88831. * Gets the list of child bones
  88832. */
  88833. _this.children = new Array();
  88834. /** Gets the animations associated with this bone */
  88835. _this.animations = new Array();
  88836. /**
  88837. * @hidden Internal only
  88838. * Set this value to map this bone to a different index in the transform matrices
  88839. * Set this value to -1 to exclude the bone from the transform matrices
  88840. */
  88841. _this._index = null;
  88842. _this._absoluteTransform = new BABYLON.Matrix();
  88843. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  88844. _this._scalingDeterminant = 1;
  88845. _this._worldTransform = new BABYLON.Matrix();
  88846. _this._needToDecompose = true;
  88847. _this._needToCompose = false;
  88848. _this._skeleton = skeleton;
  88849. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  88850. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  88851. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  88852. _this._index = index;
  88853. skeleton.bones.push(_this);
  88854. _this.setParent(parentBone, false);
  88855. if (baseMatrix || localMatrix) {
  88856. _this._updateDifferenceMatrix();
  88857. }
  88858. return _this;
  88859. }
  88860. Object.defineProperty(Bone.prototype, "_matrix", {
  88861. /** @hidden */
  88862. get: function () {
  88863. this._compose();
  88864. return this._localMatrix;
  88865. },
  88866. /** @hidden */
  88867. set: function (value) {
  88868. this._localMatrix.copyFrom(value);
  88869. this._needToDecompose = true;
  88870. },
  88871. enumerable: true,
  88872. configurable: true
  88873. });
  88874. // Members
  88875. /**
  88876. * Gets the parent skeleton
  88877. * @returns a skeleton
  88878. */
  88879. Bone.prototype.getSkeleton = function () {
  88880. return this._skeleton;
  88881. };
  88882. /**
  88883. * Gets parent bone
  88884. * @returns a bone or null if the bone is the root of the bone hierarchy
  88885. */
  88886. Bone.prototype.getParent = function () {
  88887. return this._parent;
  88888. };
  88889. /**
  88890. * Sets the parent bone
  88891. * @param parent defines the parent (can be null if the bone is the root)
  88892. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  88893. */
  88894. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  88895. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  88896. if (this._parent === parent) {
  88897. return;
  88898. }
  88899. if (this._parent) {
  88900. var index = this._parent.children.indexOf(this);
  88901. if (index !== -1) {
  88902. this._parent.children.splice(index, 1);
  88903. }
  88904. }
  88905. this._parent = parent;
  88906. if (this._parent) {
  88907. this._parent.children.push(this);
  88908. }
  88909. if (updateDifferenceMatrix) {
  88910. this._updateDifferenceMatrix();
  88911. }
  88912. this.markAsDirty();
  88913. };
  88914. /**
  88915. * Gets the local matrix
  88916. * @returns a matrix
  88917. */
  88918. Bone.prototype.getLocalMatrix = function () {
  88919. this._compose();
  88920. return this._localMatrix;
  88921. };
  88922. /**
  88923. * Gets the base matrix (initial matrix which remains unchanged)
  88924. * @returns a matrix
  88925. */
  88926. Bone.prototype.getBaseMatrix = function () {
  88927. return this._baseMatrix;
  88928. };
  88929. /**
  88930. * Gets the rest pose matrix
  88931. * @returns a matrix
  88932. */
  88933. Bone.prototype.getRestPose = function () {
  88934. return this._restPose;
  88935. };
  88936. /**
  88937. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  88938. */
  88939. Bone.prototype.getWorldMatrix = function () {
  88940. return this._worldTransform;
  88941. };
  88942. /**
  88943. * Sets the local matrix to rest pose matrix
  88944. */
  88945. Bone.prototype.returnToRest = function () {
  88946. this.updateMatrix(this._restPose.clone());
  88947. };
  88948. /**
  88949. * Gets the inverse of the absolute transform matrix.
  88950. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  88951. * @returns a matrix
  88952. */
  88953. Bone.prototype.getInvertedAbsoluteTransform = function () {
  88954. return this._invertedAbsoluteTransform;
  88955. };
  88956. /**
  88957. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  88958. * @returns a matrix
  88959. */
  88960. Bone.prototype.getAbsoluteTransform = function () {
  88961. return this._absoluteTransform;
  88962. };
  88963. Object.defineProperty(Bone.prototype, "position", {
  88964. // Properties (matches AbstractMesh properties)
  88965. /** Gets or sets current position (in local space) */
  88966. get: function () {
  88967. this._decompose();
  88968. return this._localPosition;
  88969. },
  88970. set: function (newPosition) {
  88971. this._decompose();
  88972. this._localPosition.copyFrom(newPosition);
  88973. this._markAsDirtyAndCompose();
  88974. },
  88975. enumerable: true,
  88976. configurable: true
  88977. });
  88978. Object.defineProperty(Bone.prototype, "rotation", {
  88979. /** Gets or sets current rotation (in local space) */
  88980. get: function () {
  88981. return this.getRotation();
  88982. },
  88983. set: function (newRotation) {
  88984. this.setRotation(newRotation);
  88985. },
  88986. enumerable: true,
  88987. configurable: true
  88988. });
  88989. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  88990. /** Gets or sets current rotation quaternion (in local space) */
  88991. get: function () {
  88992. this._decompose();
  88993. return this._localRotation;
  88994. },
  88995. set: function (newRotation) {
  88996. this.setRotationQuaternion(newRotation);
  88997. },
  88998. enumerable: true,
  88999. configurable: true
  89000. });
  89001. Object.defineProperty(Bone.prototype, "scaling", {
  89002. /** Gets or sets current scaling (in local space) */
  89003. get: function () {
  89004. return this.getScale();
  89005. },
  89006. set: function (newScaling) {
  89007. this.setScale(newScaling);
  89008. },
  89009. enumerable: true,
  89010. configurable: true
  89011. });
  89012. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  89013. /**
  89014. * Gets the animation properties override
  89015. */
  89016. get: function () {
  89017. return this._skeleton.animationPropertiesOverride;
  89018. },
  89019. enumerable: true,
  89020. configurable: true
  89021. });
  89022. // Methods
  89023. Bone.prototype._decompose = function () {
  89024. if (!this._needToDecompose) {
  89025. return;
  89026. }
  89027. this._needToDecompose = false;
  89028. if (!this._localScaling) {
  89029. this._localScaling = BABYLON.Vector3.Zero();
  89030. this._localRotation = BABYLON.Quaternion.Zero();
  89031. this._localPosition = BABYLON.Vector3.Zero();
  89032. }
  89033. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  89034. };
  89035. Bone.prototype._compose = function () {
  89036. if (!this._needToCompose) {
  89037. return;
  89038. }
  89039. this._needToCompose = false;
  89040. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  89041. };
  89042. /**
  89043. * Update the base and local matrices
  89044. * @param matrix defines the new base or local matrix
  89045. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  89046. * @param updateLocalMatrix defines if the local matrix should be updated
  89047. */
  89048. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  89049. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  89050. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  89051. this._baseMatrix.copyFrom(matrix);
  89052. if (updateDifferenceMatrix) {
  89053. this._updateDifferenceMatrix();
  89054. }
  89055. if (updateLocalMatrix) {
  89056. this._localMatrix.copyFrom(matrix);
  89057. this._markAsDirtyAndDecompose();
  89058. }
  89059. else {
  89060. this.markAsDirty();
  89061. }
  89062. };
  89063. /** @hidden */
  89064. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  89065. if (updateChildren === void 0) { updateChildren = true; }
  89066. if (!rootMatrix) {
  89067. rootMatrix = this._baseMatrix;
  89068. }
  89069. if (this._parent) {
  89070. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  89071. }
  89072. else {
  89073. this._absoluteTransform.copyFrom(rootMatrix);
  89074. }
  89075. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  89076. if (updateChildren) {
  89077. for (var index = 0; index < this.children.length; index++) {
  89078. this.children[index]._updateDifferenceMatrix();
  89079. }
  89080. }
  89081. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  89082. };
  89083. /**
  89084. * Flag the bone as dirty (Forcing it to update everything)
  89085. */
  89086. Bone.prototype.markAsDirty = function () {
  89087. this._currentRenderId++;
  89088. this._childRenderId++;
  89089. this._skeleton._markAsDirty();
  89090. };
  89091. Bone.prototype._markAsDirtyAndCompose = function () {
  89092. this.markAsDirty();
  89093. this._needToCompose = true;
  89094. };
  89095. Bone.prototype._markAsDirtyAndDecompose = function () {
  89096. this.markAsDirty();
  89097. this._needToDecompose = true;
  89098. };
  89099. /**
  89100. * Copy an animation range from another bone
  89101. * @param source defines the source bone
  89102. * @param rangeName defines the range name to copy
  89103. * @param frameOffset defines the frame offset
  89104. * @param rescaleAsRequired defines if rescaling must be applied if required
  89105. * @param skelDimensionsRatio defines the scaling ratio
  89106. * @returns true if operation was successful
  89107. */
  89108. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  89109. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  89110. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  89111. // all animation may be coming from a library skeleton, so may need to create animation
  89112. if (this.animations.length === 0) {
  89113. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  89114. this.animations[0].setKeys([]);
  89115. }
  89116. // get animation info / verify there is such a range from the source bone
  89117. var sourceRange = source.animations[0].getRange(rangeName);
  89118. if (!sourceRange) {
  89119. return false;
  89120. }
  89121. var from = sourceRange.from;
  89122. var to = sourceRange.to;
  89123. var sourceKeys = source.animations[0].getKeys();
  89124. // rescaling prep
  89125. var sourceBoneLength = source.length;
  89126. var sourceParent = source.getParent();
  89127. var parent = this.getParent();
  89128. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  89129. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  89130. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  89131. var destKeys = this.animations[0].getKeys();
  89132. // loop vars declaration
  89133. var orig;
  89134. var origTranslation;
  89135. var mat;
  89136. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  89137. orig = sourceKeys[key];
  89138. if (orig.frame >= from && orig.frame <= to) {
  89139. if (rescaleAsRequired) {
  89140. mat = orig.value.clone();
  89141. // scale based on parent ratio, when bone has parent
  89142. if (parentScalingReqd) {
  89143. origTranslation = mat.getTranslation();
  89144. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  89145. // scale based on skeleton dimension ratio when root bone, and value is passed
  89146. }
  89147. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  89148. origTranslation = mat.getTranslation();
  89149. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  89150. // use original when root bone, and no data for skelDimensionsRatio
  89151. }
  89152. else {
  89153. mat = orig.value;
  89154. }
  89155. }
  89156. else {
  89157. mat = orig.value;
  89158. }
  89159. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  89160. }
  89161. }
  89162. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  89163. return true;
  89164. };
  89165. /**
  89166. * Translate the bone in local or world space
  89167. * @param vec The amount to translate the bone
  89168. * @param space The space that the translation is in
  89169. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89170. */
  89171. Bone.prototype.translate = function (vec, space, mesh) {
  89172. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89173. var lm = this.getLocalMatrix();
  89174. if (space == BABYLON.Space.LOCAL) {
  89175. lm.m[12] += vec.x;
  89176. lm.m[13] += vec.y;
  89177. lm.m[14] += vec.z;
  89178. }
  89179. else {
  89180. var wm = null;
  89181. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89182. if (mesh) {
  89183. wm = mesh.getWorldMatrix();
  89184. }
  89185. this._skeleton.computeAbsoluteTransforms();
  89186. var tmat = Bone._tmpMats[0];
  89187. var tvec = Bone._tmpVecs[0];
  89188. if (this._parent) {
  89189. if (mesh && wm) {
  89190. tmat.copyFrom(this._parent.getAbsoluteTransform());
  89191. tmat.multiplyToRef(wm, tmat);
  89192. }
  89193. else {
  89194. tmat.copyFrom(this._parent.getAbsoluteTransform());
  89195. }
  89196. }
  89197. tmat.m[12] = 0;
  89198. tmat.m[13] = 0;
  89199. tmat.m[14] = 0;
  89200. tmat.invert();
  89201. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  89202. lm.m[12] += tvec.x;
  89203. lm.m[13] += tvec.y;
  89204. lm.m[14] += tvec.z;
  89205. }
  89206. this._markAsDirtyAndDecompose();
  89207. };
  89208. /**
  89209. * Set the postion of the bone in local or world space
  89210. * @param position The position to set the bone
  89211. * @param space The space that the position is in
  89212. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89213. */
  89214. Bone.prototype.setPosition = function (position, space, mesh) {
  89215. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89216. var lm = this.getLocalMatrix();
  89217. if (space == BABYLON.Space.LOCAL) {
  89218. lm.m[12] = position.x;
  89219. lm.m[13] = position.y;
  89220. lm.m[14] = position.z;
  89221. }
  89222. else {
  89223. var wm = null;
  89224. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89225. if (mesh) {
  89226. wm = mesh.getWorldMatrix();
  89227. }
  89228. this._skeleton.computeAbsoluteTransforms();
  89229. var tmat = Bone._tmpMats[0];
  89230. var vec = Bone._tmpVecs[0];
  89231. if (this._parent) {
  89232. if (mesh && wm) {
  89233. tmat.copyFrom(this._parent.getAbsoluteTransform());
  89234. tmat.multiplyToRef(wm, tmat);
  89235. }
  89236. else {
  89237. tmat.copyFrom(this._parent.getAbsoluteTransform());
  89238. }
  89239. }
  89240. tmat.invert();
  89241. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  89242. lm.m[12] = vec.x;
  89243. lm.m[13] = vec.y;
  89244. lm.m[14] = vec.z;
  89245. }
  89246. this._markAsDirtyAndDecompose();
  89247. };
  89248. /**
  89249. * Set the absolute position of the bone (world space)
  89250. * @param position The position to set the bone
  89251. * @param mesh The mesh that this bone is attached to
  89252. */
  89253. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  89254. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  89255. };
  89256. /**
  89257. * Scale the bone on the x, y and z axes (in local space)
  89258. * @param x The amount to scale the bone on the x axis
  89259. * @param y The amount to scale the bone on the y axis
  89260. * @param z The amount to scale the bone on the z axis
  89261. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  89262. */
  89263. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  89264. if (scaleChildren === void 0) { scaleChildren = false; }
  89265. var locMat = this.getLocalMatrix();
  89266. // Apply new scaling on top of current local matrix
  89267. var scaleMat = Bone._tmpMats[0];
  89268. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  89269. scaleMat.multiplyToRef(locMat, locMat);
  89270. // Invert scaling matrix and apply the inverse to all children
  89271. scaleMat.invert();
  89272. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  89273. var child = _a[_i];
  89274. var cm = child.getLocalMatrix();
  89275. cm.multiplyToRef(scaleMat, cm);
  89276. cm.m[12] *= x;
  89277. cm.m[13] *= y;
  89278. cm.m[14] *= z;
  89279. child._markAsDirtyAndDecompose();
  89280. }
  89281. this._markAsDirtyAndDecompose();
  89282. if (scaleChildren) {
  89283. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  89284. var child = _c[_b];
  89285. child.scale(x, y, z, scaleChildren);
  89286. }
  89287. }
  89288. };
  89289. /**
  89290. * Set the bone scaling in local space
  89291. * @param scale defines the scaling vector
  89292. */
  89293. Bone.prototype.setScale = function (scale) {
  89294. this._decompose();
  89295. this._localScaling.copyFrom(scale);
  89296. this._markAsDirtyAndCompose();
  89297. };
  89298. /**
  89299. * Gets the current scaling in local space
  89300. * @returns the current scaling vector
  89301. */
  89302. Bone.prototype.getScale = function () {
  89303. this._decompose();
  89304. return this._localScaling;
  89305. };
  89306. /**
  89307. * Gets the current scaling in local space and stores it in a target vector
  89308. * @param result defines the target vector
  89309. */
  89310. Bone.prototype.getScaleToRef = function (result) {
  89311. this._decompose();
  89312. result.copyFrom(this._localScaling);
  89313. };
  89314. /**
  89315. * Set the yaw, pitch, and roll of the bone in local or world space
  89316. * @param yaw The rotation of the bone on the y axis
  89317. * @param pitch The rotation of the bone on the x axis
  89318. * @param roll The rotation of the bone on the z axis
  89319. * @param space The space that the axes of rotation are in
  89320. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89321. */
  89322. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  89323. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89324. if (space === BABYLON.Space.LOCAL) {
  89325. var quat = Bone._tmpQuat;
  89326. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  89327. this.setRotationQuaternion(quat, space, mesh);
  89328. return;
  89329. }
  89330. var rotMatInv = Bone._tmpMats[0];
  89331. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  89332. return;
  89333. }
  89334. var rotMat = Bone._tmpMats[1];
  89335. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  89336. rotMatInv.multiplyToRef(rotMat, rotMat);
  89337. this._rotateWithMatrix(rotMat, space, mesh);
  89338. };
  89339. /**
  89340. * Add a rotation to the bone on an axis in local or world space
  89341. * @param axis The axis to rotate the bone on
  89342. * @param amount The amount to rotate the bone
  89343. * @param space The space that the axis is in
  89344. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89345. */
  89346. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  89347. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89348. var rmat = Bone._tmpMats[0];
  89349. rmat.m[12] = 0;
  89350. rmat.m[13] = 0;
  89351. rmat.m[14] = 0;
  89352. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  89353. this._rotateWithMatrix(rmat, space, mesh);
  89354. };
  89355. /**
  89356. * Set the rotation of the bone to a particular axis angle in local or world space
  89357. * @param axis The axis to rotate the bone on
  89358. * @param angle The angle that the bone should be rotated to
  89359. * @param space The space that the axis is in
  89360. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89361. */
  89362. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  89363. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89364. if (space === BABYLON.Space.LOCAL) {
  89365. var quat = Bone._tmpQuat;
  89366. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  89367. this.setRotationQuaternion(quat, space, mesh);
  89368. return;
  89369. }
  89370. var rotMatInv = Bone._tmpMats[0];
  89371. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  89372. return;
  89373. }
  89374. var rotMat = Bone._tmpMats[1];
  89375. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  89376. rotMatInv.multiplyToRef(rotMat, rotMat);
  89377. this._rotateWithMatrix(rotMat, space, mesh);
  89378. };
  89379. /**
  89380. * Set the euler rotation of the bone in local of world space
  89381. * @param rotation The euler rotation that the bone should be set to
  89382. * @param space The space that the rotation is in
  89383. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89384. */
  89385. Bone.prototype.setRotation = function (rotation, space, mesh) {
  89386. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89387. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  89388. };
  89389. /**
  89390. * Set the quaternion rotation of the bone in local of world space
  89391. * @param quat The quaternion rotation that the bone should be set to
  89392. * @param space The space that the rotation is in
  89393. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89394. */
  89395. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  89396. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89397. if (space === BABYLON.Space.LOCAL) {
  89398. this._decompose();
  89399. this._localRotation.copyFrom(quat);
  89400. this._markAsDirtyAndCompose();
  89401. return;
  89402. }
  89403. var rotMatInv = Bone._tmpMats[0];
  89404. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  89405. return;
  89406. }
  89407. var rotMat = Bone._tmpMats[1];
  89408. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  89409. rotMatInv.multiplyToRef(rotMat, rotMat);
  89410. this._rotateWithMatrix(rotMat, space, mesh);
  89411. };
  89412. /**
  89413. * Set the rotation matrix of the bone in local of world space
  89414. * @param rotMat The rotation matrix that the bone should be set to
  89415. * @param space The space that the rotation is in
  89416. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89417. */
  89418. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  89419. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89420. if (space === BABYLON.Space.LOCAL) {
  89421. var quat = Bone._tmpQuat;
  89422. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  89423. this.setRotationQuaternion(quat, space, mesh);
  89424. return;
  89425. }
  89426. var rotMatInv = Bone._tmpMats[0];
  89427. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  89428. return;
  89429. }
  89430. var rotMat2 = Bone._tmpMats[1];
  89431. rotMat2.copyFrom(rotMat);
  89432. rotMatInv.multiplyToRef(rotMat, rotMat2);
  89433. this._rotateWithMatrix(rotMat2, space, mesh);
  89434. };
  89435. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  89436. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89437. var lmat = this.getLocalMatrix();
  89438. var lx = lmat.m[12];
  89439. var ly = lmat.m[13];
  89440. var lz = lmat.m[14];
  89441. var parent = this.getParent();
  89442. var parentScale = Bone._tmpMats[3];
  89443. var parentScaleInv = Bone._tmpMats[4];
  89444. if (parent && space == BABYLON.Space.WORLD) {
  89445. if (mesh) {
  89446. parentScale.copyFrom(mesh.getWorldMatrix());
  89447. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  89448. }
  89449. else {
  89450. parentScale.copyFrom(parent.getAbsoluteTransform());
  89451. }
  89452. parentScaleInv.copyFrom(parentScale);
  89453. parentScaleInv.invert();
  89454. lmat.multiplyToRef(parentScale, lmat);
  89455. lmat.multiplyToRef(rmat, lmat);
  89456. lmat.multiplyToRef(parentScaleInv, lmat);
  89457. }
  89458. else {
  89459. if (space == BABYLON.Space.WORLD && mesh) {
  89460. parentScale.copyFrom(mesh.getWorldMatrix());
  89461. parentScaleInv.copyFrom(parentScale);
  89462. parentScaleInv.invert();
  89463. lmat.multiplyToRef(parentScale, lmat);
  89464. lmat.multiplyToRef(rmat, lmat);
  89465. lmat.multiplyToRef(parentScaleInv, lmat);
  89466. }
  89467. else {
  89468. lmat.multiplyToRef(rmat, lmat);
  89469. }
  89470. }
  89471. lmat.m[12] = lx;
  89472. lmat.m[13] = ly;
  89473. lmat.m[14] = lz;
  89474. this.computeAbsoluteTransforms();
  89475. this._markAsDirtyAndDecompose();
  89476. };
  89477. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  89478. var scaleMatrix = Bone._tmpMats[2];
  89479. rotMatInv.copyFrom(this.getAbsoluteTransform());
  89480. if (mesh) {
  89481. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  89482. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  89483. }
  89484. rotMatInv.invert();
  89485. if (isNaN(rotMatInv.m[0])) {
  89486. // Matrix failed to invert.
  89487. // This can happen if scale is zero for example.
  89488. return false;
  89489. }
  89490. scaleMatrix.m[0] *= this._scalingDeterminant;
  89491. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  89492. return true;
  89493. };
  89494. /**
  89495. * Get the position of the bone in local or world space
  89496. * @param space The space that the returned position is in
  89497. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89498. * @returns The position of the bone
  89499. */
  89500. Bone.prototype.getPosition = function (space, mesh) {
  89501. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89502. if (mesh === void 0) { mesh = null; }
  89503. var pos = BABYLON.Vector3.Zero();
  89504. this.getPositionToRef(space, mesh, pos);
  89505. return pos;
  89506. };
  89507. /**
  89508. * Copy the position of the bone to a vector3 in local or world space
  89509. * @param space The space that the returned position is in
  89510. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89511. * @param result The vector3 to copy the position to
  89512. */
  89513. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  89514. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89515. if (space == BABYLON.Space.LOCAL) {
  89516. var lm = this.getLocalMatrix();
  89517. result.x = lm.m[12];
  89518. result.y = lm.m[13];
  89519. result.z = lm.m[14];
  89520. }
  89521. else {
  89522. var wm = null;
  89523. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89524. if (mesh) {
  89525. wm = mesh.getWorldMatrix();
  89526. }
  89527. this._skeleton.computeAbsoluteTransforms();
  89528. var tmat = Bone._tmpMats[0];
  89529. if (mesh && wm) {
  89530. tmat.copyFrom(this.getAbsoluteTransform());
  89531. tmat.multiplyToRef(wm, tmat);
  89532. }
  89533. else {
  89534. tmat = this.getAbsoluteTransform();
  89535. }
  89536. result.x = tmat.m[12];
  89537. result.y = tmat.m[13];
  89538. result.z = tmat.m[14];
  89539. }
  89540. };
  89541. /**
  89542. * Get the absolute position of the bone (world space)
  89543. * @param mesh The mesh that this bone is attached to
  89544. * @returns The absolute position of the bone
  89545. */
  89546. Bone.prototype.getAbsolutePosition = function (mesh) {
  89547. if (mesh === void 0) { mesh = null; }
  89548. var pos = BABYLON.Vector3.Zero();
  89549. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  89550. return pos;
  89551. };
  89552. /**
  89553. * Copy the absolute position of the bone (world space) to the result param
  89554. * @param mesh The mesh that this bone is attached to
  89555. * @param result The vector3 to copy the absolute position to
  89556. */
  89557. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  89558. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  89559. };
  89560. /**
  89561. * Compute the absolute transforms of this bone and its children
  89562. */
  89563. Bone.prototype.computeAbsoluteTransforms = function () {
  89564. this._compose();
  89565. if (this._parent) {
  89566. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  89567. }
  89568. else {
  89569. this._absoluteTransform.copyFrom(this._localMatrix);
  89570. var poseMatrix = this._skeleton.getPoseMatrix();
  89571. if (poseMatrix) {
  89572. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  89573. }
  89574. }
  89575. var children = this.children;
  89576. var len = children.length;
  89577. for (var i = 0; i < len; i++) {
  89578. children[i].computeAbsoluteTransforms();
  89579. }
  89580. };
  89581. /**
  89582. * Get the world direction from an axis that is in the local space of the bone
  89583. * @param localAxis The local direction that is used to compute the world direction
  89584. * @param mesh The mesh that this bone is attached to
  89585. * @returns The world direction
  89586. */
  89587. Bone.prototype.getDirection = function (localAxis, mesh) {
  89588. if (mesh === void 0) { mesh = null; }
  89589. var result = BABYLON.Vector3.Zero();
  89590. this.getDirectionToRef(localAxis, mesh, result);
  89591. return result;
  89592. };
  89593. /**
  89594. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  89595. * @param localAxis The local direction that is used to compute the world direction
  89596. * @param mesh The mesh that this bone is attached to
  89597. * @param result The vector3 that the world direction will be copied to
  89598. */
  89599. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  89600. if (mesh === void 0) { mesh = null; }
  89601. var wm = null;
  89602. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89603. if (mesh) {
  89604. wm = mesh.getWorldMatrix();
  89605. }
  89606. this._skeleton.computeAbsoluteTransforms();
  89607. var mat = Bone._tmpMats[0];
  89608. mat.copyFrom(this.getAbsoluteTransform());
  89609. if (mesh && wm) {
  89610. mat.multiplyToRef(wm, mat);
  89611. }
  89612. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  89613. result.normalize();
  89614. };
  89615. /**
  89616. * Get the euler rotation of the bone in local or world space
  89617. * @param space The space that the rotation should be in
  89618. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89619. * @returns The euler rotation
  89620. */
  89621. Bone.prototype.getRotation = function (space, mesh) {
  89622. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89623. if (mesh === void 0) { mesh = null; }
  89624. var result = BABYLON.Vector3.Zero();
  89625. this.getRotationToRef(space, mesh, result);
  89626. return result;
  89627. };
  89628. /**
  89629. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  89630. * @param space The space that the rotation should be in
  89631. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89632. * @param result The vector3 that the rotation should be copied to
  89633. */
  89634. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  89635. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89636. if (mesh === void 0) { mesh = null; }
  89637. var quat = Bone._tmpQuat;
  89638. this.getRotationQuaternionToRef(space, mesh, quat);
  89639. quat.toEulerAnglesToRef(result);
  89640. };
  89641. /**
  89642. * Get the quaternion rotation of the bone in either local or world space
  89643. * @param space The space that the rotation should be in
  89644. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89645. * @returns The quaternion rotation
  89646. */
  89647. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  89648. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89649. if (mesh === void 0) { mesh = null; }
  89650. var result = BABYLON.Quaternion.Identity();
  89651. this.getRotationQuaternionToRef(space, mesh, result);
  89652. return result;
  89653. };
  89654. /**
  89655. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  89656. * @param space The space that the rotation should be in
  89657. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89658. * @param result The quaternion that the rotation should be copied to
  89659. */
  89660. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  89661. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89662. if (mesh === void 0) { mesh = null; }
  89663. if (space == BABYLON.Space.LOCAL) {
  89664. this._decompose();
  89665. result.copyFrom(this._localRotation);
  89666. }
  89667. else {
  89668. var mat = Bone._tmpMats[0];
  89669. var amat = this.getAbsoluteTransform();
  89670. if (mesh) {
  89671. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  89672. }
  89673. else {
  89674. mat.copyFrom(amat);
  89675. }
  89676. mat.m[0] *= this._scalingDeterminant;
  89677. mat.m[1] *= this._scalingDeterminant;
  89678. mat.m[2] *= this._scalingDeterminant;
  89679. mat.decompose(undefined, result, undefined);
  89680. }
  89681. };
  89682. /**
  89683. * Get the rotation matrix of the bone in local or world space
  89684. * @param space The space that the rotation should be in
  89685. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89686. * @returns The rotation matrix
  89687. */
  89688. Bone.prototype.getRotationMatrix = function (space, mesh) {
  89689. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89690. var result = BABYLON.Matrix.Identity();
  89691. this.getRotationMatrixToRef(space, mesh, result);
  89692. return result;
  89693. };
  89694. /**
  89695. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  89696. * @param space The space that the rotation should be in
  89697. * @param mesh The mesh that this bone is attached to. This is only used in world space
  89698. * @param result The quaternion that the rotation should be copied to
  89699. */
  89700. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  89701. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  89702. if (space == BABYLON.Space.LOCAL) {
  89703. this.getLocalMatrix().getRotationMatrixToRef(result);
  89704. }
  89705. else {
  89706. var mat = Bone._tmpMats[0];
  89707. var amat = this.getAbsoluteTransform();
  89708. if (mesh) {
  89709. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  89710. }
  89711. else {
  89712. mat.copyFrom(amat);
  89713. }
  89714. mat.m[0] *= this._scalingDeterminant;
  89715. mat.m[1] *= this._scalingDeterminant;
  89716. mat.m[2] *= this._scalingDeterminant;
  89717. mat.getRotationMatrixToRef(result);
  89718. }
  89719. };
  89720. /**
  89721. * Get the world position of a point that is in the local space of the bone
  89722. * @param position The local position
  89723. * @param mesh The mesh that this bone is attached to
  89724. * @returns The world position
  89725. */
  89726. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  89727. if (mesh === void 0) { mesh = null; }
  89728. var result = BABYLON.Vector3.Zero();
  89729. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  89730. return result;
  89731. };
  89732. /**
  89733. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  89734. * @param position The local position
  89735. * @param mesh The mesh that this bone is attached to
  89736. * @param result The vector3 that the world position should be copied to
  89737. */
  89738. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  89739. if (mesh === void 0) { mesh = null; }
  89740. var wm = null;
  89741. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89742. if (mesh) {
  89743. wm = mesh.getWorldMatrix();
  89744. }
  89745. this._skeleton.computeAbsoluteTransforms();
  89746. var tmat = Bone._tmpMats[0];
  89747. if (mesh && wm) {
  89748. tmat.copyFrom(this.getAbsoluteTransform());
  89749. tmat.multiplyToRef(wm, tmat);
  89750. }
  89751. else {
  89752. tmat = this.getAbsoluteTransform();
  89753. }
  89754. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  89755. };
  89756. /**
  89757. * Get the local position of a point that is in world space
  89758. * @param position The world position
  89759. * @param mesh The mesh that this bone is attached to
  89760. * @returns The local position
  89761. */
  89762. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  89763. if (mesh === void 0) { mesh = null; }
  89764. var result = BABYLON.Vector3.Zero();
  89765. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  89766. return result;
  89767. };
  89768. /**
  89769. * Get the local position of a point that is in world space and copy it to the result param
  89770. * @param position The world position
  89771. * @param mesh The mesh that this bone is attached to
  89772. * @param result The vector3 that the local position should be copied to
  89773. */
  89774. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  89775. if (mesh === void 0) { mesh = null; }
  89776. var wm = null;
  89777. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  89778. if (mesh) {
  89779. wm = mesh.getWorldMatrix();
  89780. }
  89781. this._skeleton.computeAbsoluteTransforms();
  89782. var tmat = Bone._tmpMats[0];
  89783. tmat.copyFrom(this.getAbsoluteTransform());
  89784. if (mesh && wm) {
  89785. tmat.multiplyToRef(wm, tmat);
  89786. }
  89787. tmat.invert();
  89788. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  89789. };
  89790. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  89791. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  89792. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  89793. return Bone;
  89794. }(BABYLON.Node));
  89795. BABYLON.Bone = Bone;
  89796. })(BABYLON || (BABYLON = {}));
  89797. //# sourceMappingURL=babylon.bone.js.map
  89798. var BABYLON;
  89799. (function (BABYLON) {
  89800. /**
  89801. * Class used to apply inverse kinematics to bones
  89802. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  89803. */
  89804. var BoneIKController = /** @class */ (function () {
  89805. /**
  89806. * Creates a new BoneIKController
  89807. * @param mesh defines the mesh to control
  89808. * @param bone defines the bone to control
  89809. * @param options defines options to set up the controller
  89810. */
  89811. function BoneIKController(mesh, bone, options) {
  89812. /**
  89813. * Gets or sets the target position
  89814. */
  89815. this.targetPosition = BABYLON.Vector3.Zero();
  89816. /**
  89817. * Gets or sets the pole target position
  89818. */
  89819. this.poleTargetPosition = BABYLON.Vector3.Zero();
  89820. /**
  89821. * Gets or sets the pole target local offset
  89822. */
  89823. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  89824. /**
  89825. * Gets or sets the pole angle
  89826. */
  89827. this.poleAngle = 0;
  89828. /**
  89829. * 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)
  89830. */
  89831. this.slerpAmount = 1;
  89832. this._bone1Quat = BABYLON.Quaternion.Identity();
  89833. this._bone1Mat = BABYLON.Matrix.Identity();
  89834. this._bone2Ang = Math.PI;
  89835. this._maxAngle = Math.PI;
  89836. this._rightHandedSystem = false;
  89837. this._bendAxis = BABYLON.Vector3.Right();
  89838. this._slerping = false;
  89839. this._adjustRoll = 0;
  89840. this._bone2 = bone;
  89841. this._bone1 = bone.getParent();
  89842. if (!this._bone1) {
  89843. return;
  89844. }
  89845. this.mesh = mesh;
  89846. var bonePos = bone.getPosition();
  89847. if (bone.getAbsoluteTransform().determinant() > 0) {
  89848. this._rightHandedSystem = true;
  89849. this._bendAxis.x = 0;
  89850. this._bendAxis.y = 0;
  89851. this._bendAxis.z = -1;
  89852. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  89853. this._adjustRoll = Math.PI * .5;
  89854. this._bendAxis.z = 1;
  89855. }
  89856. }
  89857. if (this._bone1.length) {
  89858. var boneScale1 = this._bone1.getScale();
  89859. var boneScale2 = this._bone2.getScale();
  89860. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  89861. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  89862. }
  89863. else if (this._bone1.children[0]) {
  89864. mesh.computeWorldMatrix(true);
  89865. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  89866. var pos2 = this._bone2.getAbsolutePosition(mesh);
  89867. var pos3 = this._bone1.getAbsolutePosition(mesh);
  89868. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  89869. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  89870. }
  89871. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  89872. this.maxAngle = Math.PI;
  89873. if (options) {
  89874. if (options.targetMesh) {
  89875. this.targetMesh = options.targetMesh;
  89876. this.targetMesh.computeWorldMatrix(true);
  89877. }
  89878. if (options.poleTargetMesh) {
  89879. this.poleTargetMesh = options.poleTargetMesh;
  89880. this.poleTargetMesh.computeWorldMatrix(true);
  89881. }
  89882. else if (options.poleTargetBone) {
  89883. this.poleTargetBone = options.poleTargetBone;
  89884. }
  89885. else if (this._bone1.getParent()) {
  89886. this.poleTargetBone = this._bone1.getParent();
  89887. }
  89888. if (options.poleTargetLocalOffset) {
  89889. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  89890. }
  89891. if (options.poleAngle) {
  89892. this.poleAngle = options.poleAngle;
  89893. }
  89894. if (options.bendAxis) {
  89895. this._bendAxis.copyFrom(options.bendAxis);
  89896. }
  89897. if (options.maxAngle) {
  89898. this.maxAngle = options.maxAngle;
  89899. }
  89900. if (options.slerpAmount) {
  89901. this.slerpAmount = options.slerpAmount;
  89902. }
  89903. }
  89904. }
  89905. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  89906. /**
  89907. * Gets or sets maximum allowed angle
  89908. */
  89909. get: function () {
  89910. return this._maxAngle;
  89911. },
  89912. set: function (value) {
  89913. this._setMaxAngle(value);
  89914. },
  89915. enumerable: true,
  89916. configurable: true
  89917. });
  89918. BoneIKController.prototype._setMaxAngle = function (ang) {
  89919. if (ang < 0) {
  89920. ang = 0;
  89921. }
  89922. if (ang > Math.PI || ang == undefined) {
  89923. ang = Math.PI;
  89924. }
  89925. this._maxAngle = ang;
  89926. var a = this._bone1Length;
  89927. var b = this._bone2Length;
  89928. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  89929. };
  89930. /**
  89931. * Force the controller to update the bones
  89932. */
  89933. BoneIKController.prototype.update = function () {
  89934. var bone1 = this._bone1;
  89935. if (!bone1) {
  89936. return;
  89937. }
  89938. var target = this.targetPosition;
  89939. var poleTarget = this.poleTargetPosition;
  89940. var mat1 = BoneIKController._tmpMats[0];
  89941. var mat2 = BoneIKController._tmpMats[1];
  89942. if (this.targetMesh) {
  89943. target.copyFrom(this.targetMesh.getAbsolutePosition());
  89944. }
  89945. if (this.poleTargetBone) {
  89946. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  89947. }
  89948. else if (this.poleTargetMesh) {
  89949. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  89950. }
  89951. var bonePos = BoneIKController._tmpVecs[0];
  89952. var zaxis = BoneIKController._tmpVecs[1];
  89953. var xaxis = BoneIKController._tmpVecs[2];
  89954. var yaxis = BoneIKController._tmpVecs[3];
  89955. var upAxis = BoneIKController._tmpVecs[4];
  89956. var _tmpQuat = BoneIKController._tmpQuat;
  89957. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  89958. poleTarget.subtractToRef(bonePos, upAxis);
  89959. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  89960. upAxis.y = 1;
  89961. }
  89962. else {
  89963. upAxis.normalize();
  89964. }
  89965. target.subtractToRef(bonePos, yaxis);
  89966. yaxis.normalize();
  89967. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  89968. zaxis.normalize();
  89969. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  89970. xaxis.normalize();
  89971. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  89972. var a = this._bone1Length;
  89973. var b = this._bone2Length;
  89974. var c = BABYLON.Vector3.Distance(bonePos, target);
  89975. if (this._maxReach > 0) {
  89976. c = Math.min(this._maxReach, c);
  89977. }
  89978. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  89979. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  89980. if (acosa > 1) {
  89981. acosa = 1;
  89982. }
  89983. if (acosb > 1) {
  89984. acosb = 1;
  89985. }
  89986. if (acosa < -1) {
  89987. acosa = -1;
  89988. }
  89989. if (acosb < -1) {
  89990. acosb = -1;
  89991. }
  89992. var angA = Math.acos(acosa);
  89993. var angB = Math.acos(acosb);
  89994. var angC = -angA - angB;
  89995. if (this._rightHandedSystem) {
  89996. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  89997. mat2.multiplyToRef(mat1, mat1);
  89998. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  89999. mat2.multiplyToRef(mat1, mat1);
  90000. }
  90001. else {
  90002. var _tmpVec = BoneIKController._tmpVecs[5];
  90003. _tmpVec.copyFrom(this._bendAxis);
  90004. _tmpVec.x *= -1;
  90005. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  90006. mat2.multiplyToRef(mat1, mat1);
  90007. }
  90008. if (this.poleAngle) {
  90009. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  90010. mat1.multiplyToRef(mat2, mat1);
  90011. }
  90012. if (this._bone1) {
  90013. if (this.slerpAmount < 1) {
  90014. if (!this._slerping) {
  90015. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  90016. }
  90017. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  90018. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  90019. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  90020. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  90021. this._slerping = true;
  90022. }
  90023. else {
  90024. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  90025. this._bone1Mat.copyFrom(mat1);
  90026. this._slerping = false;
  90027. }
  90028. }
  90029. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  90030. this._bone2Ang = angC;
  90031. };
  90032. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  90033. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  90034. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  90035. return BoneIKController;
  90036. }());
  90037. BABYLON.BoneIKController = BoneIKController;
  90038. })(BABYLON || (BABYLON = {}));
  90039. //# sourceMappingURL=babylon.boneIKController.js.map
  90040. var BABYLON;
  90041. (function (BABYLON) {
  90042. /**
  90043. * Class used to make a bone look toward a point in space
  90044. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  90045. */
  90046. var BoneLookController = /** @class */ (function () {
  90047. /**
  90048. * Create a BoneLookController
  90049. * @param mesh the mesh that the bone belongs to
  90050. * @param bone the bone that will be looking to the target
  90051. * @param target the target Vector3 to look at
  90052. * @param settings optional settings:
  90053. * * maxYaw: the maximum angle the bone will yaw to
  90054. * * minYaw: the minimum angle the bone will yaw to
  90055. * * maxPitch: the maximum angle the bone will pitch to
  90056. * * minPitch: the minimum angle the bone will yaw to
  90057. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  90058. * * upAxis: the up axis of the coordinate system
  90059. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  90060. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  90061. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  90062. * * adjustYaw: used to make an adjustment to the yaw of the bone
  90063. * * adjustPitch: used to make an adjustment to the pitch of the bone
  90064. * * adjustRoll: used to make an adjustment to the roll of the bone
  90065. **/
  90066. function BoneLookController(mesh, bone, target, options) {
  90067. /**
  90068. * The up axis of the coordinate system that is used when the bone is rotated
  90069. */
  90070. this.upAxis = BABYLON.Vector3.Up();
  90071. /**
  90072. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  90073. */
  90074. this.upAxisSpace = BABYLON.Space.LOCAL;
  90075. /**
  90076. * Used to make an adjustment to the yaw of the bone
  90077. */
  90078. this.adjustYaw = 0;
  90079. /**
  90080. * Used to make an adjustment to the pitch of the bone
  90081. */
  90082. this.adjustPitch = 0;
  90083. /**
  90084. * Used to make an adjustment to the roll of the bone
  90085. */
  90086. this.adjustRoll = 0;
  90087. /**
  90088. * 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)
  90089. */
  90090. this.slerpAmount = 1;
  90091. this._boneQuat = BABYLON.Quaternion.Identity();
  90092. this._slerping = false;
  90093. this._firstFrameSkipped = false;
  90094. this._fowardAxis = BABYLON.Vector3.Forward();
  90095. this.mesh = mesh;
  90096. this.bone = bone;
  90097. this.target = target;
  90098. if (options) {
  90099. if (options.adjustYaw) {
  90100. this.adjustYaw = options.adjustYaw;
  90101. }
  90102. if (options.adjustPitch) {
  90103. this.adjustPitch = options.adjustPitch;
  90104. }
  90105. if (options.adjustRoll) {
  90106. this.adjustRoll = options.adjustRoll;
  90107. }
  90108. if (options.maxYaw != null) {
  90109. this.maxYaw = options.maxYaw;
  90110. }
  90111. else {
  90112. this.maxYaw = Math.PI;
  90113. }
  90114. if (options.minYaw != null) {
  90115. this.minYaw = options.minYaw;
  90116. }
  90117. else {
  90118. this.minYaw = -Math.PI;
  90119. }
  90120. if (options.maxPitch != null) {
  90121. this.maxPitch = options.maxPitch;
  90122. }
  90123. else {
  90124. this.maxPitch = Math.PI;
  90125. }
  90126. if (options.minPitch != null) {
  90127. this.minPitch = options.minPitch;
  90128. }
  90129. else {
  90130. this.minPitch = -Math.PI;
  90131. }
  90132. if (options.slerpAmount != null) {
  90133. this.slerpAmount = options.slerpAmount;
  90134. }
  90135. if (options.upAxis != null) {
  90136. this.upAxis = options.upAxis;
  90137. }
  90138. if (options.upAxisSpace != null) {
  90139. this.upAxisSpace = options.upAxisSpace;
  90140. }
  90141. if (options.yawAxis != null || options.pitchAxis != null) {
  90142. var newYawAxis = BABYLON.Axis.Y;
  90143. var newPitchAxis = BABYLON.Axis.X;
  90144. if (options.yawAxis != null) {
  90145. newYawAxis = options.yawAxis.clone();
  90146. newYawAxis.normalize();
  90147. }
  90148. if (options.pitchAxis != null) {
  90149. newPitchAxis = options.pitchAxis.clone();
  90150. newPitchAxis.normalize();
  90151. }
  90152. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  90153. this._transformYawPitch = BABYLON.Matrix.Identity();
  90154. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  90155. this._transformYawPitchInv = this._transformYawPitch.clone();
  90156. this._transformYawPitch.invert();
  90157. }
  90158. }
  90159. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  90160. this.upAxisSpace = BABYLON.Space.LOCAL;
  90161. }
  90162. }
  90163. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  90164. /**
  90165. * Gets or sets the minimum yaw angle that the bone can look to
  90166. */
  90167. get: function () {
  90168. return this._minYaw;
  90169. },
  90170. set: function (value) {
  90171. this._minYaw = value;
  90172. this._minYawSin = Math.sin(value);
  90173. this._minYawCos = Math.cos(value);
  90174. if (this._maxYaw != null) {
  90175. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  90176. this._yawRange = this._maxYaw - this._minYaw;
  90177. }
  90178. },
  90179. enumerable: true,
  90180. configurable: true
  90181. });
  90182. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  90183. /**
  90184. * Gets or sets the maximum yaw angle that the bone can look to
  90185. */
  90186. get: function () {
  90187. return this._maxYaw;
  90188. },
  90189. set: function (value) {
  90190. this._maxYaw = value;
  90191. this._maxYawSin = Math.sin(value);
  90192. this._maxYawCos = Math.cos(value);
  90193. if (this._minYaw != null) {
  90194. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  90195. this._yawRange = this._maxYaw - this._minYaw;
  90196. }
  90197. },
  90198. enumerable: true,
  90199. configurable: true
  90200. });
  90201. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  90202. /**
  90203. * Gets or sets the minimum pitch angle that the bone can look to
  90204. */
  90205. get: function () {
  90206. return this._minPitch;
  90207. },
  90208. set: function (value) {
  90209. this._minPitch = value;
  90210. this._minPitchTan = Math.tan(value);
  90211. },
  90212. enumerable: true,
  90213. configurable: true
  90214. });
  90215. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  90216. /**
  90217. * Gets or sets the maximum pitch angle that the bone can look to
  90218. */
  90219. get: function () {
  90220. return this._maxPitch;
  90221. },
  90222. set: function (value) {
  90223. this._maxPitch = value;
  90224. this._maxPitchTan = Math.tan(value);
  90225. },
  90226. enumerable: true,
  90227. configurable: true
  90228. });
  90229. /**
  90230. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  90231. */
  90232. BoneLookController.prototype.update = function () {
  90233. //skip the first frame when slerping so that the mesh rotation is correct
  90234. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  90235. this._firstFrameSkipped = true;
  90236. return;
  90237. }
  90238. var bone = this.bone;
  90239. var bonePos = BoneLookController._tmpVecs[0];
  90240. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  90241. var target = this.target;
  90242. var _tmpMat1 = BoneLookController._tmpMats[0];
  90243. var _tmpMat2 = BoneLookController._tmpMats[1];
  90244. var mesh = this.mesh;
  90245. var parentBone = bone.getParent();
  90246. var upAxis = BoneLookController._tmpVecs[1];
  90247. upAxis.copyFrom(this.upAxis);
  90248. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  90249. if (this._transformYawPitch) {
  90250. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  90251. }
  90252. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  90253. }
  90254. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  90255. mesh.getDirectionToRef(upAxis, upAxis);
  90256. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  90257. upAxis.normalize();
  90258. }
  90259. }
  90260. var checkYaw = false;
  90261. var checkPitch = false;
  90262. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  90263. checkYaw = true;
  90264. }
  90265. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  90266. checkPitch = true;
  90267. }
  90268. if (checkYaw || checkPitch) {
  90269. var spaceMat = BoneLookController._tmpMats[2];
  90270. var spaceMatInv = BoneLookController._tmpMats[3];
  90271. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  90272. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  90273. }
  90274. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  90275. spaceMat.copyFrom(mesh.getWorldMatrix());
  90276. }
  90277. else {
  90278. var forwardAxis = BoneLookController._tmpVecs[2];
  90279. forwardAxis.copyFrom(this._fowardAxis);
  90280. if (this._transformYawPitch) {
  90281. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  90282. }
  90283. if (parentBone) {
  90284. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  90285. }
  90286. else {
  90287. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  90288. }
  90289. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  90290. rightAxis.normalize();
  90291. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  90292. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  90293. }
  90294. spaceMat.invertToRef(spaceMatInv);
  90295. var xzlen = null;
  90296. if (checkPitch) {
  90297. var localTarget = BoneLookController._tmpVecs[3];
  90298. target.subtractToRef(bonePos, localTarget);
  90299. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  90300. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  90301. var pitch = Math.atan2(localTarget.y, xzlen);
  90302. var newPitch = pitch;
  90303. if (pitch > this._maxPitch) {
  90304. localTarget.y = this._maxPitchTan * xzlen;
  90305. newPitch = this._maxPitch;
  90306. }
  90307. else if (pitch < this._minPitch) {
  90308. localTarget.y = this._minPitchTan * xzlen;
  90309. newPitch = this._minPitch;
  90310. }
  90311. if (pitch != newPitch) {
  90312. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  90313. localTarget.addInPlace(bonePos);
  90314. target = localTarget;
  90315. }
  90316. }
  90317. if (checkYaw) {
  90318. var localTarget = BoneLookController._tmpVecs[4];
  90319. target.subtractToRef(bonePos, localTarget);
  90320. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  90321. var yaw = Math.atan2(localTarget.x, localTarget.z);
  90322. var newYaw = yaw;
  90323. if (yaw > this._maxYaw || yaw < this._minYaw) {
  90324. if (xzlen == null) {
  90325. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  90326. }
  90327. if (this._yawRange > Math.PI) {
  90328. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  90329. localTarget.z = this._maxYawCos * xzlen;
  90330. localTarget.x = this._maxYawSin * xzlen;
  90331. newYaw = this._maxYaw;
  90332. }
  90333. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  90334. localTarget.z = this._minYawCos * xzlen;
  90335. localTarget.x = this._minYawSin * xzlen;
  90336. newYaw = this._minYaw;
  90337. }
  90338. }
  90339. else {
  90340. if (yaw > this._maxYaw) {
  90341. localTarget.z = this._maxYawCos * xzlen;
  90342. localTarget.x = this._maxYawSin * xzlen;
  90343. newYaw = this._maxYaw;
  90344. }
  90345. else if (yaw < this._minYaw) {
  90346. localTarget.z = this._minYawCos * xzlen;
  90347. localTarget.x = this._minYawSin * xzlen;
  90348. newYaw = this._minYaw;
  90349. }
  90350. }
  90351. }
  90352. if (this._slerping && this._yawRange > Math.PI) {
  90353. //are we going to be crossing into the min/max region?
  90354. var boneFwd = BoneLookController._tmpVecs[8];
  90355. boneFwd.copyFrom(BABYLON.Axis.Z);
  90356. if (this._transformYawPitch) {
  90357. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  90358. }
  90359. var boneRotMat = BoneLookController._tmpMats[4];
  90360. this._boneQuat.toRotationMatrix(boneRotMat);
  90361. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  90362. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  90363. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  90364. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  90365. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  90366. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  90367. if (angBtwTar > angBtwMidYaw) {
  90368. if (xzlen == null) {
  90369. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  90370. }
  90371. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  90372. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  90373. if (angBtwMin < angBtwMax) {
  90374. newYaw = boneYaw + Math.PI * .75;
  90375. localTarget.z = Math.cos(newYaw) * xzlen;
  90376. localTarget.x = Math.sin(newYaw) * xzlen;
  90377. }
  90378. else {
  90379. newYaw = boneYaw - Math.PI * .75;
  90380. localTarget.z = Math.cos(newYaw) * xzlen;
  90381. localTarget.x = Math.sin(newYaw) * xzlen;
  90382. }
  90383. }
  90384. }
  90385. if (yaw != newYaw) {
  90386. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  90387. localTarget.addInPlace(bonePos);
  90388. target = localTarget;
  90389. }
  90390. }
  90391. }
  90392. var zaxis = BoneLookController._tmpVecs[5];
  90393. var xaxis = BoneLookController._tmpVecs[6];
  90394. var yaxis = BoneLookController._tmpVecs[7];
  90395. var _tmpQuat = BoneLookController._tmpQuat;
  90396. target.subtractToRef(bonePos, zaxis);
  90397. zaxis.normalize();
  90398. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  90399. xaxis.normalize();
  90400. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  90401. yaxis.normalize();
  90402. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  90403. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  90404. return;
  90405. }
  90406. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  90407. return;
  90408. }
  90409. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  90410. return;
  90411. }
  90412. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  90413. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  90414. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  90415. }
  90416. if (this.slerpAmount < 1) {
  90417. if (!this._slerping) {
  90418. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  90419. }
  90420. if (this._transformYawPitch) {
  90421. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  90422. }
  90423. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  90424. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  90425. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  90426. this._slerping = true;
  90427. }
  90428. else {
  90429. if (this._transformYawPitch) {
  90430. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  90431. }
  90432. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  90433. this._slerping = false;
  90434. }
  90435. };
  90436. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  90437. var angDiff = ang2 - ang1;
  90438. angDiff %= Math.PI * 2;
  90439. if (angDiff > Math.PI) {
  90440. angDiff -= Math.PI * 2;
  90441. }
  90442. else if (angDiff < -Math.PI) {
  90443. angDiff += Math.PI * 2;
  90444. }
  90445. return angDiff;
  90446. };
  90447. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  90448. ang1 %= (2 * Math.PI);
  90449. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  90450. ang2 %= (2 * Math.PI);
  90451. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  90452. var ab = 0;
  90453. if (ang1 < ang2) {
  90454. ab = ang2 - ang1;
  90455. }
  90456. else {
  90457. ab = ang1 - ang2;
  90458. }
  90459. if (ab > Math.PI) {
  90460. ab = Math.PI * 2 - ab;
  90461. }
  90462. return ab;
  90463. };
  90464. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  90465. ang %= (2 * Math.PI);
  90466. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  90467. ang1 %= (2 * Math.PI);
  90468. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  90469. ang2 %= (2 * Math.PI);
  90470. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  90471. if (ang1 < ang2) {
  90472. if (ang > ang1 && ang < ang2) {
  90473. return true;
  90474. }
  90475. }
  90476. else {
  90477. if (ang > ang2 && ang < ang1) {
  90478. return true;
  90479. }
  90480. }
  90481. return false;
  90482. };
  90483. 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()];
  90484. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  90485. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  90486. return BoneLookController;
  90487. }());
  90488. BABYLON.BoneLookController = BoneLookController;
  90489. })(BABYLON || (BABYLON = {}));
  90490. //# sourceMappingURL=babylon.boneLookController.js.map
  90491. var BABYLON;
  90492. (function (BABYLON) {
  90493. /**
  90494. * Class used to handle skinning animations
  90495. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  90496. */
  90497. var Skeleton = /** @class */ (function () {
  90498. /**
  90499. * Creates a new skeleton
  90500. * @param name defines the skeleton name
  90501. * @param id defines the skeleton Id
  90502. * @param scene defines the hosting scene
  90503. */
  90504. function Skeleton(
  90505. /** defines the skeleton name */
  90506. name,
  90507. /** defines the skeleton Id */
  90508. id, scene) {
  90509. this.name = name;
  90510. this.id = id;
  90511. /**
  90512. * Gets the list of child bones
  90513. */
  90514. this.bones = new Array();
  90515. /**
  90516. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  90517. */
  90518. this.needInitialSkinMatrix = false;
  90519. this._isDirty = true;
  90520. this._meshesWithPoseMatrix = new Array();
  90521. this._identity = BABYLON.Matrix.Identity();
  90522. this._ranges = {};
  90523. this._lastAbsoluteTransformsUpdateId = -1;
  90524. /**
  90525. * Specifies if the skeleton should be serialized
  90526. */
  90527. this.doNotSerialize = false;
  90528. this._animationPropertiesOverride = null;
  90529. // Events
  90530. /**
  90531. * An observable triggered before computing the skeleton's matrices
  90532. */
  90533. this.onBeforeComputeObservable = new BABYLON.Observable();
  90534. this.bones = [];
  90535. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90536. scene.skeletons.push(this);
  90537. //make sure it will recalculate the matrix next time prepare is called.
  90538. this._isDirty = true;
  90539. }
  90540. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  90541. /**
  90542. * Gets or sets the animation properties override
  90543. */
  90544. get: function () {
  90545. if (!this._animationPropertiesOverride) {
  90546. return this._scene.animationPropertiesOverride;
  90547. }
  90548. return this._animationPropertiesOverride;
  90549. },
  90550. set: function (value) {
  90551. this._animationPropertiesOverride = value;
  90552. },
  90553. enumerable: true,
  90554. configurable: true
  90555. });
  90556. // Members
  90557. /**
  90558. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  90559. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  90560. * @returns a Float32Array containing matrices data
  90561. */
  90562. Skeleton.prototype.getTransformMatrices = function (mesh) {
  90563. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  90564. return mesh._bonesTransformMatrices;
  90565. }
  90566. if (!this._transformMatrices) {
  90567. this.prepare();
  90568. }
  90569. return this._transformMatrices;
  90570. };
  90571. /**
  90572. * Gets the current hosting scene
  90573. * @returns a scene object
  90574. */
  90575. Skeleton.prototype.getScene = function () {
  90576. return this._scene;
  90577. };
  90578. // Methods
  90579. /**
  90580. * Gets a string representing the current skeleton data
  90581. * @param fullDetails defines a boolean indicating if we want a verbose version
  90582. * @returns a string representing the current skeleton data
  90583. */
  90584. Skeleton.prototype.toString = function (fullDetails) {
  90585. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  90586. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  90587. if (fullDetails) {
  90588. ret += ", Ranges: {";
  90589. var first = true;
  90590. for (var name_1 in this._ranges) {
  90591. if (first) {
  90592. ret += ", ";
  90593. first = false;
  90594. }
  90595. ret += name_1;
  90596. }
  90597. ret += "}";
  90598. }
  90599. return ret;
  90600. };
  90601. /**
  90602. * Get bone's index searching by name
  90603. * @param name defines bone's name to search for
  90604. * @return the indice of the bone. Returns -1 if not found
  90605. */
  90606. Skeleton.prototype.getBoneIndexByName = function (name) {
  90607. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  90608. if (this.bones[boneIndex].name === name) {
  90609. return boneIndex;
  90610. }
  90611. }
  90612. return -1;
  90613. };
  90614. /**
  90615. * Creater a new animation range
  90616. * @param name defines the name of the range
  90617. * @param from defines the start key
  90618. * @param to defines the end key
  90619. */
  90620. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  90621. // check name not already in use
  90622. if (!this._ranges[name]) {
  90623. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  90624. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  90625. if (this.bones[i].animations[0]) {
  90626. this.bones[i].animations[0].createRange(name, from, to);
  90627. }
  90628. }
  90629. }
  90630. };
  90631. /**
  90632. * Delete a specific animation range
  90633. * @param name defines the name of the range
  90634. * @param deleteFrames defines if frames must be removed as well
  90635. */
  90636. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  90637. if (deleteFrames === void 0) { deleteFrames = true; }
  90638. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  90639. if (this.bones[i].animations[0]) {
  90640. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  90641. }
  90642. }
  90643. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  90644. };
  90645. /**
  90646. * Gets a specific animation range
  90647. * @param name defines the name of the range to look for
  90648. * @returns the requested animation range or null if not found
  90649. */
  90650. Skeleton.prototype.getAnimationRange = function (name) {
  90651. return this._ranges[name];
  90652. };
  90653. /**
  90654. * Gets the list of all animation ranges defined on this skeleton
  90655. * @returns an array
  90656. */
  90657. Skeleton.prototype.getAnimationRanges = function () {
  90658. var animationRanges = [];
  90659. var name;
  90660. var i = 0;
  90661. for (name in this._ranges) {
  90662. animationRanges[i] = this._ranges[name];
  90663. i++;
  90664. }
  90665. return animationRanges;
  90666. };
  90667. /**
  90668. * Copy animation range from a source skeleton.
  90669. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  90670. * @param source defines the source skeleton
  90671. * @param name defines the name of the range to copy
  90672. * @param rescaleAsRequired defines if rescaling must be applied if required
  90673. * @returns true if operation was successful
  90674. */
  90675. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  90676. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  90677. if (this._ranges[name] || !source.getAnimationRange(name)) {
  90678. return false;
  90679. }
  90680. var ret = true;
  90681. var frameOffset = this._getHighestAnimationFrame() + 1;
  90682. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  90683. var boneDict = {};
  90684. var sourceBones = source.bones;
  90685. var nBones;
  90686. var i;
  90687. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  90688. boneDict[sourceBones[i].name] = sourceBones[i];
  90689. }
  90690. if (this.bones.length !== sourceBones.length) {
  90691. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  90692. ret = false;
  90693. }
  90694. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  90695. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  90696. var boneName = this.bones[i].name;
  90697. var sourceBone = boneDict[boneName];
  90698. if (sourceBone) {
  90699. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  90700. }
  90701. else {
  90702. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  90703. ret = false;
  90704. }
  90705. }
  90706. // do not call createAnimationRange(), since it also is done to bones, which was already done
  90707. var range = source.getAnimationRange(name);
  90708. if (range) {
  90709. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  90710. }
  90711. return ret;
  90712. };
  90713. /**
  90714. * Forces the skeleton to go to rest pose
  90715. */
  90716. Skeleton.prototype.returnToRest = function () {
  90717. for (var index = 0; index < this.bones.length; index++) {
  90718. this.bones[index].returnToRest();
  90719. }
  90720. };
  90721. Skeleton.prototype._getHighestAnimationFrame = function () {
  90722. var ret = 0;
  90723. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  90724. if (this.bones[i].animations[0]) {
  90725. var highest = this.bones[i].animations[0].getHighestFrame();
  90726. if (ret < highest) {
  90727. ret = highest;
  90728. }
  90729. }
  90730. }
  90731. return ret;
  90732. };
  90733. /**
  90734. * Begin a specific animation range
  90735. * @param name defines the name of the range to start
  90736. * @param loop defines if looping must be turned on (false by default)
  90737. * @param speedRatio defines the speed ratio to apply (1 by default)
  90738. * @param onAnimationEnd defines a callback which will be called when animation will end
  90739. * @returns a new animatable
  90740. */
  90741. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  90742. var range = this.getAnimationRange(name);
  90743. if (!range) {
  90744. return null;
  90745. }
  90746. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  90747. };
  90748. /** @hidden */
  90749. Skeleton.prototype._markAsDirty = function () {
  90750. this._isDirty = true;
  90751. };
  90752. /** @hidden */
  90753. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  90754. this._meshesWithPoseMatrix.push(mesh);
  90755. };
  90756. /** @hidden */
  90757. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  90758. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  90759. if (index > -1) {
  90760. this._meshesWithPoseMatrix.splice(index, 1);
  90761. }
  90762. };
  90763. /** @hidden */
  90764. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  90765. this.onBeforeComputeObservable.notifyObservers(this);
  90766. for (var index = 0; index < this.bones.length; index++) {
  90767. var bone = this.bones[index];
  90768. var parentBone = bone.getParent();
  90769. if (parentBone) {
  90770. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  90771. }
  90772. else {
  90773. if (initialSkinMatrix) {
  90774. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  90775. }
  90776. else {
  90777. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  90778. }
  90779. }
  90780. if (bone._index !== -1) {
  90781. var mappedIndex = bone._index === null ? index : bone._index;
  90782. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  90783. }
  90784. }
  90785. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  90786. };
  90787. /**
  90788. * Build all resources required to render a skeleton
  90789. */
  90790. Skeleton.prototype.prepare = function () {
  90791. if (!this._isDirty) {
  90792. return;
  90793. }
  90794. if (this.needInitialSkinMatrix) {
  90795. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  90796. var mesh = this._meshesWithPoseMatrix[index];
  90797. var poseMatrix = mesh.getPoseMatrix();
  90798. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  90799. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  90800. }
  90801. if (this._synchronizedWithMesh !== mesh) {
  90802. this._synchronizedWithMesh = mesh;
  90803. // Prepare bones
  90804. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  90805. var bone = this.bones[boneIndex];
  90806. if (!bone.getParent()) {
  90807. var matrix = bone.getBaseMatrix();
  90808. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  90809. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  90810. }
  90811. }
  90812. }
  90813. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  90814. }
  90815. }
  90816. else {
  90817. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  90818. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  90819. }
  90820. this._computeTransformMatrices(this._transformMatrices, null);
  90821. }
  90822. this._isDirty = false;
  90823. this._scene._activeBones.addCount(this.bones.length, false);
  90824. };
  90825. /**
  90826. * Gets the list of animatables currently running for this skeleton
  90827. * @returns an array of animatables
  90828. */
  90829. Skeleton.prototype.getAnimatables = function () {
  90830. if (!this._animatables || this._animatables.length !== this.bones.length) {
  90831. this._animatables = [];
  90832. for (var index = 0; index < this.bones.length; index++) {
  90833. this._animatables.push(this.bones[index]);
  90834. }
  90835. }
  90836. return this._animatables;
  90837. };
  90838. /**
  90839. * Clone the current skeleton
  90840. * @param name defines the name of the new skeleton
  90841. * @param id defines the id of the enw skeleton
  90842. * @returns the new skeleton
  90843. */
  90844. Skeleton.prototype.clone = function (name, id) {
  90845. var result = new Skeleton(name, id || name, this._scene);
  90846. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  90847. for (var index = 0; index < this.bones.length; index++) {
  90848. var source = this.bones[index];
  90849. var parentBone = null;
  90850. var parent_1 = source.getParent();
  90851. if (parent_1) {
  90852. var parentIndex = this.bones.indexOf(parent_1);
  90853. parentBone = result.bones[parentIndex];
  90854. }
  90855. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  90856. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  90857. }
  90858. if (this._ranges) {
  90859. result._ranges = {};
  90860. for (var rangeName in this._ranges) {
  90861. var range = this._ranges[rangeName];
  90862. if (range) {
  90863. result._ranges[rangeName] = range.clone();
  90864. }
  90865. }
  90866. }
  90867. this._isDirty = true;
  90868. return result;
  90869. };
  90870. /**
  90871. * Enable animation blending for this skeleton
  90872. * @param blendingSpeed defines the blending speed to apply
  90873. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  90874. */
  90875. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  90876. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  90877. this.bones.forEach(function (bone) {
  90878. bone.animations.forEach(function (animation) {
  90879. animation.enableBlending = true;
  90880. animation.blendingSpeed = blendingSpeed;
  90881. });
  90882. });
  90883. };
  90884. /**
  90885. * Releases all resources associated with the current skeleton
  90886. */
  90887. Skeleton.prototype.dispose = function () {
  90888. this._meshesWithPoseMatrix = [];
  90889. // Animations
  90890. this.getScene().stopAnimation(this);
  90891. // Remove from scene
  90892. this.getScene().removeSkeleton(this);
  90893. };
  90894. /**
  90895. * Serialize the skeleton in a JSON object
  90896. * @returns a JSON object
  90897. */
  90898. Skeleton.prototype.serialize = function () {
  90899. var serializationObject = {};
  90900. serializationObject.name = this.name;
  90901. serializationObject.id = this.id;
  90902. if (this.dimensionsAtRest) {
  90903. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  90904. }
  90905. serializationObject.bones = [];
  90906. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  90907. for (var index = 0; index < this.bones.length; index++) {
  90908. var bone = this.bones[index];
  90909. var parent_2 = bone.getParent();
  90910. var serializedBone = {
  90911. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  90912. name: bone.name,
  90913. matrix: bone.getBaseMatrix().toArray(),
  90914. rest: bone.getRestPose().toArray()
  90915. };
  90916. serializationObject.bones.push(serializedBone);
  90917. if (bone.length) {
  90918. serializedBone.length = bone.length;
  90919. }
  90920. if (bone.metadata) {
  90921. serializedBone.metadata = bone.metadata;
  90922. }
  90923. if (bone.animations && bone.animations.length > 0) {
  90924. serializedBone.animation = bone.animations[0].serialize();
  90925. }
  90926. serializationObject.ranges = [];
  90927. for (var name in this._ranges) {
  90928. var source = this._ranges[name];
  90929. if (!source) {
  90930. continue;
  90931. }
  90932. var range = {};
  90933. range.name = name;
  90934. range.from = source.from;
  90935. range.to = source.to;
  90936. serializationObject.ranges.push(range);
  90937. }
  90938. }
  90939. return serializationObject;
  90940. };
  90941. /**
  90942. * Creates a new skeleton from serialized data
  90943. * @param parsedSkeleton defines the serialized data
  90944. * @param scene defines the hosting scene
  90945. * @returns a new skeleton
  90946. */
  90947. Skeleton.Parse = function (parsedSkeleton, scene) {
  90948. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  90949. if (parsedSkeleton.dimensionsAtRest) {
  90950. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  90951. }
  90952. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  90953. var index;
  90954. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  90955. var parsedBone = parsedSkeleton.bones[index];
  90956. var parentBone = null;
  90957. if (parsedBone.parentBoneIndex > -1) {
  90958. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  90959. }
  90960. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  90961. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  90962. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  90963. bone.id = parsedBone.id;
  90964. }
  90965. if (parsedBone.length) {
  90966. bone.length = parsedBone.length;
  90967. }
  90968. if (parsedBone.metadata) {
  90969. bone.metadata = parsedBone.metadata;
  90970. }
  90971. if (parsedBone.animation) {
  90972. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  90973. }
  90974. }
  90975. // placed after bones, so createAnimationRange can cascade down
  90976. if (parsedSkeleton.ranges) {
  90977. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  90978. var data = parsedSkeleton.ranges[index];
  90979. skeleton.createAnimationRange(data.name, data.from, data.to);
  90980. }
  90981. }
  90982. return skeleton;
  90983. };
  90984. /**
  90985. * Compute all node absolute transforms
  90986. * @param forceUpdate defines if computation must be done even if cache is up to date
  90987. */
  90988. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  90989. if (forceUpdate === void 0) { forceUpdate = false; }
  90990. var renderId = this._scene.getRenderId();
  90991. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  90992. this.bones[0].computeAbsoluteTransforms();
  90993. this._lastAbsoluteTransformsUpdateId = renderId;
  90994. }
  90995. };
  90996. /**
  90997. * Gets the root pose matrix
  90998. * @returns a matrix
  90999. */
  91000. Skeleton.prototype.getPoseMatrix = function () {
  91001. var poseMatrix = null;
  91002. if (this._meshesWithPoseMatrix.length > 0) {
  91003. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  91004. }
  91005. return poseMatrix;
  91006. };
  91007. /**
  91008. * Sorts bones per internal index
  91009. */
  91010. Skeleton.prototype.sortBones = function () {
  91011. var bones = new Array();
  91012. var visited = new Array(this.bones.length);
  91013. for (var index = 0; index < this.bones.length; index++) {
  91014. this._sortBones(index, bones, visited);
  91015. }
  91016. this.bones = bones;
  91017. };
  91018. Skeleton.prototype._sortBones = function (index, bones, visited) {
  91019. if (visited[index]) {
  91020. return;
  91021. }
  91022. visited[index] = true;
  91023. var bone = this.bones[index];
  91024. if (bone._index === undefined) {
  91025. bone._index = index;
  91026. }
  91027. var parentBone = bone.getParent();
  91028. if (parentBone) {
  91029. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  91030. }
  91031. bones.push(bone);
  91032. };
  91033. return Skeleton;
  91034. }());
  91035. BABYLON.Skeleton = Skeleton;
  91036. })(BABYLON || (BABYLON = {}));
  91037. //# sourceMappingURL=babylon.skeleton.js.map
  91038. var BABYLON;
  91039. (function (BABYLON) {
  91040. ;
  91041. /**
  91042. * This groups tools to convert HDR texture to native colors array.
  91043. */
  91044. var HDRTools = /** @class */ (function () {
  91045. function HDRTools() {
  91046. }
  91047. HDRTools.Ldexp = function (mantissa, exponent) {
  91048. if (exponent > 1023) {
  91049. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  91050. }
  91051. if (exponent < -1074) {
  91052. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  91053. }
  91054. return mantissa * Math.pow(2, exponent);
  91055. };
  91056. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  91057. if (exponent > 0) { /*nonzero pixel*/
  91058. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  91059. float32array[index + 0] = red * exponent;
  91060. float32array[index + 1] = green * exponent;
  91061. float32array[index + 2] = blue * exponent;
  91062. }
  91063. else {
  91064. float32array[index + 0] = 0;
  91065. float32array[index + 1] = 0;
  91066. float32array[index + 2] = 0;
  91067. }
  91068. };
  91069. HDRTools.readStringLine = function (uint8array, startIndex) {
  91070. var line = "";
  91071. var character = "";
  91072. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  91073. character = String.fromCharCode(uint8array[i]);
  91074. if (character == "\n") {
  91075. break;
  91076. }
  91077. line += character;
  91078. }
  91079. return line;
  91080. };
  91081. /**
  91082. * Reads header information from an RGBE texture stored in a native array.
  91083. * More information on this format are available here:
  91084. * https://en.wikipedia.org/wiki/RGBE_image_format
  91085. *
  91086. * @param uint8array The binary file stored in native array.
  91087. * @return The header information.
  91088. */
  91089. HDRTools.RGBE_ReadHeader = function (uint8array) {
  91090. var height = 0;
  91091. var width = 0;
  91092. var line = this.readStringLine(uint8array, 0);
  91093. if (line[0] != '#' || line[1] != '?') {
  91094. throw "Bad HDR Format.";
  91095. }
  91096. var endOfHeader = false;
  91097. var findFormat = false;
  91098. var lineIndex = 0;
  91099. do {
  91100. lineIndex += (line.length + 1);
  91101. line = this.readStringLine(uint8array, lineIndex);
  91102. if (line == "FORMAT=32-bit_rle_rgbe") {
  91103. findFormat = true;
  91104. }
  91105. else if (line.length == 0) {
  91106. endOfHeader = true;
  91107. }
  91108. } while (!endOfHeader);
  91109. if (!findFormat) {
  91110. throw "HDR Bad header format, unsupported FORMAT";
  91111. }
  91112. lineIndex += (line.length + 1);
  91113. line = this.readStringLine(uint8array, lineIndex);
  91114. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  91115. var match = sizeRegexp.exec(line);
  91116. // TODO. Support +Y and -X if needed.
  91117. if (!match || match.length < 3) {
  91118. throw "HDR Bad header format, no size";
  91119. }
  91120. width = parseInt(match[2]);
  91121. height = parseInt(match[1]);
  91122. if (width < 8 || width > 0x7fff) {
  91123. throw "HDR Bad header format, unsupported size";
  91124. }
  91125. lineIndex += (line.length + 1);
  91126. return {
  91127. height: height,
  91128. width: width,
  91129. dataPosition: lineIndex
  91130. };
  91131. };
  91132. /**
  91133. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  91134. * This RGBE texture needs to store the information as a panorama.
  91135. *
  91136. * More information on this format are available here:
  91137. * https://en.wikipedia.org/wiki/RGBE_image_format
  91138. *
  91139. * @param buffer The binary file stored in an array buffer.
  91140. * @param size The expected size of the extracted cubemap.
  91141. * @return The Cube Map information.
  91142. */
  91143. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  91144. var uint8array = new Uint8Array(buffer);
  91145. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  91146. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  91147. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  91148. return cubeMapData;
  91149. };
  91150. /**
  91151. * Returns the pixels data extracted from an RGBE texture.
  91152. * This pixels will be stored left to right up to down in the R G B order in one array.
  91153. *
  91154. * More information on this format are available here:
  91155. * https://en.wikipedia.org/wiki/RGBE_image_format
  91156. *
  91157. * @param uint8array The binary file stored in an array buffer.
  91158. * @param hdrInfo The header information of the file.
  91159. * @return The pixels data in RGB right to left up to down order.
  91160. */
  91161. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  91162. // Keep for multi format supports.
  91163. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  91164. };
  91165. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  91166. var num_scanlines = hdrInfo.height;
  91167. var scanline_width = hdrInfo.width;
  91168. var a, b, c, d, count;
  91169. var dataIndex = hdrInfo.dataPosition;
  91170. var index = 0, endIndex = 0, i = 0;
  91171. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  91172. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  91173. // 3 channels of 4 bytes per pixel in float.
  91174. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  91175. var resultArray = new Float32Array(resultBuffer);
  91176. // read in each successive scanline
  91177. while (num_scanlines > 0) {
  91178. a = uint8array[dataIndex++];
  91179. b = uint8array[dataIndex++];
  91180. c = uint8array[dataIndex++];
  91181. d = uint8array[dataIndex++];
  91182. if (a != 2 || b != 2 || (c & 0x80)) {
  91183. // this file is not run length encoded
  91184. throw "HDR Bad header format, not RLE";
  91185. }
  91186. if (((c << 8) | d) != scanline_width) {
  91187. throw "HDR Bad header format, wrong scan line width";
  91188. }
  91189. index = 0;
  91190. // read each of the four channels for the scanline into the buffer
  91191. for (i = 0; i < 4; i++) {
  91192. endIndex = (i + 1) * scanline_width;
  91193. while (index < endIndex) {
  91194. a = uint8array[dataIndex++];
  91195. b = uint8array[dataIndex++];
  91196. if (a > 128) {
  91197. // a run of the same value
  91198. count = a - 128;
  91199. if ((count == 0) || (count > endIndex - index)) {
  91200. throw "HDR Bad Format, bad scanline data (run)";
  91201. }
  91202. while (count-- > 0) {
  91203. scanLineArray[index++] = b;
  91204. }
  91205. }
  91206. else {
  91207. // a non-run
  91208. count = a;
  91209. if ((count == 0) || (count > endIndex - index)) {
  91210. throw "HDR Bad Format, bad scanline data (non-run)";
  91211. }
  91212. scanLineArray[index++] = b;
  91213. if (--count > 0) {
  91214. for (var j = 0; j < count; j++) {
  91215. scanLineArray[index++] = uint8array[dataIndex++];
  91216. }
  91217. }
  91218. }
  91219. }
  91220. }
  91221. // now convert data from buffer into floats
  91222. for (i = 0; i < scanline_width; i++) {
  91223. a = scanLineArray[i];
  91224. b = scanLineArray[i + scanline_width];
  91225. c = scanLineArray[i + 2 * scanline_width];
  91226. d = scanLineArray[i + 3 * scanline_width];
  91227. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  91228. }
  91229. num_scanlines--;
  91230. }
  91231. return resultArray;
  91232. };
  91233. return HDRTools;
  91234. }());
  91235. BABYLON.HDRTools = HDRTools;
  91236. })(BABYLON || (BABYLON = {}));
  91237. //# sourceMappingURL=babylon.hdr.js.map
  91238. var BABYLON;
  91239. (function (BABYLON) {
  91240. /**
  91241. * This represents a texture coming from an HDR input.
  91242. *
  91243. * The only supported format is currently panorama picture stored in RGBE format.
  91244. * Example of such files can be found on HDRLib: http://hdrlib.com/
  91245. */
  91246. var HDRCubeTexture = /** @class */ (function (_super) {
  91247. __extends(HDRCubeTexture, _super);
  91248. /**
  91249. * Instantiates an HDRTexture from the following parameters.
  91250. *
  91251. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  91252. * @param scene The scene the texture will be used in
  91253. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  91254. * @param noMipmap Forces to not generate the mipmap if true
  91255. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  91256. * @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)
  91257. * @param reserved Reserved flag for internal use.
  91258. */
  91259. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  91260. if (noMipmap === void 0) { noMipmap = false; }
  91261. if (generateHarmonics === void 0) { generateHarmonics = true; }
  91262. if (gammaSpace === void 0) { gammaSpace = false; }
  91263. if (reserved === void 0) { reserved = false; }
  91264. if (onLoad === void 0) { onLoad = null; }
  91265. if (onError === void 0) { onError = null; }
  91266. var _this = _super.call(this, scene) || this;
  91267. _this._generateHarmonics = true;
  91268. _this._onLoad = null;
  91269. _this._onError = null;
  91270. /**
  91271. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  91272. */
  91273. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  91274. _this._isBlocking = true;
  91275. _this._rotationY = 0;
  91276. /**
  91277. * Gets or sets the center of the bounding box associated with the cube texture
  91278. * It must define where the camera used to render the texture was set
  91279. */
  91280. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  91281. if (!url) {
  91282. return _this;
  91283. }
  91284. _this.name = url;
  91285. _this.url = url;
  91286. _this.hasAlpha = false;
  91287. _this.isCube = true;
  91288. _this._textureMatrix = BABYLON.Matrix.Identity();
  91289. _this._onLoad = onLoad;
  91290. _this._onError = onError;
  91291. _this.gammaSpace = gammaSpace;
  91292. _this._noMipmap = noMipmap;
  91293. _this._size = size;
  91294. _this._texture = _this._getFromCache(url, _this._noMipmap);
  91295. if (!_this._texture) {
  91296. if (!scene.useDelayedTextureLoading) {
  91297. _this.loadTexture();
  91298. }
  91299. else {
  91300. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  91301. }
  91302. }
  91303. return _this;
  91304. }
  91305. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  91306. /**
  91307. * Gets wether or not the texture is blocking during loading.
  91308. */
  91309. get: function () {
  91310. return this._isBlocking;
  91311. },
  91312. /**
  91313. * Sets wether or not the texture is blocking during loading.
  91314. */
  91315. set: function (value) {
  91316. this._isBlocking = value;
  91317. },
  91318. enumerable: true,
  91319. configurable: true
  91320. });
  91321. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  91322. /**
  91323. * Gets texture matrix rotation angle around Y axis radians.
  91324. */
  91325. get: function () {
  91326. return this._rotationY;
  91327. },
  91328. /**
  91329. * Sets texture matrix rotation angle around Y axis in radians.
  91330. */
  91331. set: function (value) {
  91332. this._rotationY = value;
  91333. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  91334. },
  91335. enumerable: true,
  91336. configurable: true
  91337. });
  91338. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  91339. get: function () {
  91340. return this._boundingBoxSize;
  91341. },
  91342. /**
  91343. * Gets or sets the size of the bounding box associated with the cube texture
  91344. * When defined, the cubemap will switch to local mode
  91345. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  91346. * @example https://www.babylonjs-playground.com/#RNASML
  91347. */
  91348. set: function (value) {
  91349. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  91350. return;
  91351. }
  91352. this._boundingBoxSize = value;
  91353. var scene = this.getScene();
  91354. if (scene) {
  91355. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  91356. }
  91357. },
  91358. enumerable: true,
  91359. configurable: true
  91360. });
  91361. /**
  91362. * Occurs when the file is raw .hdr file.
  91363. */
  91364. HDRCubeTexture.prototype.loadTexture = function () {
  91365. var _this = this;
  91366. var callback = function (buffer) {
  91367. _this.lodGenerationOffset = 0.0;
  91368. _this.lodGenerationScale = 0.8;
  91369. var scene = _this.getScene();
  91370. if (!scene) {
  91371. return null;
  91372. }
  91373. // Extract the raw linear data.
  91374. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  91375. // Generate harmonics if needed.
  91376. if (_this._generateHarmonics) {
  91377. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  91378. _this.sphericalPolynomial = sphericalPolynomial;
  91379. }
  91380. var results = [];
  91381. var byteArray = null;
  91382. // Push each faces.
  91383. for (var j = 0; j < 6; j++) {
  91384. // Create uintarray fallback.
  91385. if (!scene.getEngine().getCaps().textureFloat) {
  91386. // 3 channels of 1 bytes per pixel in bytes.
  91387. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  91388. byteArray = new Uint8Array(byteBuffer);
  91389. }
  91390. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  91391. // If special cases.
  91392. if (_this.gammaSpace || byteArray) {
  91393. for (var i = 0; i < _this._size * _this._size; i++) {
  91394. // Put in gamma space if requested.
  91395. if (_this.gammaSpace) {
  91396. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  91397. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  91398. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  91399. }
  91400. // Convert to int texture for fallback.
  91401. if (byteArray) {
  91402. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  91403. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  91404. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  91405. // May use luminance instead if the result is not accurate.
  91406. var max = Math.max(Math.max(r, g), b);
  91407. if (max > 255) {
  91408. var scale = 255 / max;
  91409. r *= scale;
  91410. g *= scale;
  91411. b *= scale;
  91412. }
  91413. byteArray[(i * 3) + 0] = r;
  91414. byteArray[(i * 3) + 1] = g;
  91415. byteArray[(i * 3) + 2] = b;
  91416. }
  91417. }
  91418. }
  91419. if (byteArray) {
  91420. results.push(byteArray);
  91421. }
  91422. else {
  91423. results.push(dataFace);
  91424. }
  91425. }
  91426. return results;
  91427. };
  91428. var scene = this.getScene();
  91429. if (scene) {
  91430. 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);
  91431. }
  91432. };
  91433. HDRCubeTexture.prototype.clone = function () {
  91434. var scene = this.getScene();
  91435. if (!scene) {
  91436. return this;
  91437. }
  91438. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  91439. // Base texture
  91440. newTexture.level = this.level;
  91441. newTexture.wrapU = this.wrapU;
  91442. newTexture.wrapV = this.wrapV;
  91443. newTexture.coordinatesIndex = this.coordinatesIndex;
  91444. newTexture.coordinatesMode = this.coordinatesMode;
  91445. return newTexture;
  91446. };
  91447. // Methods
  91448. HDRCubeTexture.prototype.delayLoad = function () {
  91449. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  91450. return;
  91451. }
  91452. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  91453. this._texture = this._getFromCache(this.url, this._noMipmap);
  91454. if (!this._texture) {
  91455. this.loadTexture();
  91456. }
  91457. };
  91458. /**
  91459. * Get the texture reflection matrix used to rotate/transform the reflection.
  91460. * @returns the reflection matrix
  91461. */
  91462. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  91463. return this._textureMatrix;
  91464. };
  91465. /**
  91466. * Set the texture reflection matrix used to rotate/transform the reflection.
  91467. * @param value Define the reflection matrix to set
  91468. */
  91469. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  91470. this._textureMatrix = value;
  91471. };
  91472. /**
  91473. * Parses a JSON representation of an HDR Texture in order to create the texture
  91474. * @param parsedTexture Define the JSON representation
  91475. * @param scene Define the scene the texture should be created in
  91476. * @param rootUrl Define the root url in case we need to load relative dependencies
  91477. * @returns the newly created texture after parsing
  91478. */
  91479. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  91480. var texture = null;
  91481. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  91482. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  91483. texture.name = parsedTexture.name;
  91484. texture.hasAlpha = parsedTexture.hasAlpha;
  91485. texture.level = parsedTexture.level;
  91486. texture.coordinatesMode = parsedTexture.coordinatesMode;
  91487. texture.isBlocking = parsedTexture.isBlocking;
  91488. }
  91489. if (texture) {
  91490. if (parsedTexture.boundingBoxPosition) {
  91491. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  91492. }
  91493. if (parsedTexture.boundingBoxSize) {
  91494. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  91495. }
  91496. if (parsedTexture.rotationY) {
  91497. texture.rotationY = parsedTexture.rotationY;
  91498. }
  91499. }
  91500. return texture;
  91501. };
  91502. HDRCubeTexture.prototype.serialize = function () {
  91503. if (!this.name) {
  91504. return null;
  91505. }
  91506. var serializationObject = {};
  91507. serializationObject.name = this.name;
  91508. serializationObject.hasAlpha = this.hasAlpha;
  91509. serializationObject.isCube = true;
  91510. serializationObject.level = this.level;
  91511. serializationObject.size = this._size;
  91512. serializationObject.coordinatesMode = this.coordinatesMode;
  91513. serializationObject.useInGammaSpace = this.gammaSpace;
  91514. serializationObject.generateHarmonics = this._generateHarmonics;
  91515. serializationObject.customType = "BABYLON.HDRCubeTexture";
  91516. serializationObject.noMipmap = this._noMipmap;
  91517. serializationObject.isBlocking = this._isBlocking;
  91518. serializationObject.rotationY = this._rotationY;
  91519. return serializationObject;
  91520. };
  91521. HDRCubeTexture._facesMapping = [
  91522. "right",
  91523. "left",
  91524. "up",
  91525. "down",
  91526. "front",
  91527. "back"
  91528. ];
  91529. return HDRCubeTexture;
  91530. }(BABYLON.BaseTexture));
  91531. BABYLON.HDRCubeTexture = HDRCubeTexture;
  91532. })(BABYLON || (BABYLON = {}));
  91533. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  91534. var BABYLON;
  91535. (function (BABYLON) {
  91536. /**
  91537. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  91538. */
  91539. var PanoramaToCubeMapTools = /** @class */ (function () {
  91540. function PanoramaToCubeMapTools() {
  91541. }
  91542. /**
  91543. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  91544. *
  91545. * @param float32Array The source data.
  91546. * @param inputWidth The width of the input panorama.
  91547. * @param inputhHeight The height of the input panorama.
  91548. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  91549. * @return The cubemap data
  91550. */
  91551. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  91552. if (!float32Array) {
  91553. throw "ConvertPanoramaToCubemap: input cannot be null";
  91554. }
  91555. if (float32Array.length != inputWidth * inputHeight * 3) {
  91556. throw "ConvertPanoramaToCubemap: input size is wrong";
  91557. }
  91558. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  91559. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  91560. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  91561. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  91562. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  91563. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  91564. return {
  91565. front: textureFront,
  91566. back: textureBack,
  91567. left: textureLeft,
  91568. right: textureRight,
  91569. up: textureUp,
  91570. down: textureDown,
  91571. size: size,
  91572. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  91573. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  91574. gammaSpace: false,
  91575. };
  91576. };
  91577. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  91578. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  91579. var textureArray = new Float32Array(buffer);
  91580. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  91581. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  91582. var dy = 1 / texSize;
  91583. var fy = 0;
  91584. for (var y = 0; y < texSize; y++) {
  91585. var xv1 = faceData[0];
  91586. var xv2 = faceData[2];
  91587. for (var x = 0; x < texSize; x++) {
  91588. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  91589. v.normalize();
  91590. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  91591. // 3 channels per pixels
  91592. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  91593. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  91594. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  91595. xv1 = xv1.add(rotDX1);
  91596. xv2 = xv2.add(rotDX2);
  91597. }
  91598. fy += dy;
  91599. }
  91600. return textureArray;
  91601. };
  91602. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  91603. var theta = Math.atan2(vDir.z, vDir.x);
  91604. var phi = Math.acos(vDir.y);
  91605. while (theta < -Math.PI)
  91606. theta += 2 * Math.PI;
  91607. while (theta > Math.PI)
  91608. theta -= 2 * Math.PI;
  91609. var dx = theta / Math.PI;
  91610. var dy = phi / Math.PI;
  91611. // recenter.
  91612. dx = dx * 0.5 + 0.5;
  91613. var px = Math.round(dx * inputWidth);
  91614. if (px < 0)
  91615. px = 0;
  91616. else if (px >= inputWidth)
  91617. px = inputWidth - 1;
  91618. var py = Math.round(dy * inputHeight);
  91619. if (py < 0)
  91620. py = 0;
  91621. else if (py >= inputHeight)
  91622. py = inputHeight - 1;
  91623. var inputY = (inputHeight - py - 1);
  91624. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  91625. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  91626. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  91627. return {
  91628. r: r,
  91629. g: g,
  91630. b: b
  91631. };
  91632. };
  91633. PanoramaToCubeMapTools.FACE_FRONT = [
  91634. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  91635. new BABYLON.Vector3(1.0, -1.0, -1.0),
  91636. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  91637. new BABYLON.Vector3(1.0, 1.0, -1.0)
  91638. ];
  91639. PanoramaToCubeMapTools.FACE_BACK = [
  91640. new BABYLON.Vector3(1.0, -1.0, 1.0),
  91641. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  91642. new BABYLON.Vector3(1.0, 1.0, 1.0),
  91643. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  91644. ];
  91645. PanoramaToCubeMapTools.FACE_RIGHT = [
  91646. new BABYLON.Vector3(1.0, -1.0, -1.0),
  91647. new BABYLON.Vector3(1.0, -1.0, 1.0),
  91648. new BABYLON.Vector3(1.0, 1.0, -1.0),
  91649. new BABYLON.Vector3(1.0, 1.0, 1.0)
  91650. ];
  91651. PanoramaToCubeMapTools.FACE_LEFT = [
  91652. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  91653. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  91654. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  91655. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  91656. ];
  91657. PanoramaToCubeMapTools.FACE_DOWN = [
  91658. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  91659. new BABYLON.Vector3(1.0, 1.0, -1.0),
  91660. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  91661. new BABYLON.Vector3(1.0, 1.0, 1.0)
  91662. ];
  91663. PanoramaToCubeMapTools.FACE_UP = [
  91664. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  91665. new BABYLON.Vector3(1.0, -1.0, 1.0),
  91666. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  91667. new BABYLON.Vector3(1.0, -1.0, -1.0)
  91668. ];
  91669. return PanoramaToCubeMapTools;
  91670. }());
  91671. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  91672. })(BABYLON || (BABYLON = {}));
  91673. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  91674. var BABYLON;
  91675. (function (BABYLON) {
  91676. var IndexedVector2 = /** @class */ (function (_super) {
  91677. __extends(IndexedVector2, _super);
  91678. function IndexedVector2(original, index) {
  91679. var _this = _super.call(this, original.x, original.y) || this;
  91680. _this.index = index;
  91681. return _this;
  91682. }
  91683. return IndexedVector2;
  91684. }(BABYLON.Vector2));
  91685. var PolygonPoints = /** @class */ (function () {
  91686. function PolygonPoints() {
  91687. this.elements = new Array();
  91688. }
  91689. PolygonPoints.prototype.add = function (originalPoints) {
  91690. var _this = this;
  91691. var result = new Array();
  91692. originalPoints.forEach(function (point) {
  91693. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  91694. var newPoint = new IndexedVector2(point, _this.elements.length);
  91695. result.push(newPoint);
  91696. _this.elements.push(newPoint);
  91697. }
  91698. });
  91699. return result;
  91700. };
  91701. PolygonPoints.prototype.computeBounds = function () {
  91702. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  91703. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  91704. this.elements.forEach(function (point) {
  91705. // x
  91706. if (point.x < lmin.x) {
  91707. lmin.x = point.x;
  91708. }
  91709. else if (point.x > lmax.x) {
  91710. lmax.x = point.x;
  91711. }
  91712. // y
  91713. if (point.y < lmin.y) {
  91714. lmin.y = point.y;
  91715. }
  91716. else if (point.y > lmax.y) {
  91717. lmax.y = point.y;
  91718. }
  91719. });
  91720. return {
  91721. min: lmin,
  91722. max: lmax,
  91723. width: lmax.x - lmin.x,
  91724. height: lmax.y - lmin.y
  91725. };
  91726. };
  91727. return PolygonPoints;
  91728. }());
  91729. var Polygon = /** @class */ (function () {
  91730. function Polygon() {
  91731. }
  91732. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  91733. return [
  91734. new BABYLON.Vector2(xmin, ymin),
  91735. new BABYLON.Vector2(xmax, ymin),
  91736. new BABYLON.Vector2(xmax, ymax),
  91737. new BABYLON.Vector2(xmin, ymax)
  91738. ];
  91739. };
  91740. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  91741. if (cx === void 0) { cx = 0; }
  91742. if (cy === void 0) { cy = 0; }
  91743. if (numberOfSides === void 0) { numberOfSides = 32; }
  91744. var result = new Array();
  91745. var angle = 0;
  91746. var increment = (Math.PI * 2) / numberOfSides;
  91747. for (var i = 0; i < numberOfSides; i++) {
  91748. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  91749. angle -= increment;
  91750. }
  91751. return result;
  91752. };
  91753. Polygon.Parse = function (input) {
  91754. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  91755. var i, result = [];
  91756. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  91757. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  91758. }
  91759. return result;
  91760. };
  91761. Polygon.StartingAt = function (x, y) {
  91762. return BABYLON.Path2.StartingAt(x, y);
  91763. };
  91764. return Polygon;
  91765. }());
  91766. BABYLON.Polygon = Polygon;
  91767. var PolygonMeshBuilder = /** @class */ (function () {
  91768. function PolygonMeshBuilder(name, contours, scene) {
  91769. this._points = new PolygonPoints();
  91770. this._outlinepoints = new PolygonPoints();
  91771. this._holes = new Array();
  91772. this._epoints = new Array();
  91773. this._eholes = new Array();
  91774. this._name = name;
  91775. this._scene = scene;
  91776. var points;
  91777. if (contours instanceof BABYLON.Path2) {
  91778. points = contours.getPoints();
  91779. }
  91780. else {
  91781. points = contours;
  91782. }
  91783. this._addToepoint(points);
  91784. this._points.add(points);
  91785. this._outlinepoints.add(points);
  91786. if (typeof earcut === 'undefined') {
  91787. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  91788. }
  91789. }
  91790. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  91791. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  91792. var p = points_1[_i];
  91793. this._epoints.push(p.x, p.y);
  91794. }
  91795. };
  91796. PolygonMeshBuilder.prototype.addHole = function (hole) {
  91797. this._points.add(hole);
  91798. var holepoints = new PolygonPoints();
  91799. holepoints.add(hole);
  91800. this._holes.push(holepoints);
  91801. this._eholes.push(this._epoints.length / 2);
  91802. this._addToepoint(hole);
  91803. return this;
  91804. };
  91805. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  91806. var _this = this;
  91807. if (updatable === void 0) { updatable = false; }
  91808. if (depth === void 0) { depth = 0; }
  91809. var result = new BABYLON.Mesh(this._name, this._scene);
  91810. var normals = new Array();
  91811. var positions = new Array();
  91812. var uvs = new Array();
  91813. var bounds = this._points.computeBounds();
  91814. this._points.elements.forEach(function (p) {
  91815. normals.push(0, 1.0, 0);
  91816. positions.push(p.x, 0, p.y);
  91817. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  91818. });
  91819. var indices = new Array();
  91820. var res = earcut(this._epoints, this._eholes, 2);
  91821. for (var i = 0; i < res.length; i++) {
  91822. indices.push(res[i]);
  91823. }
  91824. if (depth > 0) {
  91825. var positionscount = (positions.length / 3); //get the current pointcount
  91826. this._points.elements.forEach(function (p) {
  91827. normals.push(0, -1.0, 0);
  91828. positions.push(p.x, -depth, p.y);
  91829. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  91830. });
  91831. var totalCount = indices.length;
  91832. for (var i = 0; i < totalCount; i += 3) {
  91833. var i0 = indices[i + 0];
  91834. var i1 = indices[i + 1];
  91835. var i2 = indices[i + 2];
  91836. indices.push(i2 + positionscount);
  91837. indices.push(i1 + positionscount);
  91838. indices.push(i0 + positionscount);
  91839. }
  91840. //Add the sides
  91841. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  91842. this._holes.forEach(function (hole) {
  91843. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  91844. });
  91845. }
  91846. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  91847. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  91848. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  91849. result.setIndices(indices);
  91850. return result;
  91851. };
  91852. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  91853. var StartIndex = positions.length / 3;
  91854. var ulength = 0;
  91855. for (var i = 0; i < points.elements.length; i++) {
  91856. var p = points.elements[i];
  91857. var p1;
  91858. if ((i + 1) > points.elements.length - 1) {
  91859. p1 = points.elements[0];
  91860. }
  91861. else {
  91862. p1 = points.elements[i + 1];
  91863. }
  91864. positions.push(p.x, 0, p.y);
  91865. positions.push(p.x, -depth, p.y);
  91866. positions.push(p1.x, 0, p1.y);
  91867. positions.push(p1.x, -depth, p1.y);
  91868. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  91869. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  91870. var v3 = v2.subtract(v1);
  91871. var v4 = new BABYLON.Vector3(0, 1, 0);
  91872. var vn = BABYLON.Vector3.Cross(v3, v4);
  91873. vn = vn.normalize();
  91874. uvs.push(ulength / bounds.width, 0);
  91875. uvs.push(ulength / bounds.width, 1);
  91876. ulength += v3.length();
  91877. uvs.push((ulength / bounds.width), 0);
  91878. uvs.push((ulength / bounds.width), 1);
  91879. if (!flip) {
  91880. normals.push(-vn.x, -vn.y, -vn.z);
  91881. normals.push(-vn.x, -vn.y, -vn.z);
  91882. normals.push(-vn.x, -vn.y, -vn.z);
  91883. normals.push(-vn.x, -vn.y, -vn.z);
  91884. indices.push(StartIndex);
  91885. indices.push(StartIndex + 1);
  91886. indices.push(StartIndex + 2);
  91887. indices.push(StartIndex + 1);
  91888. indices.push(StartIndex + 3);
  91889. indices.push(StartIndex + 2);
  91890. }
  91891. else {
  91892. normals.push(vn.x, vn.y, vn.z);
  91893. normals.push(vn.x, vn.y, vn.z);
  91894. normals.push(vn.x, vn.y, vn.z);
  91895. normals.push(vn.x, vn.y, vn.z);
  91896. indices.push(StartIndex);
  91897. indices.push(StartIndex + 2);
  91898. indices.push(StartIndex + 1);
  91899. indices.push(StartIndex + 1);
  91900. indices.push(StartIndex + 2);
  91901. indices.push(StartIndex + 3);
  91902. }
  91903. StartIndex += 4;
  91904. }
  91905. ;
  91906. };
  91907. return PolygonMeshBuilder;
  91908. }());
  91909. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  91910. })(BABYLON || (BABYLON = {}));
  91911. //# sourceMappingURL=babylon.polygonMesh.js.map
  91912. var BABYLON;
  91913. (function (BABYLON) {
  91914. /**
  91915. * Unique ID when we import meshes from Babylon to CSG
  91916. */
  91917. var currentCSGMeshId = 0;
  91918. /**
  91919. * Represents a vertex of a polygon. Use your own vertex class instead of this
  91920. * one to provide additional features like texture coordinates and vertex
  91921. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  91922. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  91923. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  91924. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  91925. * is not used anywhere else.
  91926. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  91927. */
  91928. var Vertex = /** @class */ (function () {
  91929. /**
  91930. * Initializes the vertex
  91931. * @param pos The position of the vertex
  91932. * @param normal The normal of the vertex
  91933. * @param uv The texture coordinate of the vertex
  91934. */
  91935. function Vertex(
  91936. /**
  91937. * The position of the vertex
  91938. */
  91939. pos,
  91940. /**
  91941. * The normal of the vertex
  91942. */
  91943. normal,
  91944. /**
  91945. * The texture coordinate of the vertex
  91946. */
  91947. uv) {
  91948. this.pos = pos;
  91949. this.normal = normal;
  91950. this.uv = uv;
  91951. }
  91952. /**
  91953. * Make a clone, or deep copy, of the vertex
  91954. * @returns A new Vertex
  91955. */
  91956. Vertex.prototype.clone = function () {
  91957. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  91958. };
  91959. /**
  91960. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  91961. * orientation of a polygon is flipped.
  91962. */
  91963. Vertex.prototype.flip = function () {
  91964. this.normal = this.normal.scale(-1);
  91965. };
  91966. /**
  91967. * Create a new vertex between this vertex and `other` by linearly
  91968. * interpolating all properties using a parameter of `t`. Subclasses should
  91969. * override this to interpolate additional properties.
  91970. * @param other the vertex to interpolate against
  91971. * @param t The factor used to linearly interpolate between the vertices
  91972. */
  91973. Vertex.prototype.interpolate = function (other, t) {
  91974. 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));
  91975. };
  91976. return Vertex;
  91977. }());
  91978. /**
  91979. * Represents a plane in 3D space.
  91980. */
  91981. var Plane = /** @class */ (function () {
  91982. /**
  91983. * Initializes the plane
  91984. * @param normal The normal for the plane
  91985. * @param w
  91986. */
  91987. function Plane(normal, w) {
  91988. this.normal = normal;
  91989. this.w = w;
  91990. }
  91991. /**
  91992. * Construct a plane from three points
  91993. * @param a Point a
  91994. * @param b Point b
  91995. * @param c Point c
  91996. */
  91997. Plane.FromPoints = function (a, b, c) {
  91998. var v0 = c.subtract(a);
  91999. var v1 = b.subtract(a);
  92000. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  92001. return null;
  92002. }
  92003. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  92004. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  92005. };
  92006. /**
  92007. * Clone, or make a deep copy of the plane
  92008. * @returns a new Plane
  92009. */
  92010. Plane.prototype.clone = function () {
  92011. return new Plane(this.normal.clone(), this.w);
  92012. };
  92013. /**
  92014. * Flip the face of the plane
  92015. */
  92016. Plane.prototype.flip = function () {
  92017. this.normal.scaleInPlace(-1);
  92018. this.w = -this.w;
  92019. };
  92020. /**
  92021. * Split `polygon` by this plane if needed, then put the polygon or polygon
  92022. * fragments in the appropriate lists. Coplanar polygons go into either
  92023. `* coplanarFront` or `coplanarBack` depending on their orientation with
  92024. * respect to this plane. Polygons in front or in back of this plane go into
  92025. * either `front` or `back`
  92026. * @param polygon The polygon to be split
  92027. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  92028. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  92029. * @param front Will contain the polygons in front of the plane
  92030. * @param back Will contain the polygons begind the plane
  92031. */
  92032. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  92033. var COPLANAR = 0;
  92034. var FRONT = 1;
  92035. var BACK = 2;
  92036. var SPANNING = 3;
  92037. // Classify each point as well as the entire polygon into one of the above
  92038. // four classes.
  92039. var polygonType = 0;
  92040. var types = [];
  92041. var i;
  92042. var t;
  92043. for (i = 0; i < polygon.vertices.length; i++) {
  92044. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  92045. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  92046. polygonType |= type;
  92047. types.push(type);
  92048. }
  92049. // Put the polygon in the correct list, splitting it when necessary
  92050. switch (polygonType) {
  92051. case COPLANAR:
  92052. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  92053. break;
  92054. case FRONT:
  92055. front.push(polygon);
  92056. break;
  92057. case BACK:
  92058. back.push(polygon);
  92059. break;
  92060. case SPANNING:
  92061. var f = [], b = [];
  92062. for (i = 0; i < polygon.vertices.length; i++) {
  92063. var j = (i + 1) % polygon.vertices.length;
  92064. var ti = types[i], tj = types[j];
  92065. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  92066. if (ti !== BACK)
  92067. f.push(vi);
  92068. if (ti !== FRONT)
  92069. b.push(ti !== BACK ? vi.clone() : vi);
  92070. if ((ti | tj) === SPANNING) {
  92071. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  92072. var v = vi.interpolate(vj, t);
  92073. f.push(v);
  92074. b.push(v.clone());
  92075. }
  92076. }
  92077. var poly;
  92078. if (f.length >= 3) {
  92079. poly = new Polygon(f, polygon.shared);
  92080. if (poly.plane)
  92081. front.push(poly);
  92082. }
  92083. if (b.length >= 3) {
  92084. poly = new Polygon(b, polygon.shared);
  92085. if (poly.plane)
  92086. back.push(poly);
  92087. }
  92088. break;
  92089. }
  92090. };
  92091. /**
  92092. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  92093. * point is on the plane
  92094. */
  92095. Plane.EPSILON = 1e-5;
  92096. return Plane;
  92097. }());
  92098. /**
  92099. * Represents a convex polygon. The vertices used to initialize a polygon must
  92100. * be coplanar and form a convex loop.
  92101. *
  92102. * Each convex polygon has a `shared` property, which is shared between all
  92103. * polygons that are clones of each other or were split from the same polygon.
  92104. * This can be used to define per-polygon properties (such as surface color)
  92105. */
  92106. var Polygon = /** @class */ (function () {
  92107. /**
  92108. * Initializes the polygon
  92109. * @param vertices The vertices of the polygon
  92110. * @param shared The properties shared across all polygons
  92111. */
  92112. function Polygon(vertices, shared) {
  92113. this.vertices = vertices;
  92114. this.shared = shared;
  92115. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  92116. }
  92117. /**
  92118. * Clones, or makes a deep copy, or the polygon
  92119. */
  92120. Polygon.prototype.clone = function () {
  92121. var vertices = this.vertices.map(function (v) { return v.clone(); });
  92122. return new Polygon(vertices, this.shared);
  92123. };
  92124. /**
  92125. * Flips the faces of the polygon
  92126. */
  92127. Polygon.prototype.flip = function () {
  92128. this.vertices.reverse().map(function (v) { v.flip(); });
  92129. this.plane.flip();
  92130. };
  92131. return Polygon;
  92132. }());
  92133. /**
  92134. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  92135. * by picking a polygon to split along. That polygon (and all other coplanar
  92136. * polygons) are added directly to that node and the other polygons are added to
  92137. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  92138. * no distinction between internal and leaf nodes
  92139. */
  92140. var Node = /** @class */ (function () {
  92141. /**
  92142. * Initializes the node
  92143. * @param polygons A collection of polygons held in the node
  92144. */
  92145. function Node(polygons) {
  92146. this.plane = null;
  92147. this.front = null;
  92148. this.back = null;
  92149. this.polygons = new Array();
  92150. if (polygons) {
  92151. this.build(polygons);
  92152. }
  92153. }
  92154. /**
  92155. * Clones, or makes a deep copy, of the node
  92156. * @returns The cloned node
  92157. */
  92158. Node.prototype.clone = function () {
  92159. var node = new Node();
  92160. node.plane = this.plane && this.plane.clone();
  92161. node.front = this.front && this.front.clone();
  92162. node.back = this.back && this.back.clone();
  92163. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  92164. return node;
  92165. };
  92166. /**
  92167. * Convert solid space to empty space and empty space to solid space
  92168. */
  92169. Node.prototype.invert = function () {
  92170. for (var i = 0; i < this.polygons.length; i++) {
  92171. this.polygons[i].flip();
  92172. }
  92173. if (this.plane) {
  92174. this.plane.flip();
  92175. }
  92176. if (this.front) {
  92177. this.front.invert();
  92178. }
  92179. if (this.back) {
  92180. this.back.invert();
  92181. }
  92182. var temp = this.front;
  92183. this.front = this.back;
  92184. this.back = temp;
  92185. };
  92186. /**
  92187. * Recursively remove all polygons in `polygons` that are inside this BSP
  92188. * tree.
  92189. * @param polygons Polygons to remove from the BSP
  92190. * @returns Polygons clipped from the BSP
  92191. */
  92192. Node.prototype.clipPolygons = function (polygons) {
  92193. if (!this.plane)
  92194. return polygons.slice();
  92195. var front = new Array(), back = new Array();
  92196. for (var i = 0; i < polygons.length; i++) {
  92197. this.plane.splitPolygon(polygons[i], front, back, front, back);
  92198. }
  92199. if (this.front) {
  92200. front = this.front.clipPolygons(front);
  92201. }
  92202. if (this.back) {
  92203. back = this.back.clipPolygons(back);
  92204. }
  92205. else {
  92206. back = [];
  92207. }
  92208. return front.concat(back);
  92209. };
  92210. /**
  92211. * Remove all polygons in this BSP tree that are inside the other BSP tree
  92212. * `bsp`.
  92213. * @param bsp BSP containing polygons to remove from this BSP
  92214. */
  92215. Node.prototype.clipTo = function (bsp) {
  92216. this.polygons = bsp.clipPolygons(this.polygons);
  92217. if (this.front)
  92218. this.front.clipTo(bsp);
  92219. if (this.back)
  92220. this.back.clipTo(bsp);
  92221. };
  92222. /**
  92223. * Return a list of all polygons in this BSP tree
  92224. * @returns List of all polygons in this BSP tree
  92225. */
  92226. Node.prototype.allPolygons = function () {
  92227. var polygons = this.polygons.slice();
  92228. if (this.front)
  92229. polygons = polygons.concat(this.front.allPolygons());
  92230. if (this.back)
  92231. polygons = polygons.concat(this.back.allPolygons());
  92232. return polygons;
  92233. };
  92234. /**
  92235. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  92236. * new polygons are filtered down to the bottom of the tree and become new
  92237. * nodes there. Each set of polygons is partitioned using the first polygon
  92238. * (no heuristic is used to pick a good split)
  92239. * @param polygons Polygons used to construct the BSP tree
  92240. */
  92241. Node.prototype.build = function (polygons) {
  92242. if (!polygons.length)
  92243. return;
  92244. if (!this.plane)
  92245. this.plane = polygons[0].plane.clone();
  92246. var front = new Array(), back = new Array();
  92247. for (var i = 0; i < polygons.length; i++) {
  92248. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  92249. }
  92250. if (front.length) {
  92251. if (!this.front)
  92252. this.front = new Node();
  92253. this.front.build(front);
  92254. }
  92255. if (back.length) {
  92256. if (!this.back)
  92257. this.back = new Node();
  92258. this.back.build(back);
  92259. }
  92260. };
  92261. return Node;
  92262. }());
  92263. /**
  92264. * Class for building Constructive Solid Geometry
  92265. */
  92266. var CSG = /** @class */ (function () {
  92267. function CSG() {
  92268. this.polygons = new Array();
  92269. }
  92270. /**
  92271. * Convert the BABYLON.Mesh to BABYLON.CSG
  92272. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  92273. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  92274. */
  92275. CSG.FromMesh = function (mesh) {
  92276. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  92277. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  92278. if (mesh instanceof BABYLON.Mesh) {
  92279. mesh.computeWorldMatrix(true);
  92280. matrix = mesh.getWorldMatrix();
  92281. meshPosition = mesh.position.clone();
  92282. meshRotation = mesh.rotation.clone();
  92283. if (mesh.rotationQuaternion) {
  92284. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  92285. }
  92286. meshScaling = mesh.scaling.clone();
  92287. }
  92288. else {
  92289. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  92290. }
  92291. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  92292. var subMeshes = mesh.subMeshes;
  92293. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  92294. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  92295. vertices = [];
  92296. for (var j = 0; j < 3; j++) {
  92297. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  92298. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  92299. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  92300. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  92301. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  92302. vertex = new Vertex(position, normal, uv);
  92303. vertices.push(vertex);
  92304. }
  92305. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  92306. // To handle the case of degenerated triangle
  92307. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  92308. if (polygon.plane)
  92309. polygons.push(polygon);
  92310. }
  92311. }
  92312. var csg = CSG.FromPolygons(polygons);
  92313. csg.matrix = matrix;
  92314. csg.position = meshPosition;
  92315. csg.rotation = meshRotation;
  92316. csg.scaling = meshScaling;
  92317. csg.rotationQuaternion = meshRotationQuaternion;
  92318. currentCSGMeshId++;
  92319. return csg;
  92320. };
  92321. /**
  92322. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  92323. * @param polygons Polygons used to construct a BABYLON.CSG solid
  92324. */
  92325. CSG.FromPolygons = function (polygons) {
  92326. var csg = new CSG();
  92327. csg.polygons = polygons;
  92328. return csg;
  92329. };
  92330. /**
  92331. * Clones, or makes a deep copy, of the BABYLON.CSG
  92332. * @returns A new BABYLON.CSG
  92333. */
  92334. CSG.prototype.clone = function () {
  92335. var csg = new CSG();
  92336. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  92337. csg.copyTransformAttributes(this);
  92338. return csg;
  92339. };
  92340. /**
  92341. * Unions this CSG with another CSG
  92342. * @param csg The CSG to union against this CSG
  92343. * @returns The unioned CSG
  92344. */
  92345. CSG.prototype.union = function (csg) {
  92346. var a = new Node(this.clone().polygons);
  92347. var b = new Node(csg.clone().polygons);
  92348. a.clipTo(b);
  92349. b.clipTo(a);
  92350. b.invert();
  92351. b.clipTo(a);
  92352. b.invert();
  92353. a.build(b.allPolygons());
  92354. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  92355. };
  92356. /**
  92357. * Unions this CSG with another CSG in place
  92358. * @param csg The CSG to union against this CSG
  92359. */
  92360. CSG.prototype.unionInPlace = function (csg) {
  92361. var a = new Node(this.polygons);
  92362. var b = new Node(csg.polygons);
  92363. a.clipTo(b);
  92364. b.clipTo(a);
  92365. b.invert();
  92366. b.clipTo(a);
  92367. b.invert();
  92368. a.build(b.allPolygons());
  92369. this.polygons = a.allPolygons();
  92370. };
  92371. /**
  92372. * Subtracts this CSG with another CSG
  92373. * @param csg The CSG to subtract against this CSG
  92374. * @returns A new BABYLON.CSG
  92375. */
  92376. CSG.prototype.subtract = function (csg) {
  92377. var a = new Node(this.clone().polygons);
  92378. var b = new Node(csg.clone().polygons);
  92379. a.invert();
  92380. a.clipTo(b);
  92381. b.clipTo(a);
  92382. b.invert();
  92383. b.clipTo(a);
  92384. b.invert();
  92385. a.build(b.allPolygons());
  92386. a.invert();
  92387. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  92388. };
  92389. /**
  92390. * Subtracts this CSG with another CSG in place
  92391. * @param csg The CSG to subtact against this CSG
  92392. */
  92393. CSG.prototype.subtractInPlace = function (csg) {
  92394. var a = new Node(this.polygons);
  92395. var b = new Node(csg.polygons);
  92396. a.invert();
  92397. a.clipTo(b);
  92398. b.clipTo(a);
  92399. b.invert();
  92400. b.clipTo(a);
  92401. b.invert();
  92402. a.build(b.allPolygons());
  92403. a.invert();
  92404. this.polygons = a.allPolygons();
  92405. };
  92406. /**
  92407. * Intersect this CSG with another CSG
  92408. * @param csg The CSG to intersect against this CSG
  92409. * @returns A new BABYLON.CSG
  92410. */
  92411. CSG.prototype.intersect = function (csg) {
  92412. var a = new Node(this.clone().polygons);
  92413. var b = new Node(csg.clone().polygons);
  92414. a.invert();
  92415. b.clipTo(a);
  92416. b.invert();
  92417. a.clipTo(b);
  92418. b.clipTo(a);
  92419. a.build(b.allPolygons());
  92420. a.invert();
  92421. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  92422. };
  92423. /**
  92424. * Intersects this CSG with another CSG in place
  92425. * @param csg The CSG to intersect against this CSG
  92426. */
  92427. CSG.prototype.intersectInPlace = function (csg) {
  92428. var a = new Node(this.polygons);
  92429. var b = new Node(csg.polygons);
  92430. a.invert();
  92431. b.clipTo(a);
  92432. b.invert();
  92433. a.clipTo(b);
  92434. b.clipTo(a);
  92435. a.build(b.allPolygons());
  92436. a.invert();
  92437. this.polygons = a.allPolygons();
  92438. };
  92439. /**
  92440. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  92441. * not modified.
  92442. * @returns A new BABYLON.CSG solid with solid and empty space switched
  92443. */
  92444. CSG.prototype.inverse = function () {
  92445. var csg = this.clone();
  92446. csg.inverseInPlace();
  92447. return csg;
  92448. };
  92449. /**
  92450. * Inverses the BABYLON.CSG in place
  92451. */
  92452. CSG.prototype.inverseInPlace = function () {
  92453. this.polygons.map(function (p) { p.flip(); });
  92454. };
  92455. /**
  92456. * This is used to keep meshes transformations so they can be restored
  92457. * when we build back a Babylon Mesh
  92458. * NB : All CSG operations are performed in world coordinates
  92459. * @param csg The BABYLON.CSG to copy the transform attributes from
  92460. * @returns This BABYLON.CSG
  92461. */
  92462. CSG.prototype.copyTransformAttributes = function (csg) {
  92463. this.matrix = csg.matrix;
  92464. this.position = csg.position;
  92465. this.rotation = csg.rotation;
  92466. this.scaling = csg.scaling;
  92467. this.rotationQuaternion = csg.rotationQuaternion;
  92468. return this;
  92469. };
  92470. /**
  92471. * Build Raw mesh from CSG
  92472. * Coordinates here are in world space
  92473. * @param name The name of the mesh geometry
  92474. * @param scene The BABYLON.Scene
  92475. * @param keepSubMeshes Specifies if the submeshes should be kept
  92476. * @returns A new BABYLON.Mesh
  92477. */
  92478. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  92479. var matrix = this.matrix.clone();
  92480. matrix.invert();
  92481. 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;
  92482. if (keepSubMeshes) {
  92483. // Sort Polygons, since subMeshes are indices range
  92484. polygons.sort(function (a, b) {
  92485. if (a.shared.meshId === b.shared.meshId) {
  92486. return a.shared.subMeshId - b.shared.subMeshId;
  92487. }
  92488. else {
  92489. return a.shared.meshId - b.shared.meshId;
  92490. }
  92491. });
  92492. }
  92493. for (var i = 0, il = polygons.length; i < il; i++) {
  92494. polygon = polygons[i];
  92495. // Building SubMeshes
  92496. if (!subMesh_dict[polygon.shared.meshId]) {
  92497. subMesh_dict[polygon.shared.meshId] = {};
  92498. }
  92499. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  92500. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  92501. indexStart: +Infinity,
  92502. indexEnd: -Infinity,
  92503. materialIndex: polygon.shared.materialIndex
  92504. };
  92505. }
  92506. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  92507. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  92508. polygonIndices[0] = 0;
  92509. polygonIndices[1] = j - 1;
  92510. polygonIndices[2] = j;
  92511. for (var k = 0; k < 3; k++) {
  92512. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  92513. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  92514. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  92515. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  92516. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  92517. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  92518. // Check if 2 points can be merged
  92519. if (!(typeof vertex_idx !== 'undefined' &&
  92520. normals[vertex_idx * 3] === localNormal.x &&
  92521. normals[vertex_idx * 3 + 1] === localNormal.y &&
  92522. normals[vertex_idx * 3 + 2] === localNormal.z &&
  92523. uvs[vertex_idx * 2] === uv.x &&
  92524. uvs[vertex_idx * 2 + 1] === uv.y)) {
  92525. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  92526. uvs.push(uv.x, uv.y);
  92527. normals.push(normal.x, normal.y, normal.z);
  92528. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  92529. }
  92530. indices.push(vertex_idx);
  92531. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  92532. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  92533. currentIndex++;
  92534. }
  92535. }
  92536. }
  92537. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  92538. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  92539. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  92540. mesh.setIndices(indices, null);
  92541. if (keepSubMeshes) {
  92542. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  92543. var materialIndexOffset = 0, materialMaxIndex;
  92544. mesh.subMeshes = new Array();
  92545. for (var m in subMesh_dict) {
  92546. materialMaxIndex = -1;
  92547. for (var sm in subMesh_dict[m]) {
  92548. subMesh_obj = subMesh_dict[m][sm];
  92549. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  92550. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  92551. }
  92552. materialIndexOffset += ++materialMaxIndex;
  92553. }
  92554. }
  92555. return mesh;
  92556. };
  92557. /**
  92558. * Build Mesh from CSG taking material and transforms into account
  92559. * @param name The name of the BABYLON.Mesh
  92560. * @param material The material of the BABYLON.Mesh
  92561. * @param scene The BABYLON.Scene
  92562. * @param keepSubMeshes Specifies if submeshes should be kept
  92563. * @returns The new BABYLON.Mesh
  92564. */
  92565. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  92566. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  92567. mesh.material = material;
  92568. mesh.position.copyFrom(this.position);
  92569. mesh.rotation.copyFrom(this.rotation);
  92570. if (this.rotationQuaternion) {
  92571. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  92572. }
  92573. mesh.scaling.copyFrom(this.scaling);
  92574. mesh.computeWorldMatrix(true);
  92575. return mesh;
  92576. };
  92577. return CSG;
  92578. }());
  92579. BABYLON.CSG = CSG;
  92580. })(BABYLON || (BABYLON = {}));
  92581. //# sourceMappingURL=babylon.csg.js.map
  92582. var BABYLON;
  92583. (function (BABYLON) {
  92584. /**
  92585. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  92586. * It controls one of the indiviual texture used in the effect.
  92587. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  92588. */
  92589. var LensFlare = /** @class */ (function () {
  92590. /**
  92591. * Instantiates a new Lens Flare.
  92592. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  92593. * It controls one of the indiviual texture used in the effect.
  92594. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  92595. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  92596. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  92597. * @param color Define the lens color
  92598. * @param imgUrl Define the lens texture url
  92599. * @param system Define the `lensFlareSystem` this flare is part of
  92600. */
  92601. function LensFlare(
  92602. /**
  92603. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  92604. */
  92605. size,
  92606. /**
  92607. * Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  92608. */
  92609. position, color, imgUrl, system) {
  92610. this.size = size;
  92611. this.position = position;
  92612. /**
  92613. * Define the alpha mode to render this particular lens.
  92614. */
  92615. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  92616. this.color = color || new BABYLON.Color3(1, 1, 1);
  92617. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  92618. this._system = system;
  92619. system.lensFlares.push(this);
  92620. }
  92621. /**
  92622. * Creates a new Lens Flare.
  92623. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  92624. * It controls one of the indiviual texture used in the effect.
  92625. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  92626. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  92627. * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
  92628. * @param color Define the lens color
  92629. * @param imgUrl Define the lens texture url
  92630. * @param system Define the `lensFlareSystem` this flare is part of
  92631. * @returns The newly created Lens Flare
  92632. */
  92633. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  92634. return new LensFlare(size, position, color, imgUrl, system);
  92635. };
  92636. /**
  92637. * Dispose and release the lens flare with its associated resources.
  92638. */
  92639. LensFlare.prototype.dispose = function () {
  92640. if (this.texture) {
  92641. this.texture.dispose();
  92642. }
  92643. // Remove from scene
  92644. var index = this._system.lensFlares.indexOf(this);
  92645. this._system.lensFlares.splice(index, 1);
  92646. };
  92647. ;
  92648. return LensFlare;
  92649. }());
  92650. BABYLON.LensFlare = LensFlare;
  92651. })(BABYLON || (BABYLON = {}));
  92652. //# sourceMappingURL=babylon.lensFlare.js.map
  92653. var BABYLON;
  92654. (function (BABYLON) {
  92655. // Adds the parser to the scene parsers.
  92656. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  92657. // Lens flares
  92658. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  92659. if (!container.lensFlareSystems) {
  92660. container.lensFlareSystems = new Array();
  92661. }
  92662. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  92663. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  92664. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  92665. container.lensFlareSystems.push(lf);
  92666. }
  92667. }
  92668. });
  92669. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  92670. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  92671. if (this.lensFlareSystems[index].name === name) {
  92672. return this.lensFlareSystems[index];
  92673. }
  92674. }
  92675. return null;
  92676. };
  92677. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  92678. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  92679. if (this.lensFlareSystems[index].id === id) {
  92680. return this.lensFlareSystems[index];
  92681. }
  92682. }
  92683. return null;
  92684. };
  92685. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  92686. var index = this.lensFlareSystems.indexOf(toRemove);
  92687. if (index !== -1) {
  92688. this.lensFlareSystems.splice(index, 1);
  92689. }
  92690. return index;
  92691. };
  92692. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  92693. this.lensFlareSystems.push(newLensFlareSystem);
  92694. };
  92695. /**
  92696. * Defines the lens flare scene component responsible to manage any lens flares
  92697. * in a given scene.
  92698. */
  92699. var LensFlareSystemSceneComponent = /** @class */ (function () {
  92700. /**
  92701. * Creates a new instance of the component for the given scene
  92702. * @param scene Defines the scene to register the component in
  92703. */
  92704. function LensFlareSystemSceneComponent(scene) {
  92705. /**
  92706. * The component name helpfull to identify the component in the list of scene components.
  92707. */
  92708. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  92709. this.scene = scene;
  92710. scene.lensFlareSystems = new Array();
  92711. }
  92712. /**
  92713. * Registers the component in a given scene
  92714. */
  92715. LensFlareSystemSceneComponent.prototype.register = function () {
  92716. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  92717. };
  92718. /**
  92719. * Rebuilds the elements related to this component in case of
  92720. * context lost for instance.
  92721. */
  92722. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  92723. // Nothing to do for lens flare
  92724. };
  92725. /**
  92726. * Adds all the element from the container to the scene
  92727. * @param container the container holding the elements
  92728. */
  92729. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  92730. var _this = this;
  92731. if (!container.lensFlareSystems) {
  92732. return;
  92733. }
  92734. container.lensFlareSystems.forEach(function (o) {
  92735. _this.scene.addLensFlareSystem(o);
  92736. });
  92737. };
  92738. /**
  92739. * Removes all the elements in the container from the scene
  92740. * @param container contains the elements to remove
  92741. */
  92742. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  92743. var _this = this;
  92744. if (!container.lensFlareSystems) {
  92745. return;
  92746. }
  92747. container.lensFlareSystems.forEach(function (o) {
  92748. _this.scene.removeLensFlareSystem(o);
  92749. });
  92750. };
  92751. /**
  92752. * Serializes the component data to the specified json object
  92753. * @param serializationObject The object to serialize to
  92754. */
  92755. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  92756. // Lens flares
  92757. serializationObject.lensFlareSystems = [];
  92758. var lensFlareSystems = this.scene.lensFlareSystems;
  92759. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  92760. var lensFlareSystem = lensFlareSystems_1[_i];
  92761. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  92762. }
  92763. };
  92764. /**
  92765. * Disposes the component and the associated ressources.
  92766. */
  92767. LensFlareSystemSceneComponent.prototype.dispose = function () {
  92768. var lensFlareSystems = this.scene.lensFlareSystems;
  92769. while (lensFlareSystems.length) {
  92770. lensFlareSystems[0].dispose();
  92771. }
  92772. };
  92773. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  92774. // Lens flares
  92775. if (this.scene.lensFlaresEnabled) {
  92776. var lensFlareSystems = this.scene.lensFlareSystems;
  92777. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  92778. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  92779. var lensFlareSystem = lensFlareSystems_2[_i];
  92780. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  92781. lensFlareSystem.render();
  92782. }
  92783. }
  92784. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  92785. }
  92786. };
  92787. return LensFlareSystemSceneComponent;
  92788. }());
  92789. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  92790. })(BABYLON || (BABYLON = {}));
  92791. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  92792. var BABYLON;
  92793. (function (BABYLON) {
  92794. /**
  92795. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  92796. * It is usually composed of several `BABYLON.lensFlare`.
  92797. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  92798. */
  92799. var LensFlareSystem = /** @class */ (function () {
  92800. /**
  92801. * Instantiates a lens flare system.
  92802. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  92803. * It is usually composed of several `BABYLON.lensFlare`.
  92804. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  92805. * @param name Define the name of the lens flare system in the scene
  92806. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  92807. * @param scene Define the scene the lens flare system belongs to
  92808. */
  92809. function LensFlareSystem(
  92810. /**
  92811. * Define the name of the lens flare system
  92812. */
  92813. name, emitter, scene) {
  92814. this.name = name;
  92815. /**
  92816. * List of lens flares used in this system.
  92817. */
  92818. this.lensFlares = new Array();
  92819. /**
  92820. * Define a limit from the border the lens flare can be visible.
  92821. */
  92822. this.borderLimit = 300;
  92823. /**
  92824. * Define a viewport border we do not want to see the lens flare in.
  92825. */
  92826. this.viewportBorder = 0;
  92827. /**
  92828. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  92829. */
  92830. this.layerMask = 0x0FFFFFFF;
  92831. this._vertexBuffers = {};
  92832. this._isEnabled = true;
  92833. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  92834. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  92835. if (!component) {
  92836. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  92837. scene._addComponent(component);
  92838. }
  92839. this._emitter = emitter;
  92840. this.id = name;
  92841. scene.lensFlareSystems.push(this);
  92842. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  92843. var engine = scene.getEngine();
  92844. // VBO
  92845. var vertices = [];
  92846. vertices.push(1, 1);
  92847. vertices.push(-1, 1);
  92848. vertices.push(-1, -1);
  92849. vertices.push(1, -1);
  92850. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  92851. // Indices
  92852. var indices = [];
  92853. indices.push(0);
  92854. indices.push(1);
  92855. indices.push(2);
  92856. indices.push(0);
  92857. indices.push(2);
  92858. indices.push(3);
  92859. this._indexBuffer = engine.createIndexBuffer(indices);
  92860. // Effects
  92861. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  92862. }
  92863. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  92864. /**
  92865. * Define if the lens flare system is enabled.
  92866. */
  92867. get: function () {
  92868. return this._isEnabled;
  92869. },
  92870. set: function (value) {
  92871. this._isEnabled = value;
  92872. },
  92873. enumerable: true,
  92874. configurable: true
  92875. });
  92876. /**
  92877. * Get the scene the effects belongs to.
  92878. * @returns the scene holding the lens flare system
  92879. */
  92880. LensFlareSystem.prototype.getScene = function () {
  92881. return this._scene;
  92882. };
  92883. /**
  92884. * Get the emitter of the lens flare system.
  92885. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  92886. * @returns the emitter of the lens flare system
  92887. */
  92888. LensFlareSystem.prototype.getEmitter = function () {
  92889. return this._emitter;
  92890. };
  92891. /**
  92892. * Set the emitter of the lens flare system.
  92893. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  92894. * @param newEmitter Define the new emitter of the system
  92895. */
  92896. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  92897. this._emitter = newEmitter;
  92898. };
  92899. /**
  92900. * Get the lens flare system emitter position.
  92901. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  92902. * @returns the position
  92903. */
  92904. LensFlareSystem.prototype.getEmitterPosition = function () {
  92905. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  92906. };
  92907. /**
  92908. * @hidden
  92909. */
  92910. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  92911. var position = this.getEmitterPosition();
  92912. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  92913. this._positionX = position.x;
  92914. this._positionY = position.y;
  92915. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  92916. if (this.viewportBorder > 0) {
  92917. globalViewport.x -= this.viewportBorder;
  92918. globalViewport.y -= this.viewportBorder;
  92919. globalViewport.width += this.viewportBorder * 2;
  92920. globalViewport.height += this.viewportBorder * 2;
  92921. position.x += this.viewportBorder;
  92922. position.y += this.viewportBorder;
  92923. this._positionX += this.viewportBorder;
  92924. this._positionY += this.viewportBorder;
  92925. }
  92926. if (position.z > 0) {
  92927. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  92928. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  92929. return true;
  92930. }
  92931. return true;
  92932. }
  92933. return false;
  92934. };
  92935. /** @hidden */
  92936. LensFlareSystem.prototype._isVisible = function () {
  92937. if (!this._isEnabled || !this._scene.activeCamera) {
  92938. return false;
  92939. }
  92940. var emitterPosition = this.getEmitterPosition();
  92941. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  92942. var distance = direction.length();
  92943. direction.normalize();
  92944. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  92945. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  92946. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  92947. };
  92948. /**
  92949. * @hidden
  92950. */
  92951. LensFlareSystem.prototype.render = function () {
  92952. if (!this._effect.isReady() || !this._scene.activeCamera)
  92953. return false;
  92954. var engine = this._scene.getEngine();
  92955. var viewport = this._scene.activeCamera.viewport;
  92956. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  92957. // Position
  92958. if (!this.computeEffectivePosition(globalViewport)) {
  92959. return false;
  92960. }
  92961. // Visibility
  92962. if (!this._isVisible()) {
  92963. return false;
  92964. }
  92965. // Intensity
  92966. var awayX;
  92967. var awayY;
  92968. if (this._positionX < this.borderLimit + globalViewport.x) {
  92969. awayX = this.borderLimit + globalViewport.x - this._positionX;
  92970. }
  92971. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  92972. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  92973. }
  92974. else {
  92975. awayX = 0;
  92976. }
  92977. if (this._positionY < this.borderLimit + globalViewport.y) {
  92978. awayY = this.borderLimit + globalViewport.y - this._positionY;
  92979. }
  92980. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  92981. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  92982. }
  92983. else {
  92984. awayY = 0;
  92985. }
  92986. var away = (awayX > awayY) ? awayX : awayY;
  92987. away -= this.viewportBorder;
  92988. if (away > this.borderLimit) {
  92989. away = this.borderLimit;
  92990. }
  92991. var intensity = 1.0 - (away / this.borderLimit);
  92992. if (intensity < 0) {
  92993. return false;
  92994. }
  92995. if (intensity > 1.0) {
  92996. intensity = 1.0;
  92997. }
  92998. if (this.viewportBorder > 0) {
  92999. globalViewport.x += this.viewportBorder;
  93000. globalViewport.y += this.viewportBorder;
  93001. globalViewport.width -= this.viewportBorder * 2;
  93002. globalViewport.height -= this.viewportBorder * 2;
  93003. this._positionX -= this.viewportBorder;
  93004. this._positionY -= this.viewportBorder;
  93005. }
  93006. // Position
  93007. var centerX = globalViewport.x + globalViewport.width / 2;
  93008. var centerY = globalViewport.y + globalViewport.height / 2;
  93009. var distX = centerX - this._positionX;
  93010. var distY = centerY - this._positionY;
  93011. // Effects
  93012. engine.enableEffect(this._effect);
  93013. engine.setState(false);
  93014. engine.setDepthBuffer(false);
  93015. // VBOs
  93016. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  93017. // Flares
  93018. for (var index = 0; index < this.lensFlares.length; index++) {
  93019. var flare = this.lensFlares[index];
  93020. engine.setAlphaMode(flare.alphaMode);
  93021. var x = centerX - (distX * flare.position);
  93022. var y = centerY - (distY * flare.position);
  93023. var cw = flare.size;
  93024. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  93025. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  93026. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  93027. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  93028. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  93029. // Texture
  93030. this._effect.setTexture("textureSampler", flare.texture);
  93031. // Color
  93032. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  93033. // Draw order
  93034. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93035. }
  93036. engine.setDepthBuffer(true);
  93037. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  93038. return true;
  93039. };
  93040. /**
  93041. * Dispose and release the lens flare with its associated resources.
  93042. */
  93043. LensFlareSystem.prototype.dispose = function () {
  93044. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93045. if (vertexBuffer) {
  93046. vertexBuffer.dispose();
  93047. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93048. }
  93049. if (this._indexBuffer) {
  93050. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93051. this._indexBuffer = null;
  93052. }
  93053. while (this.lensFlares.length) {
  93054. this.lensFlares[0].dispose();
  93055. }
  93056. // Remove from scene
  93057. var index = this._scene.lensFlareSystems.indexOf(this);
  93058. this._scene.lensFlareSystems.splice(index, 1);
  93059. };
  93060. /**
  93061. * Parse a lens flare system from a JSON repressentation
  93062. * @param parsedLensFlareSystem Define the JSON to parse
  93063. * @param scene Define the scene the parsed system should be instantiated in
  93064. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  93065. * @returns the parsed system
  93066. */
  93067. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  93068. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  93069. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  93070. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  93071. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  93072. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  93073. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  93074. var parsedFlare = parsedLensFlareSystem.flares[index];
  93075. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  93076. }
  93077. return lensFlareSystem;
  93078. };
  93079. /**
  93080. * Serialize the current Lens Flare System into a JSON representation.
  93081. * @returns the serialized JSON
  93082. */
  93083. LensFlareSystem.prototype.serialize = function () {
  93084. var serializationObject = {};
  93085. serializationObject.id = this.id;
  93086. serializationObject.name = this.name;
  93087. serializationObject.emitterId = this.getEmitter().id;
  93088. serializationObject.borderLimit = this.borderLimit;
  93089. serializationObject.flares = [];
  93090. for (var index = 0; index < this.lensFlares.length; index++) {
  93091. var flare = this.lensFlares[index];
  93092. serializationObject.flares.push({
  93093. size: flare.size,
  93094. position: flare.position,
  93095. color: flare.color.asArray(),
  93096. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  93097. });
  93098. }
  93099. return serializationObject;
  93100. };
  93101. return LensFlareSystem;
  93102. }());
  93103. BABYLON.LensFlareSystem = LensFlareSystem;
  93104. })(BABYLON || (BABYLON = {}));
  93105. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  93106. var BABYLON;
  93107. (function (BABYLON) {
  93108. /**
  93109. * This is a holder class for the physics joint created by the physics plugin.
  93110. * It holds a set of functions to control the underlying joint.
  93111. */
  93112. var PhysicsJoint = /** @class */ (function () {
  93113. function PhysicsJoint(type, jointData) {
  93114. this.type = type;
  93115. this.jointData = jointData;
  93116. jointData.nativeParams = jointData.nativeParams || {};
  93117. }
  93118. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  93119. get: function () {
  93120. return this._physicsJoint;
  93121. },
  93122. set: function (newJoint) {
  93123. if (this._physicsJoint) {
  93124. //remove from the wolrd
  93125. }
  93126. this._physicsJoint = newJoint;
  93127. },
  93128. enumerable: true,
  93129. configurable: true
  93130. });
  93131. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  93132. set: function (physicsPlugin) {
  93133. this._physicsPlugin = physicsPlugin;
  93134. },
  93135. enumerable: true,
  93136. configurable: true
  93137. });
  93138. /**
  93139. * Execute a function that is physics-plugin specific.
  93140. * @param {Function} func the function that will be executed.
  93141. * It accepts two parameters: the physics world and the physics joint.
  93142. */
  93143. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  93144. func(this._physicsPlugin.world, this._physicsJoint);
  93145. };
  93146. //TODO check if the native joints are the same
  93147. //Joint Types
  93148. PhysicsJoint.DistanceJoint = 0;
  93149. PhysicsJoint.HingeJoint = 1;
  93150. PhysicsJoint.BallAndSocketJoint = 2;
  93151. PhysicsJoint.WheelJoint = 3;
  93152. PhysicsJoint.SliderJoint = 4;
  93153. //OIMO
  93154. PhysicsJoint.PrismaticJoint = 5;
  93155. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  93156. PhysicsJoint.UniversalJoint = 6;
  93157. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  93158. //Cannon
  93159. //Similar to a Ball-Joint. Different in params
  93160. PhysicsJoint.PointToPointJoint = 8;
  93161. //Cannon only at the moment
  93162. PhysicsJoint.SpringJoint = 9;
  93163. PhysicsJoint.LockJoint = 10;
  93164. return PhysicsJoint;
  93165. }());
  93166. BABYLON.PhysicsJoint = PhysicsJoint;
  93167. /**
  93168. * A class representing a physics distance joint.
  93169. */
  93170. var DistanceJoint = /** @class */ (function (_super) {
  93171. __extends(DistanceJoint, _super);
  93172. function DistanceJoint(jointData) {
  93173. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  93174. }
  93175. /**
  93176. * Update the predefined distance.
  93177. */
  93178. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  93179. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  93180. };
  93181. return DistanceJoint;
  93182. }(PhysicsJoint));
  93183. BABYLON.DistanceJoint = DistanceJoint;
  93184. var MotorEnabledJoint = /** @class */ (function (_super) {
  93185. __extends(MotorEnabledJoint, _super);
  93186. function MotorEnabledJoint(type, jointData) {
  93187. return _super.call(this, type, jointData) || this;
  93188. }
  93189. /**
  93190. * Set the motor values.
  93191. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93192. * @param {number} force the force to apply
  93193. * @param {number} maxForce max force for this motor.
  93194. */
  93195. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  93196. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  93197. };
  93198. /**
  93199. * Set the motor's limits.
  93200. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93201. */
  93202. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  93203. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  93204. };
  93205. return MotorEnabledJoint;
  93206. }(PhysicsJoint));
  93207. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  93208. /**
  93209. * This class represents a single hinge physics joint
  93210. */
  93211. var HingeJoint = /** @class */ (function (_super) {
  93212. __extends(HingeJoint, _super);
  93213. function HingeJoint(jointData) {
  93214. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  93215. }
  93216. /**
  93217. * Set the motor values.
  93218. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93219. * @param {number} force the force to apply
  93220. * @param {number} maxForce max force for this motor.
  93221. */
  93222. HingeJoint.prototype.setMotor = function (force, maxForce) {
  93223. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  93224. };
  93225. /**
  93226. * Set the motor's limits.
  93227. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93228. */
  93229. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  93230. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  93231. };
  93232. return HingeJoint;
  93233. }(MotorEnabledJoint));
  93234. BABYLON.HingeJoint = HingeJoint;
  93235. /**
  93236. * This class represents a dual hinge physics joint (same as wheel joint)
  93237. */
  93238. var Hinge2Joint = /** @class */ (function (_super) {
  93239. __extends(Hinge2Joint, _super);
  93240. function Hinge2Joint(jointData) {
  93241. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  93242. }
  93243. /**
  93244. * Set the motor values.
  93245. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93246. * @param {number} force the force to apply
  93247. * @param {number} maxForce max force for this motor.
  93248. * @param {motorIndex} the motor's index, 0 or 1.
  93249. */
  93250. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  93251. if (motorIndex === void 0) { motorIndex = 0; }
  93252. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  93253. };
  93254. /**
  93255. * Set the motor limits.
  93256. * Attention, this function is plugin specific. Engines won't react 100% the same.
  93257. * @param {number} upperLimit the upper limit
  93258. * @param {number} lowerLimit lower limit
  93259. * @param {motorIndex} the motor's index, 0 or 1.
  93260. */
  93261. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  93262. if (motorIndex === void 0) { motorIndex = 0; }
  93263. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  93264. };
  93265. return Hinge2Joint;
  93266. }(MotorEnabledJoint));
  93267. BABYLON.Hinge2Joint = Hinge2Joint;
  93268. })(BABYLON || (BABYLON = {}));
  93269. //# sourceMappingURL=babylon.physicsJoint.js.map
  93270. var BABYLON;
  93271. (function (BABYLON) {
  93272. var PhysicsImpostor = /** @class */ (function () {
  93273. function PhysicsImpostor(object, type, _options, _scene) {
  93274. if (_options === void 0) { _options = { mass: 0 }; }
  93275. var _this = this;
  93276. this.object = object;
  93277. this.type = type;
  93278. this._options = _options;
  93279. this._scene = _scene;
  93280. this._bodyUpdateRequired = false;
  93281. this._onBeforePhysicsStepCallbacks = new Array();
  93282. this._onAfterPhysicsStepCallbacks = new Array();
  93283. this._onPhysicsCollideCallbacks = [];
  93284. this._deltaPosition = BABYLON.Vector3.Zero();
  93285. this._isDisposed = false;
  93286. //temp variables for parent rotation calculations
  93287. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  93288. this._tmpQuat = new BABYLON.Quaternion();
  93289. this._tmpQuat2 = new BABYLON.Quaternion();
  93290. /**
  93291. * this function is executed by the physics engine.
  93292. */
  93293. this.beforeStep = function () {
  93294. if (!_this._physicsEngine) {
  93295. return;
  93296. }
  93297. _this.object.translate(_this._deltaPosition, -1);
  93298. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  93299. _this.object.computeWorldMatrix(false);
  93300. if (_this.object.parent && _this.object.rotationQuaternion) {
  93301. _this.getParentsRotation();
  93302. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  93303. }
  93304. else {
  93305. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  93306. }
  93307. if (!_this._options.disableBidirectionalTransformation) {
  93308. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  93309. }
  93310. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  93311. func(_this);
  93312. });
  93313. };
  93314. /**
  93315. * this function is executed by the physics engine.
  93316. */
  93317. this.afterStep = function () {
  93318. if (!_this._physicsEngine) {
  93319. return;
  93320. }
  93321. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  93322. func(_this);
  93323. });
  93324. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  93325. // object has now its world rotation. needs to be converted to local.
  93326. if (_this.object.parent && _this.object.rotationQuaternion) {
  93327. _this.getParentsRotation();
  93328. _this._tmpQuat.conjugateInPlace();
  93329. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  93330. }
  93331. // take the position set and make it the absolute position of this object.
  93332. _this.object.setAbsolutePosition(_this.object.position);
  93333. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  93334. _this.object.translate(_this._deltaPosition, 1);
  93335. };
  93336. /**
  93337. * Legacy collision detection event support
  93338. */
  93339. this.onCollideEvent = null;
  93340. //event and body object due to cannon's event-based architecture.
  93341. this.onCollide = function (e) {
  93342. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  93343. return;
  93344. }
  93345. if (!_this._physicsEngine) {
  93346. return;
  93347. }
  93348. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  93349. if (otherImpostor) {
  93350. // Legacy collision detection event support
  93351. if (_this.onCollideEvent) {
  93352. _this.onCollideEvent(_this, otherImpostor);
  93353. }
  93354. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  93355. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  93356. }).forEach(function (obj) {
  93357. obj.callback(_this, otherImpostor);
  93358. });
  93359. }
  93360. };
  93361. //sanity check!
  93362. if (!this.object) {
  93363. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  93364. return;
  93365. }
  93366. //legacy support for old syntax.
  93367. if (!this._scene && object.getScene) {
  93368. this._scene = object.getScene();
  93369. }
  93370. if (!this._scene) {
  93371. return;
  93372. }
  93373. this._physicsEngine = this._scene.getPhysicsEngine();
  93374. if (!this._physicsEngine) {
  93375. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  93376. }
  93377. else {
  93378. //set the object's quaternion, if not set
  93379. if (!this.object.rotationQuaternion) {
  93380. if (this.object.rotation) {
  93381. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  93382. }
  93383. else {
  93384. this.object.rotationQuaternion = new BABYLON.Quaternion();
  93385. }
  93386. }
  93387. //default options params
  93388. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  93389. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  93390. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  93391. this._joints = [];
  93392. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  93393. if (!this.object.parent || this._options.ignoreParent) {
  93394. this._init();
  93395. }
  93396. else if (this.object.parent.physicsImpostor) {
  93397. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  93398. }
  93399. }
  93400. }
  93401. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  93402. get: function () {
  93403. return this._isDisposed;
  93404. },
  93405. enumerable: true,
  93406. configurable: true
  93407. });
  93408. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  93409. get: function () {
  93410. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  93411. },
  93412. set: function (value) {
  93413. this.setMass(value);
  93414. },
  93415. enumerable: true,
  93416. configurable: true
  93417. });
  93418. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  93419. get: function () {
  93420. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  93421. },
  93422. set: function (value) {
  93423. if (!this._physicsEngine) {
  93424. return;
  93425. }
  93426. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  93427. },
  93428. enumerable: true,
  93429. configurable: true
  93430. });
  93431. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  93432. get: function () {
  93433. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  93434. },
  93435. set: function (value) {
  93436. if (!this._physicsEngine) {
  93437. return;
  93438. }
  93439. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  93440. },
  93441. enumerable: true,
  93442. configurable: true
  93443. });
  93444. /**
  93445. * This function will completly initialize this impostor.
  93446. * It will create a new body - but only if this mesh has no parent.
  93447. * If it has, this impostor will not be used other than to define the impostor
  93448. * of the child mesh.
  93449. * @hidden
  93450. */
  93451. PhysicsImpostor.prototype._init = function () {
  93452. if (!this._physicsEngine) {
  93453. return;
  93454. }
  93455. this._physicsEngine.removeImpostor(this);
  93456. this.physicsBody = null;
  93457. this._parent = this._parent || this._getPhysicsParent();
  93458. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  93459. this._physicsEngine.addImpostor(this);
  93460. }
  93461. };
  93462. PhysicsImpostor.prototype._getPhysicsParent = function () {
  93463. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  93464. var parentMesh = this.object.parent;
  93465. return parentMesh.physicsImpostor;
  93466. }
  93467. return null;
  93468. };
  93469. /**
  93470. * Should a new body be generated.
  93471. */
  93472. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  93473. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  93474. };
  93475. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  93476. this.forceUpdate();
  93477. };
  93478. /**
  93479. * Force a regeneration of this or the parent's impostor's body.
  93480. * Use under cautious - This will remove all joints already implemented.
  93481. */
  93482. PhysicsImpostor.prototype.forceUpdate = function () {
  93483. this._init();
  93484. if (this.parent && !this._options.ignoreParent) {
  93485. this.parent.forceUpdate();
  93486. }
  93487. };
  93488. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  93489. /*public get mesh(): AbstractMesh {
  93490. return this._mesh;
  93491. }*/
  93492. /**
  93493. * Gets the body that holds this impostor. Either its own, or its parent.
  93494. */
  93495. get: function () {
  93496. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  93497. },
  93498. /**
  93499. * Set the physics body. Used mainly by the physics engine/plugin
  93500. */
  93501. set: function (physicsBody) {
  93502. if (this._physicsBody && this._physicsEngine) {
  93503. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  93504. }
  93505. this._physicsBody = physicsBody;
  93506. this.resetUpdateFlags();
  93507. },
  93508. enumerable: true,
  93509. configurable: true
  93510. });
  93511. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  93512. get: function () {
  93513. return !this._options.ignoreParent && this._parent ? this._parent : null;
  93514. },
  93515. set: function (value) {
  93516. this._parent = value;
  93517. },
  93518. enumerable: true,
  93519. configurable: true
  93520. });
  93521. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  93522. this._bodyUpdateRequired = false;
  93523. };
  93524. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  93525. if (this.object.getBoundingInfo) {
  93526. var q = this.object.rotationQuaternion;
  93527. //reset rotation
  93528. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  93529. //calculate the world matrix with no rotation
  93530. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  93531. var boundingInfo = this.object.getBoundingInfo();
  93532. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  93533. //bring back the rotation
  93534. this.object.rotationQuaternion = q;
  93535. //calculate the world matrix with the new rotation
  93536. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  93537. return size;
  93538. }
  93539. else {
  93540. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  93541. }
  93542. };
  93543. PhysicsImpostor.prototype.getObjectCenter = function () {
  93544. if (this.object.getBoundingInfo) {
  93545. var boundingInfo = this.object.getBoundingInfo();
  93546. return boundingInfo.boundingBox.centerWorld;
  93547. }
  93548. else {
  93549. return this.object.position;
  93550. }
  93551. };
  93552. /**
  93553. * Get a specific parametes from the options parameter.
  93554. */
  93555. PhysicsImpostor.prototype.getParam = function (paramName) {
  93556. return this._options[paramName];
  93557. };
  93558. /**
  93559. * Sets a specific parameter in the options given to the physics plugin
  93560. */
  93561. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  93562. this._options[paramName] = value;
  93563. this._bodyUpdateRequired = true;
  93564. };
  93565. /**
  93566. * Specifically change the body's mass option. Won't recreate the physics body object
  93567. */
  93568. PhysicsImpostor.prototype.setMass = function (mass) {
  93569. if (this.getParam("mass") !== mass) {
  93570. this.setParam("mass", mass);
  93571. }
  93572. if (this._physicsEngine) {
  93573. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  93574. }
  93575. };
  93576. PhysicsImpostor.prototype.getLinearVelocity = function () {
  93577. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  93578. };
  93579. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  93580. if (this._physicsEngine) {
  93581. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  93582. }
  93583. };
  93584. PhysicsImpostor.prototype.getAngularVelocity = function () {
  93585. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  93586. };
  93587. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  93588. if (this._physicsEngine) {
  93589. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  93590. }
  93591. };
  93592. /**
  93593. * Execute a function with the physics plugin native code.
  93594. * Provide a function the will have two variables - the world object and the physics body object.
  93595. */
  93596. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  93597. if (this._physicsEngine) {
  93598. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  93599. }
  93600. };
  93601. /**
  93602. * Register a function that will be executed before the physics world is stepping forward.
  93603. */
  93604. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  93605. this._onBeforePhysicsStepCallbacks.push(func);
  93606. };
  93607. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  93608. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  93609. if (index > -1) {
  93610. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  93611. }
  93612. else {
  93613. BABYLON.Tools.Warn("Function to remove was not found");
  93614. }
  93615. };
  93616. /**
  93617. * Register a function that will be executed after the physics step
  93618. */
  93619. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  93620. this._onAfterPhysicsStepCallbacks.push(func);
  93621. };
  93622. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  93623. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  93624. if (index > -1) {
  93625. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  93626. }
  93627. else {
  93628. BABYLON.Tools.Warn("Function to remove was not found");
  93629. }
  93630. };
  93631. /**
  93632. * register a function that will be executed when this impostor collides against a different body.
  93633. */
  93634. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  93635. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  93636. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  93637. };
  93638. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  93639. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  93640. var index = -1;
  93641. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  93642. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  93643. // chcek the arrays match
  93644. var sameList = cbDef.otherImpostors.every(function (impostor) {
  93645. return collidedAgainstList.indexOf(impostor) > -1;
  93646. });
  93647. if (sameList) {
  93648. index = idx;
  93649. }
  93650. return sameList;
  93651. }
  93652. return false;
  93653. });
  93654. if (found) {
  93655. this._onPhysicsCollideCallbacks.splice(index, 1);
  93656. }
  93657. else {
  93658. BABYLON.Tools.Warn("Function to remove was not found");
  93659. }
  93660. };
  93661. PhysicsImpostor.prototype.getParentsRotation = function () {
  93662. var parent = this.object.parent;
  93663. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  93664. while (parent) {
  93665. if (parent.rotationQuaternion) {
  93666. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  93667. }
  93668. else {
  93669. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  93670. }
  93671. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  93672. parent = parent.parent;
  93673. }
  93674. return this._tmpQuat;
  93675. };
  93676. /**
  93677. * Apply a force
  93678. */
  93679. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  93680. if (this._physicsEngine) {
  93681. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  93682. }
  93683. return this;
  93684. };
  93685. /**
  93686. * Apply an impulse
  93687. */
  93688. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  93689. if (this._physicsEngine) {
  93690. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  93691. }
  93692. return this;
  93693. };
  93694. /**
  93695. * A help function to create a joint.
  93696. */
  93697. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  93698. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  93699. this.addJoint(otherImpostor, joint);
  93700. return this;
  93701. };
  93702. /**
  93703. * Add a joint to this impostor with a different impostor.
  93704. */
  93705. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  93706. this._joints.push({
  93707. otherImpostor: otherImpostor,
  93708. joint: joint
  93709. });
  93710. if (this._physicsEngine) {
  93711. this._physicsEngine.addJoint(this, otherImpostor, joint);
  93712. }
  93713. return this;
  93714. };
  93715. /**
  93716. * Will keep this body still, in a sleep mode.
  93717. */
  93718. PhysicsImpostor.prototype.sleep = function () {
  93719. if (this._physicsEngine) {
  93720. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  93721. }
  93722. return this;
  93723. };
  93724. /**
  93725. * Wake the body up.
  93726. */
  93727. PhysicsImpostor.prototype.wakeUp = function () {
  93728. if (this._physicsEngine) {
  93729. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  93730. }
  93731. return this;
  93732. };
  93733. PhysicsImpostor.prototype.clone = function (newObject) {
  93734. if (!newObject)
  93735. return null;
  93736. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  93737. };
  93738. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  93739. var _this = this;
  93740. //no dispose if no physics engine is available.
  93741. if (!this._physicsEngine) {
  93742. return;
  93743. }
  93744. this._joints.forEach(function (j) {
  93745. if (_this._physicsEngine) {
  93746. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  93747. }
  93748. });
  93749. //dispose the physics body
  93750. this._physicsEngine.removeImpostor(this);
  93751. if (this.parent) {
  93752. this.parent.forceUpdate();
  93753. }
  93754. else {
  93755. /*this._object.getChildMeshes().forEach(function(mesh) {
  93756. if (mesh.physicsImpostor) {
  93757. if (disposeChildren) {
  93758. mesh.physicsImpostor.dispose();
  93759. mesh.physicsImpostor = null;
  93760. }
  93761. }
  93762. })*/
  93763. }
  93764. this._isDisposed = true;
  93765. };
  93766. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  93767. this._deltaPosition.copyFrom(position);
  93768. };
  93769. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  93770. if (!this._deltaRotation) {
  93771. this._deltaRotation = new BABYLON.Quaternion();
  93772. }
  93773. this._deltaRotation.copyFrom(rotation);
  93774. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  93775. };
  93776. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  93777. if (this._physicsEngine) {
  93778. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  93779. }
  93780. return this;
  93781. };
  93782. PhysicsImpostor.prototype.getRadius = function () {
  93783. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  93784. };
  93785. /**
  93786. * Sync a bone with this impostor
  93787. * @param bone The bone to sync to the impostor.
  93788. * @param boneMesh The mesh that the bone is influencing.
  93789. * @param jointPivot The pivot of the joint / bone in local space.
  93790. * @param distToJoint Optional distance from the impostor to the joint.
  93791. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  93792. */
  93793. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  93794. var tempVec = PhysicsImpostor._tmpVecs[0];
  93795. var mesh = this.object;
  93796. if (mesh.rotationQuaternion) {
  93797. if (adjustRotation) {
  93798. var tempQuat = PhysicsImpostor._tmpQuat;
  93799. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  93800. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  93801. }
  93802. else {
  93803. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  93804. }
  93805. }
  93806. tempVec.x = 0;
  93807. tempVec.y = 0;
  93808. tempVec.z = 0;
  93809. if (jointPivot) {
  93810. tempVec.x = jointPivot.x;
  93811. tempVec.y = jointPivot.y;
  93812. tempVec.z = jointPivot.z;
  93813. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  93814. if (distToJoint === undefined || distToJoint === null) {
  93815. distToJoint = jointPivot.length();
  93816. }
  93817. tempVec.x *= distToJoint;
  93818. tempVec.y *= distToJoint;
  93819. tempVec.z *= distToJoint;
  93820. }
  93821. if (bone.getParent()) {
  93822. tempVec.addInPlace(mesh.getAbsolutePosition());
  93823. bone.setAbsolutePosition(tempVec, boneMesh);
  93824. }
  93825. else {
  93826. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  93827. boneMesh.position.x -= tempVec.x;
  93828. boneMesh.position.y -= tempVec.y;
  93829. boneMesh.position.z -= tempVec.z;
  93830. }
  93831. };
  93832. /**
  93833. * Sync impostor to a bone
  93834. * @param bone The bone that the impostor will be synced to.
  93835. * @param boneMesh The mesh that the bone is influencing.
  93836. * @param jointPivot The pivot of the joint / bone in local space.
  93837. * @param distToJoint Optional distance from the impostor to the joint.
  93838. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  93839. * @param boneAxis Optional vector3 axis the bone is aligned with
  93840. */
  93841. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  93842. var mesh = this.object;
  93843. if (mesh.rotationQuaternion) {
  93844. if (adjustRotation) {
  93845. var tempQuat = PhysicsImpostor._tmpQuat;
  93846. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  93847. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  93848. }
  93849. else {
  93850. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  93851. }
  93852. }
  93853. var pos = PhysicsImpostor._tmpVecs[0];
  93854. var boneDir = PhysicsImpostor._tmpVecs[1];
  93855. if (!boneAxis) {
  93856. boneAxis = PhysicsImpostor._tmpVecs[2];
  93857. boneAxis.x = 0;
  93858. boneAxis.y = 1;
  93859. boneAxis.z = 0;
  93860. }
  93861. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  93862. bone.getAbsolutePositionToRef(boneMesh, pos);
  93863. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  93864. distToJoint = jointPivot.length();
  93865. }
  93866. if (distToJoint !== undefined && distToJoint !== null) {
  93867. pos.x += boneDir.x * distToJoint;
  93868. pos.y += boneDir.y * distToJoint;
  93869. pos.z += boneDir.z * distToJoint;
  93870. }
  93871. mesh.setAbsolutePosition(pos);
  93872. };
  93873. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  93874. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  93875. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  93876. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  93877. //Impostor types
  93878. PhysicsImpostor.NoImpostor = 0;
  93879. PhysicsImpostor.SphereImpostor = 1;
  93880. PhysicsImpostor.BoxImpostor = 2;
  93881. PhysicsImpostor.PlaneImpostor = 3;
  93882. PhysicsImpostor.MeshImpostor = 4;
  93883. PhysicsImpostor.CylinderImpostor = 7;
  93884. PhysicsImpostor.ParticleImpostor = 8;
  93885. PhysicsImpostor.HeightmapImpostor = 9;
  93886. return PhysicsImpostor;
  93887. }());
  93888. BABYLON.PhysicsImpostor = PhysicsImpostor;
  93889. })(BABYLON || (BABYLON = {}));
  93890. //# sourceMappingURL=babylon.physicsImpostor.js.map
  93891. var BABYLON;
  93892. (function (BABYLON) {
  93893. /**
  93894. * Class used to control physics engine
  93895. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  93896. */
  93897. var PhysicsEngine = /** @class */ (function () {
  93898. /**
  93899. * Creates a new Physics Engine
  93900. * @param gravity defines the gravity vector used by the simulation
  93901. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  93902. */
  93903. function PhysicsEngine(gravity, _physicsPlugin) {
  93904. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  93905. this._physicsPlugin = _physicsPlugin;
  93906. this._impostors = [];
  93907. this._joints = [];
  93908. if (!this._physicsPlugin.isSupported()) {
  93909. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  93910. + "Please make sure it is included.");
  93911. }
  93912. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  93913. this.setGravity(gravity);
  93914. this.setTimeStep();
  93915. }
  93916. /**
  93917. * Sets the gravity vector used by the simulation
  93918. * @param gravity defines the gravity vector to use
  93919. */
  93920. PhysicsEngine.prototype.setGravity = function (gravity) {
  93921. this.gravity = gravity;
  93922. this._physicsPlugin.setGravity(this.gravity);
  93923. };
  93924. /**
  93925. * Set the time step of the physics engine.
  93926. * Default is 1/60.
  93927. * To slow it down, enter 1/600 for example.
  93928. * To speed it up, 1/30
  93929. * @param newTimeStep defines the new timestep to apply to this world.
  93930. */
  93931. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  93932. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  93933. this._physicsPlugin.setTimeStep(newTimeStep);
  93934. };
  93935. /**
  93936. * Get the time step of the physics engine.
  93937. * @returns the current time step
  93938. */
  93939. PhysicsEngine.prototype.getTimeStep = function () {
  93940. return this._physicsPlugin.getTimeStep();
  93941. };
  93942. /**
  93943. * Release all resources
  93944. */
  93945. PhysicsEngine.prototype.dispose = function () {
  93946. this._impostors.forEach(function (impostor) {
  93947. impostor.dispose();
  93948. });
  93949. this._physicsPlugin.dispose();
  93950. };
  93951. /**
  93952. * Gets the name of the current physics plugin
  93953. * @returns the name of the plugin
  93954. */
  93955. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  93956. return this._physicsPlugin.name;
  93957. };
  93958. /**
  93959. * Adding a new impostor for the impostor tracking.
  93960. * This will be done by the impostor itself.
  93961. * @param impostor the impostor to add
  93962. */
  93963. PhysicsEngine.prototype.addImpostor = function (impostor) {
  93964. impostor.uniqueId = this._impostors.push(impostor);
  93965. //if no parent, generate the body
  93966. if (!impostor.parent) {
  93967. this._physicsPlugin.generatePhysicsBody(impostor);
  93968. }
  93969. };
  93970. /**
  93971. * Remove an impostor from the engine.
  93972. * This impostor and its mesh will not longer be updated by the physics engine.
  93973. * @param impostor the impostor to remove
  93974. */
  93975. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  93976. var index = this._impostors.indexOf(impostor);
  93977. if (index > -1) {
  93978. var removed = this._impostors.splice(index, 1);
  93979. //Is it needed?
  93980. if (removed.length) {
  93981. //this will also remove it from the world.
  93982. removed[0].physicsBody = null;
  93983. }
  93984. }
  93985. };
  93986. /**
  93987. * Add a joint to the physics engine
  93988. * @param mainImpostor defines the main impostor to which the joint is added.
  93989. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  93990. * @param joint defines the joint that will connect both impostors.
  93991. */
  93992. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  93993. var impostorJoint = {
  93994. mainImpostor: mainImpostor,
  93995. connectedImpostor: connectedImpostor,
  93996. joint: joint
  93997. };
  93998. joint.physicsPlugin = this._physicsPlugin;
  93999. this._joints.push(impostorJoint);
  94000. this._physicsPlugin.generateJoint(impostorJoint);
  94001. };
  94002. /**
  94003. * Removes a joint from the simulation
  94004. * @param mainImpostor defines the impostor used with the joint
  94005. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  94006. * @param joint defines the joint to remove
  94007. */
  94008. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  94009. var matchingJoints = this._joints.filter(function (impostorJoint) {
  94010. return (impostorJoint.connectedImpostor === connectedImpostor
  94011. && impostorJoint.joint === joint
  94012. && impostorJoint.mainImpostor === mainImpostor);
  94013. });
  94014. if (matchingJoints.length) {
  94015. this._physicsPlugin.removeJoint(matchingJoints[0]);
  94016. //TODO remove it from the list as well
  94017. }
  94018. };
  94019. /**
  94020. * Called by the scene. No need to call it.
  94021. * @param delta defines the timespam between frames
  94022. */
  94023. PhysicsEngine.prototype._step = function (delta) {
  94024. var _this = this;
  94025. //check if any mesh has no body / requires an update
  94026. this._impostors.forEach(function (impostor) {
  94027. if (impostor.isBodyInitRequired()) {
  94028. _this._physicsPlugin.generatePhysicsBody(impostor);
  94029. }
  94030. });
  94031. if (delta > 0.1) {
  94032. delta = 0.1;
  94033. }
  94034. else if (delta <= 0) {
  94035. delta = 1.0 / 60.0;
  94036. }
  94037. this._physicsPlugin.executeStep(delta, this._impostors);
  94038. };
  94039. /**
  94040. * Gets the current plugin used to run the simulation
  94041. * @returns current plugin
  94042. */
  94043. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  94044. return this._physicsPlugin;
  94045. };
  94046. /**
  94047. * Gets the list of physic impostors
  94048. * @returns an array of PhysicsImpostor
  94049. */
  94050. PhysicsEngine.prototype.getImpostors = function () {
  94051. return this._impostors;
  94052. };
  94053. /**
  94054. * Gets the impostor for a physics enabled object
  94055. * @param object defines the object impersonated by the impostor
  94056. * @returns the PhysicsImpostor or null if not found
  94057. */
  94058. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  94059. for (var i = 0; i < this._impostors.length; ++i) {
  94060. if (this._impostors[i].object === object) {
  94061. return this._impostors[i];
  94062. }
  94063. }
  94064. return null;
  94065. };
  94066. /**
  94067. * Gets the impostor for a physics body object
  94068. * @param body defines physics body used by the impostor
  94069. * @returns the PhysicsImpostor or null if not found
  94070. */
  94071. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  94072. for (var i = 0; i < this._impostors.length; ++i) {
  94073. if (this._impostors[i].physicsBody === body) {
  94074. return this._impostors[i];
  94075. }
  94076. }
  94077. return null;
  94078. };
  94079. /**
  94080. * Global value used to control the smallest number supported by the simulation
  94081. */
  94082. PhysicsEngine.Epsilon = 0.001;
  94083. return PhysicsEngine;
  94084. }());
  94085. BABYLON.PhysicsEngine = PhysicsEngine;
  94086. })(BABYLON || (BABYLON = {}));
  94087. //# sourceMappingURL=babylon.physicsEngine.js.map
  94088. var BABYLON;
  94089. (function (BABYLON) {
  94090. var PhysicsHelper = /** @class */ (function () {
  94091. function PhysicsHelper(scene) {
  94092. this._scene = scene;
  94093. this._physicsEngine = this._scene.getPhysicsEngine();
  94094. if (!this._physicsEngine) {
  94095. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  94096. }
  94097. }
  94098. /**
  94099. * @param {Vector3} origin the origin of the explosion
  94100. * @param {number} radius the explosion radius
  94101. * @param {number} strength the explosion strength
  94102. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  94103. */
  94104. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  94105. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  94106. if (!this._physicsEngine) {
  94107. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  94108. return null;
  94109. }
  94110. var impostors = this._physicsEngine.getImpostors();
  94111. if (impostors.length === 0) {
  94112. return null;
  94113. }
  94114. var event = new PhysicsRadialExplosionEvent(this._scene);
  94115. impostors.forEach(function (impostor) {
  94116. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  94117. if (!impostorForceAndContactPoint) {
  94118. return;
  94119. }
  94120. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  94121. });
  94122. event.dispose(false);
  94123. return event;
  94124. };
  94125. /**
  94126. * @param {Vector3} origin the origin of the explosion
  94127. * @param {number} radius the explosion radius
  94128. * @param {number} strength the explosion strength
  94129. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  94130. */
  94131. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  94132. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  94133. if (!this._physicsEngine) {
  94134. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  94135. return null;
  94136. }
  94137. var impostors = this._physicsEngine.getImpostors();
  94138. if (impostors.length === 0) {
  94139. return null;
  94140. }
  94141. var event = new PhysicsRadialExplosionEvent(this._scene);
  94142. impostors.forEach(function (impostor) {
  94143. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  94144. if (!impostorForceAndContactPoint) {
  94145. return;
  94146. }
  94147. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  94148. });
  94149. event.dispose(false);
  94150. return event;
  94151. };
  94152. /**
  94153. * @param {Vector3} origin the origin of the explosion
  94154. * @param {number} radius the explosion radius
  94155. * @param {number} strength the explosion strength
  94156. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  94157. */
  94158. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  94159. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  94160. if (!this._physicsEngine) {
  94161. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  94162. return null;
  94163. }
  94164. var impostors = this._physicsEngine.getImpostors();
  94165. if (impostors.length === 0) {
  94166. return null;
  94167. }
  94168. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  94169. event.dispose(false);
  94170. return event;
  94171. };
  94172. /**
  94173. * @param {Vector3} origin the origin of the updraft
  94174. * @param {number} radius the radius of the updraft
  94175. * @param {number} strength the strength of the updraft
  94176. * @param {number} height the height of the updraft
  94177. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  94178. */
  94179. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  94180. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  94181. if (!this._physicsEngine) {
  94182. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  94183. return null;
  94184. }
  94185. if (this._physicsEngine.getImpostors().length === 0) {
  94186. return null;
  94187. }
  94188. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  94189. event.dispose(false);
  94190. return event;
  94191. };
  94192. /**
  94193. * @param {Vector3} origin the of the vortex
  94194. * @param {number} radius the radius of the vortex
  94195. * @param {number} strength the strength of the vortex
  94196. * @param {number} height the height of the vortex
  94197. */
  94198. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  94199. if (!this._physicsEngine) {
  94200. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  94201. return null;
  94202. }
  94203. if (this._physicsEngine.getImpostors().length === 0) {
  94204. return null;
  94205. }
  94206. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  94207. event.dispose(false);
  94208. return event;
  94209. };
  94210. return PhysicsHelper;
  94211. }());
  94212. BABYLON.PhysicsHelper = PhysicsHelper;
  94213. /***** Radial explosion *****/
  94214. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  94215. function PhysicsRadialExplosionEvent(scene) {
  94216. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  94217. this._rays = [];
  94218. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  94219. this._scene = scene;
  94220. }
  94221. /**
  94222. * Returns the data related to the radial explosion event (sphere & rays).
  94223. * @returns {PhysicsRadialExplosionEventData}
  94224. */
  94225. PhysicsRadialExplosionEvent.prototype.getData = function () {
  94226. this._dataFetched = true;
  94227. return {
  94228. sphere: this._sphere,
  94229. rays: this._rays,
  94230. };
  94231. };
  94232. /**
  94233. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  94234. * @param impostor
  94235. * @param {Vector3} origin the origin of the explosion
  94236. * @param {number} radius the explosion radius
  94237. * @param {number} strength the explosion strength
  94238. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  94239. * @returns {Nullable<PhysicsForceAndContactPoint>}
  94240. */
  94241. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  94242. if (impostor.mass === 0) {
  94243. return null;
  94244. }
  94245. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  94246. return null;
  94247. }
  94248. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  94249. return null;
  94250. }
  94251. var impostorObjectCenter = impostor.getObjectCenter();
  94252. var direction = impostorObjectCenter.subtract(origin);
  94253. var ray = new BABYLON.Ray(origin, direction, radius);
  94254. this._rays.push(ray);
  94255. var hit = ray.intersectsMesh(impostor.object);
  94256. var contactPoint = hit.pickedPoint;
  94257. if (!contactPoint) {
  94258. return null;
  94259. }
  94260. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  94261. if (distanceFromOrigin > radius) {
  94262. return null;
  94263. }
  94264. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  94265. ? strength
  94266. : strength * (1 - (distanceFromOrigin / radius));
  94267. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  94268. return { force: force, contactPoint: contactPoint };
  94269. };
  94270. /**
  94271. * Disposes the sphere.
  94272. * @param {bolean} force
  94273. */
  94274. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  94275. var _this = this;
  94276. if (force === void 0) { force = true; }
  94277. if (force) {
  94278. this._sphere.dispose();
  94279. }
  94280. else {
  94281. setTimeout(function () {
  94282. if (!_this._dataFetched) {
  94283. _this._sphere.dispose();
  94284. }
  94285. }, 0);
  94286. }
  94287. };
  94288. /*** Helpers ***/
  94289. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  94290. if (!this._sphere) {
  94291. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  94292. this._sphere.isVisible = false;
  94293. }
  94294. };
  94295. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  94296. var impostorObject = impostor.object;
  94297. this._prepareSphere();
  94298. this._sphere.position = origin;
  94299. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  94300. this._sphere._updateBoundingInfo();
  94301. this._sphere.computeWorldMatrix(true);
  94302. return this._sphere.intersectsMesh(impostorObject, true);
  94303. };
  94304. return PhysicsRadialExplosionEvent;
  94305. }());
  94306. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  94307. /***** Gravitational Field *****/
  94308. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  94309. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  94310. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  94311. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  94312. this._physicsHelper = physicsHelper;
  94313. this._scene = scene;
  94314. this._origin = origin;
  94315. this._radius = radius;
  94316. this._strength = strength;
  94317. this._falloff = falloff;
  94318. this._tickCallback = this._tick.bind(this);
  94319. }
  94320. /**
  94321. * Returns the data related to the gravitational field event (sphere).
  94322. * @returns {PhysicsGravitationalFieldEventData}
  94323. */
  94324. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  94325. this._dataFetched = true;
  94326. return {
  94327. sphere: this._sphere,
  94328. };
  94329. };
  94330. /**
  94331. * Enables the gravitational field.
  94332. */
  94333. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  94334. this._tickCallback.call(this);
  94335. this._scene.registerBeforeRender(this._tickCallback);
  94336. };
  94337. /**
  94338. * Disables the gravitational field.
  94339. */
  94340. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  94341. this._scene.unregisterBeforeRender(this._tickCallback);
  94342. };
  94343. /**
  94344. * Disposes the sphere.
  94345. * @param {bolean} force
  94346. */
  94347. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  94348. var _this = this;
  94349. if (force === void 0) { force = true; }
  94350. if (force) {
  94351. this._sphere.dispose();
  94352. }
  94353. else {
  94354. setTimeout(function () {
  94355. if (!_this._dataFetched) {
  94356. _this._sphere.dispose();
  94357. }
  94358. }, 0);
  94359. }
  94360. };
  94361. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  94362. // Since the params won't change, we fetch the event only once
  94363. if (this._sphere) {
  94364. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  94365. }
  94366. else {
  94367. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  94368. if (radialExplosionEvent) {
  94369. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  94370. }
  94371. }
  94372. };
  94373. return PhysicsGravitationalFieldEvent;
  94374. }());
  94375. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  94376. /***** Updraft *****/
  94377. var PhysicsUpdraftEvent = /** @class */ (function () {
  94378. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  94379. this._scene = _scene;
  94380. this._origin = _origin;
  94381. this._radius = _radius;
  94382. this._strength = _strength;
  94383. this._height = _height;
  94384. this._updraftMode = _updraftMode;
  94385. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  94386. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  94387. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  94388. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  94389. this._physicsEngine = this._scene.getPhysicsEngine();
  94390. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  94391. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  94392. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  94393. this._originDirection = this._origin.subtract(this._originTop).normalize();
  94394. }
  94395. this._tickCallback = this._tick.bind(this);
  94396. }
  94397. /**
  94398. * Returns the data related to the updraft event (cylinder).
  94399. * @returns {PhysicsUpdraftEventData}
  94400. */
  94401. PhysicsUpdraftEvent.prototype.getData = function () {
  94402. this._dataFetched = true;
  94403. return {
  94404. cylinder: this._cylinder,
  94405. };
  94406. };
  94407. /**
  94408. * Enables the updraft.
  94409. */
  94410. PhysicsUpdraftEvent.prototype.enable = function () {
  94411. this._tickCallback.call(this);
  94412. this._scene.registerBeforeRender(this._tickCallback);
  94413. };
  94414. /**
  94415. * Disables the cortex.
  94416. */
  94417. PhysicsUpdraftEvent.prototype.disable = function () {
  94418. this._scene.unregisterBeforeRender(this._tickCallback);
  94419. };
  94420. /**
  94421. * Disposes the sphere.
  94422. * @param {bolean} force
  94423. */
  94424. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  94425. var _this = this;
  94426. if (force === void 0) { force = true; }
  94427. if (force) {
  94428. this._cylinder.dispose();
  94429. }
  94430. else {
  94431. setTimeout(function () {
  94432. if (!_this._dataFetched) {
  94433. _this._cylinder.dispose();
  94434. }
  94435. }, 0);
  94436. }
  94437. };
  94438. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  94439. if (impostor.mass === 0) {
  94440. return null;
  94441. }
  94442. if (!this._intersectsWithCylinder(impostor)) {
  94443. return null;
  94444. }
  94445. var impostorObjectCenter = impostor.getObjectCenter();
  94446. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  94447. var direction = this._originDirection;
  94448. }
  94449. else {
  94450. var direction = impostorObjectCenter.subtract(this._originTop);
  94451. }
  94452. var multiplier = this._strength * -1;
  94453. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  94454. return { force: force, contactPoint: impostorObjectCenter };
  94455. };
  94456. PhysicsUpdraftEvent.prototype._tick = function () {
  94457. var _this = this;
  94458. this._physicsEngine.getImpostors().forEach(function (impostor) {
  94459. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  94460. if (!impostorForceAndContactPoint) {
  94461. return;
  94462. }
  94463. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  94464. });
  94465. };
  94466. /*** Helpers ***/
  94467. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  94468. if (!this._cylinder) {
  94469. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  94470. height: this._height,
  94471. diameter: this._radius * 2,
  94472. }, this._scene);
  94473. this._cylinder.isVisible = false;
  94474. }
  94475. };
  94476. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  94477. var impostorObject = impostor.object;
  94478. this._prepareCylinder();
  94479. this._cylinder.position = this._cylinderPosition;
  94480. return this._cylinder.intersectsMesh(impostorObject, true);
  94481. };
  94482. return PhysicsUpdraftEvent;
  94483. }());
  94484. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  94485. /***** Vortex *****/
  94486. var PhysicsVortexEvent = /** @class */ (function () {
  94487. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  94488. this._scene = _scene;
  94489. this._origin = _origin;
  94490. this._radius = _radius;
  94491. this._strength = _strength;
  94492. this._height = _height;
  94493. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  94494. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  94495. this._updraftMultiplier = 0.02;
  94496. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  94497. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  94498. this._physicsEngine = this._scene.getPhysicsEngine();
  94499. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  94500. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  94501. this._tickCallback = this._tick.bind(this);
  94502. }
  94503. /**
  94504. * Returns the data related to the vortex event (cylinder).
  94505. * @returns {PhysicsVortexEventData}
  94506. */
  94507. PhysicsVortexEvent.prototype.getData = function () {
  94508. this._dataFetched = true;
  94509. return {
  94510. cylinder: this._cylinder,
  94511. };
  94512. };
  94513. /**
  94514. * Enables the vortex.
  94515. */
  94516. PhysicsVortexEvent.prototype.enable = function () {
  94517. this._tickCallback.call(this);
  94518. this._scene.registerBeforeRender(this._tickCallback);
  94519. };
  94520. /**
  94521. * Disables the cortex.
  94522. */
  94523. PhysicsVortexEvent.prototype.disable = function () {
  94524. this._scene.unregisterBeforeRender(this._tickCallback);
  94525. };
  94526. /**
  94527. * Disposes the sphere.
  94528. * @param {bolean} force
  94529. */
  94530. PhysicsVortexEvent.prototype.dispose = function (force) {
  94531. var _this = this;
  94532. if (force === void 0) { force = true; }
  94533. if (force) {
  94534. this._cylinder.dispose();
  94535. }
  94536. else {
  94537. setTimeout(function () {
  94538. if (!_this._dataFetched) {
  94539. _this._cylinder.dispose();
  94540. }
  94541. }, 0);
  94542. }
  94543. };
  94544. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  94545. if (impostor.mass === 0) {
  94546. return null;
  94547. }
  94548. if (!this._intersectsWithCylinder(impostor)) {
  94549. return null;
  94550. }
  94551. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  94552. return null;
  94553. }
  94554. var impostorObjectCenter = impostor.getObjectCenter();
  94555. 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)
  94556. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  94557. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  94558. var hit = ray.intersectsMesh(impostor.object);
  94559. var contactPoint = hit.pickedPoint;
  94560. if (!contactPoint) {
  94561. return null;
  94562. }
  94563. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  94564. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  94565. var directionToOrigin = contactPoint.normalize();
  94566. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  94567. directionToOrigin = directionToOrigin.negate();
  94568. }
  94569. // TODO: find a more physically based solution
  94570. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  94571. var forceX = directionToOrigin.x * this._strength / 8;
  94572. var forceY = directionToOrigin.y * this._updraftMultiplier;
  94573. var forceZ = directionToOrigin.z * this._strength / 8;
  94574. }
  94575. else {
  94576. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  94577. var forceY = this._originTop.y * this._updraftMultiplier;
  94578. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  94579. }
  94580. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  94581. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  94582. return { force: force, contactPoint: impostorObjectCenter };
  94583. };
  94584. PhysicsVortexEvent.prototype._tick = function () {
  94585. var _this = this;
  94586. this._physicsEngine.getImpostors().forEach(function (impostor) {
  94587. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  94588. if (!impostorForceAndContactPoint) {
  94589. return;
  94590. }
  94591. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  94592. });
  94593. };
  94594. /*** Helpers ***/
  94595. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  94596. if (!this._cylinder) {
  94597. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  94598. height: this._height,
  94599. diameter: this._radius * 2,
  94600. }, this._scene);
  94601. this._cylinder.isVisible = false;
  94602. }
  94603. };
  94604. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  94605. var impostorObject = impostor.object;
  94606. this._prepareCylinder();
  94607. this._cylinder.position = this._cylinderPosition;
  94608. return this._cylinder.intersectsMesh(impostorObject, true);
  94609. };
  94610. return PhysicsVortexEvent;
  94611. }());
  94612. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  94613. /***** Enums *****/
  94614. /**
  94615. * The strenght of the force in correspondence to the distance of the affected object
  94616. */
  94617. var PhysicsRadialImpulseFalloff;
  94618. (function (PhysicsRadialImpulseFalloff) {
  94619. /** Defines that impulse is constant in strength across it's whole radius */
  94620. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  94621. /** DEfines that impulse gets weaker if it's further from the origin */
  94622. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  94623. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  94624. /**
  94625. * The strenght of the force in correspondence to the distance of the affected object
  94626. */
  94627. var PhysicsUpdraftMode;
  94628. (function (PhysicsUpdraftMode) {
  94629. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  94630. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  94631. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  94632. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  94633. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  94634. })(BABYLON || (BABYLON = {}));
  94635. //# sourceMappingURL=babylon.physicsHelper.js.map
  94636. var BABYLON;
  94637. (function (BABYLON) {
  94638. /** @hidden */
  94639. var CannonJSPlugin = /** @class */ (function () {
  94640. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  94641. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  94642. if (iterations === void 0) { iterations = 10; }
  94643. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  94644. this.name = "CannonJSPlugin";
  94645. this._physicsMaterials = new Array();
  94646. this._fixedTimeStep = 1 / 60;
  94647. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  94648. this.BJSCANNON = CANNON;
  94649. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  94650. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  94651. this._tmpPosition = BABYLON.Vector3.Zero();
  94652. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  94653. this._tmpUnityRotation = new BABYLON.Quaternion();
  94654. if (!this.isSupported()) {
  94655. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  94656. return;
  94657. }
  94658. this._extendNamespace();
  94659. this.world = new this.BJSCANNON.World();
  94660. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  94661. this.world.solver.iterations = iterations;
  94662. }
  94663. CannonJSPlugin.prototype.setGravity = function (gravity) {
  94664. this.world.gravity.copy(gravity);
  94665. };
  94666. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  94667. this._fixedTimeStep = timeStep;
  94668. };
  94669. CannonJSPlugin.prototype.getTimeStep = function () {
  94670. return this._fixedTimeStep;
  94671. };
  94672. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  94673. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  94674. };
  94675. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  94676. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  94677. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  94678. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  94679. };
  94680. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  94681. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  94682. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  94683. impostor.physicsBody.applyForce(impulse, worldPoint);
  94684. };
  94685. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  94686. //parent-child relationship. Does this impostor has a parent impostor?
  94687. if (impostor.parent) {
  94688. if (impostor.physicsBody) {
  94689. this.removePhysicsBody(impostor);
  94690. //TODO is that needed?
  94691. impostor.forceUpdate();
  94692. }
  94693. return;
  94694. }
  94695. //should a new body be created for this impostor?
  94696. if (impostor.isBodyInitRequired()) {
  94697. var shape = this._createShape(impostor);
  94698. //unregister events, if body is being changed
  94699. var oldBody = impostor.physicsBody;
  94700. if (oldBody) {
  94701. this.removePhysicsBody(impostor);
  94702. }
  94703. //create the body and material
  94704. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  94705. var bodyCreationObject = {
  94706. mass: impostor.getParam("mass"),
  94707. material: material
  94708. };
  94709. // A simple extend, in case native options were used.
  94710. var nativeOptions = impostor.getParam("nativeOptions");
  94711. for (var key in nativeOptions) {
  94712. if (nativeOptions.hasOwnProperty(key)) {
  94713. bodyCreationObject[key] = nativeOptions[key];
  94714. }
  94715. }
  94716. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  94717. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  94718. this.world.addEventListener("preStep", impostor.beforeStep);
  94719. this.world.addEventListener("postStep", impostor.afterStep);
  94720. impostor.physicsBody.addShape(shape);
  94721. this.world.add(impostor.physicsBody);
  94722. //try to keep the body moving in the right direction by taking old properties.
  94723. //Should be tested!
  94724. if (oldBody) {
  94725. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  94726. impostor.physicsBody[param].copy(oldBody[param]);
  94727. });
  94728. }
  94729. this._processChildMeshes(impostor);
  94730. }
  94731. //now update the body's transformation
  94732. this._updatePhysicsBodyTransformation(impostor);
  94733. };
  94734. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  94735. var _this = this;
  94736. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  94737. var currentRotation = mainImpostor.object.rotationQuaternion;
  94738. if (meshChildren.length) {
  94739. var processMesh = function (localPosition, mesh) {
  94740. if (!currentRotation || !mesh.rotationQuaternion) {
  94741. return;
  94742. }
  94743. var childImpostor = mesh.getPhysicsImpostor();
  94744. if (childImpostor) {
  94745. var parent = childImpostor.parent;
  94746. if (parent !== mainImpostor) {
  94747. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  94748. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  94749. if (childImpostor.physicsBody) {
  94750. _this.removePhysicsBody(childImpostor);
  94751. childImpostor.physicsBody = null;
  94752. }
  94753. childImpostor.parent = mainImpostor;
  94754. childImpostor.resetUpdateFlags();
  94755. 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));
  94756. //Add the mass of the children.
  94757. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  94758. }
  94759. }
  94760. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  94761. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  94762. };
  94763. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  94764. }
  94765. };
  94766. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  94767. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  94768. this.world.removeEventListener("preStep", impostor.beforeStep);
  94769. this.world.removeEventListener("postStep", impostor.afterStep);
  94770. this.world.remove(impostor.physicsBody);
  94771. };
  94772. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  94773. var mainBody = impostorJoint.mainImpostor.physicsBody;
  94774. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  94775. if (!mainBody || !connectedBody) {
  94776. return;
  94777. }
  94778. var constraint;
  94779. var jointData = impostorJoint.joint.jointData;
  94780. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  94781. var constraintData = {
  94782. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  94783. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  94784. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  94785. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  94786. maxForce: jointData.nativeParams.maxForce,
  94787. collideConnected: !!jointData.collision
  94788. };
  94789. switch (impostorJoint.joint.type) {
  94790. case BABYLON.PhysicsJoint.HingeJoint:
  94791. case BABYLON.PhysicsJoint.Hinge2Joint:
  94792. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  94793. break;
  94794. case BABYLON.PhysicsJoint.DistanceJoint:
  94795. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  94796. break;
  94797. case BABYLON.PhysicsJoint.SpringJoint:
  94798. var springData = jointData;
  94799. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  94800. restLength: springData.length,
  94801. stiffness: springData.stiffness,
  94802. damping: springData.damping,
  94803. localAnchorA: constraintData.pivotA,
  94804. localAnchorB: constraintData.pivotB
  94805. });
  94806. break;
  94807. case BABYLON.PhysicsJoint.LockJoint:
  94808. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  94809. break;
  94810. case BABYLON.PhysicsJoint.PointToPointJoint:
  94811. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  94812. default:
  94813. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  94814. break;
  94815. }
  94816. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  94817. constraint.collideConnected = !!jointData.collision;
  94818. impostorJoint.joint.physicsJoint = constraint;
  94819. //don't add spring as constraint, as it is not one.
  94820. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  94821. this.world.addConstraint(constraint);
  94822. }
  94823. else {
  94824. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  94825. constraint.applyForce();
  94826. };
  94827. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  94828. }
  94829. };
  94830. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  94831. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  94832. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  94833. }
  94834. else {
  94835. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  94836. }
  94837. };
  94838. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  94839. var index;
  94840. var mat;
  94841. for (index = 0; index < this._physicsMaterials.length; index++) {
  94842. mat = this._physicsMaterials[index];
  94843. if (mat.friction === friction && mat.restitution === restitution) {
  94844. return mat;
  94845. }
  94846. }
  94847. var currentMat = new this.BJSCANNON.Material(name);
  94848. currentMat.friction = friction;
  94849. currentMat.restitution = restitution;
  94850. this._physicsMaterials.push(currentMat);
  94851. return currentMat;
  94852. };
  94853. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  94854. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  94855. };
  94856. CannonJSPlugin.prototype._createShape = function (impostor) {
  94857. var object = impostor.object;
  94858. var returnValue;
  94859. var extendSize = impostor.getObjectExtendSize();
  94860. switch (impostor.type) {
  94861. case BABYLON.PhysicsImpostor.SphereImpostor:
  94862. var radiusX = extendSize.x;
  94863. var radiusY = extendSize.y;
  94864. var radiusZ = extendSize.z;
  94865. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  94866. break;
  94867. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  94868. case BABYLON.PhysicsImpostor.CylinderImpostor:
  94869. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  94870. break;
  94871. case BABYLON.PhysicsImpostor.BoxImpostor:
  94872. var box = extendSize.scale(0.5);
  94873. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  94874. break;
  94875. case BABYLON.PhysicsImpostor.PlaneImpostor:
  94876. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  94877. returnValue = new this.BJSCANNON.Plane();
  94878. break;
  94879. case BABYLON.PhysicsImpostor.MeshImpostor:
  94880. // should transform the vertex data to world coordinates!!
  94881. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  94882. var rawFaces = object.getIndices ? object.getIndices() : [];
  94883. if (!rawVerts)
  94884. return;
  94885. // get only scale! so the object could transform correctly.
  94886. var oldPosition = object.position.clone();
  94887. var oldRotation = object.rotation && object.rotation.clone();
  94888. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  94889. object.position.copyFromFloats(0, 0, 0);
  94890. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  94891. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  94892. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  94893. var transform = object.computeWorldMatrix(true);
  94894. // convert rawVerts to object space
  94895. var temp = new Array();
  94896. var index;
  94897. for (index = 0; index < rawVerts.length; index += 3) {
  94898. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  94899. }
  94900. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  94901. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  94902. //now set back the transformation!
  94903. object.position.copyFrom(oldPosition);
  94904. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  94905. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  94906. break;
  94907. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  94908. var oldPosition2 = object.position.clone();
  94909. var oldRotation2 = object.rotation && object.rotation.clone();
  94910. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  94911. object.position.copyFromFloats(0, 0, 0);
  94912. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  94913. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  94914. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  94915. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  94916. returnValue = this._createHeightmap(object);
  94917. object.position.copyFrom(oldPosition2);
  94918. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  94919. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  94920. object.computeWorldMatrix(true);
  94921. break;
  94922. case BABYLON.PhysicsImpostor.ParticleImpostor:
  94923. returnValue = new this.BJSCANNON.Particle();
  94924. break;
  94925. }
  94926. return returnValue;
  94927. };
  94928. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  94929. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  94930. var transform = object.computeWorldMatrix(true);
  94931. // convert rawVerts to object space
  94932. var temp = new Array();
  94933. var index;
  94934. for (index = 0; index < pos.length; index += 3) {
  94935. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  94936. }
  94937. pos = temp;
  94938. var matrix = new Array();
  94939. //For now pointDepth will not be used and will be automatically calculated.
  94940. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  94941. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  94942. var boundingInfo = object.getBoundingInfo();
  94943. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  94944. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  94945. var elementSize = dim * 2 / arraySize;
  94946. for (var i = 0; i < pos.length; i = i + 3) {
  94947. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  94948. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  94949. var y = -pos[i + 2] + minY;
  94950. if (!matrix[x]) {
  94951. matrix[x] = [];
  94952. }
  94953. if (!matrix[x][z]) {
  94954. matrix[x][z] = y;
  94955. }
  94956. matrix[x][z] = Math.max(y, matrix[x][z]);
  94957. }
  94958. for (var x = 0; x <= arraySize; ++x) {
  94959. if (!matrix[x]) {
  94960. var loc = 1;
  94961. while (!matrix[(x + loc) % arraySize]) {
  94962. loc++;
  94963. }
  94964. matrix[x] = matrix[(x + loc) % arraySize].slice();
  94965. //console.log("missing x", x);
  94966. }
  94967. for (var z = 0; z <= arraySize; ++z) {
  94968. if (!matrix[x][z]) {
  94969. var loc = 1;
  94970. var newValue;
  94971. while (newValue === undefined) {
  94972. newValue = matrix[x][(z + loc++) % arraySize];
  94973. }
  94974. matrix[x][z] = newValue;
  94975. }
  94976. }
  94977. }
  94978. var shape = new this.BJSCANNON.Heightfield(matrix, {
  94979. elementSize: elementSize
  94980. });
  94981. //For future reference, needed for body transformation
  94982. shape.minY = minY;
  94983. return shape;
  94984. };
  94985. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  94986. var object = impostor.object;
  94987. //make sure it is updated...
  94988. object.computeWorldMatrix && object.computeWorldMatrix(true);
  94989. // The delta between the mesh position and the mesh bounding box center
  94990. var bInfo = object.getBoundingInfo();
  94991. if (!bInfo)
  94992. return;
  94993. var center = impostor.getObjectCenter();
  94994. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  94995. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  94996. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  94997. this._tmpPosition.copyFrom(center);
  94998. var quaternion = object.rotationQuaternion;
  94999. if (!quaternion) {
  95000. return;
  95001. }
  95002. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  95003. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  95004. //-90 DEG in X, precalculated
  95005. quaternion = quaternion.multiply(this._minus90X);
  95006. //Invert! (Precalculated, 90 deg in X)
  95007. //No need to clone. this will never change.
  95008. impostor.setDeltaRotation(this._plus90X);
  95009. }
  95010. //If it is a heightfield, if should be centered.
  95011. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  95012. var mesh = object;
  95013. var boundingInfo = mesh.getBoundingInfo();
  95014. //calculate the correct body position:
  95015. var rotationQuaternion = mesh.rotationQuaternion;
  95016. mesh.rotationQuaternion = this._tmpUnityRotation;
  95017. mesh.computeWorldMatrix(true);
  95018. //get original center with no rotation
  95019. var c = center.clone();
  95020. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  95021. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  95022. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  95023. mesh.setPreTransformMatrix(p);
  95024. mesh.computeWorldMatrix(true);
  95025. //calculate the translation
  95026. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  95027. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  95028. //add it inverted to the delta
  95029. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  95030. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  95031. //rotation is back
  95032. mesh.rotationQuaternion = rotationQuaternion;
  95033. mesh.setPreTransformMatrix(oldPivot);
  95034. mesh.computeWorldMatrix(true);
  95035. }
  95036. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  95037. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  95038. //this._tmpPosition.copyFrom(object.position);
  95039. }
  95040. impostor.setDeltaPosition(this._tmpDeltaPosition);
  95041. //Now update the impostor object
  95042. impostor.physicsBody.position.copy(this._tmpPosition);
  95043. impostor.physicsBody.quaternion.copy(quaternion);
  95044. };
  95045. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  95046. impostor.object.position.copyFrom(impostor.physicsBody.position);
  95047. if (impostor.object.rotationQuaternion) {
  95048. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  95049. }
  95050. };
  95051. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  95052. impostor.physicsBody.position.copy(newPosition);
  95053. impostor.physicsBody.quaternion.copy(newRotation);
  95054. };
  95055. CannonJSPlugin.prototype.isSupported = function () {
  95056. return this.BJSCANNON !== undefined;
  95057. };
  95058. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  95059. impostor.physicsBody.velocity.copy(velocity);
  95060. };
  95061. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  95062. impostor.physicsBody.angularVelocity.copy(velocity);
  95063. };
  95064. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  95065. var v = impostor.physicsBody.velocity;
  95066. if (!v) {
  95067. return null;
  95068. }
  95069. return new BABYLON.Vector3(v.x, v.y, v.z);
  95070. };
  95071. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  95072. var v = impostor.physicsBody.angularVelocity;
  95073. if (!v) {
  95074. return null;
  95075. }
  95076. return new BABYLON.Vector3(v.x, v.y, v.z);
  95077. };
  95078. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  95079. impostor.physicsBody.mass = mass;
  95080. impostor.physicsBody.updateMassProperties();
  95081. };
  95082. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  95083. return impostor.physicsBody.mass;
  95084. };
  95085. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  95086. return impostor.physicsBody.material.friction;
  95087. };
  95088. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  95089. impostor.physicsBody.material.friction = friction;
  95090. };
  95091. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  95092. return impostor.physicsBody.material.restitution;
  95093. };
  95094. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  95095. impostor.physicsBody.material.restitution = restitution;
  95096. };
  95097. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  95098. impostor.physicsBody.sleep();
  95099. };
  95100. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  95101. impostor.physicsBody.wakeUp();
  95102. };
  95103. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  95104. joint.physicsJoint.distance = maxDistance;
  95105. };
  95106. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  95107. // if (!motorIndex) {
  95108. // joint.physicsJoint.enableMotor();
  95109. // }
  95110. // }
  95111. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  95112. // if (!motorIndex) {
  95113. // joint.physicsJoint.disableMotor();
  95114. // }
  95115. // }
  95116. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  95117. if (!motorIndex) {
  95118. joint.physicsJoint.enableMotor();
  95119. joint.physicsJoint.setMotorSpeed(speed);
  95120. if (maxForce) {
  95121. this.setLimit(joint, maxForce);
  95122. }
  95123. }
  95124. };
  95125. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  95126. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  95127. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  95128. };
  95129. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  95130. var body = impostor.physicsBody;
  95131. mesh.position.x = body.position.x;
  95132. mesh.position.y = body.position.y;
  95133. mesh.position.z = body.position.z;
  95134. if (mesh.rotationQuaternion) {
  95135. mesh.rotationQuaternion.x = body.quaternion.x;
  95136. mesh.rotationQuaternion.y = body.quaternion.y;
  95137. mesh.rotationQuaternion.z = body.quaternion.z;
  95138. mesh.rotationQuaternion.w = body.quaternion.w;
  95139. }
  95140. };
  95141. CannonJSPlugin.prototype.getRadius = function (impostor) {
  95142. var shape = impostor.physicsBody.shapes[0];
  95143. return shape.boundingSphereRadius;
  95144. };
  95145. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  95146. var shape = impostor.physicsBody.shapes[0];
  95147. result.x = shape.halfExtents.x * 2;
  95148. result.y = shape.halfExtents.y * 2;
  95149. result.z = shape.halfExtents.z * 2;
  95150. };
  95151. CannonJSPlugin.prototype.dispose = function () {
  95152. };
  95153. CannonJSPlugin.prototype._extendNamespace = function () {
  95154. //this will force cannon to execute at least one step when using interpolation
  95155. var step_tmp1 = new this.BJSCANNON.Vec3();
  95156. var Engine = this.BJSCANNON;
  95157. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  95158. maxSubSteps = maxSubSteps || 10;
  95159. timeSinceLastCalled = timeSinceLastCalled || 0;
  95160. if (timeSinceLastCalled === 0) {
  95161. this.internalStep(dt);
  95162. this.time += dt;
  95163. }
  95164. else {
  95165. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  95166. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  95167. var t0 = performance.now();
  95168. for (var i = 0; i !== internalSteps; i++) {
  95169. this.internalStep(dt);
  95170. if (performance.now() - t0 > dt * 1000) {
  95171. break;
  95172. }
  95173. }
  95174. this.time += timeSinceLastCalled;
  95175. var h = this.time % dt;
  95176. var h_div_dt = h / dt;
  95177. var interpvelo = step_tmp1;
  95178. var bodies = this.bodies;
  95179. for (var j = 0; j !== bodies.length; j++) {
  95180. var b = bodies[j];
  95181. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  95182. b.position.vsub(b.previousPosition, interpvelo);
  95183. interpvelo.scale(h_div_dt, interpvelo);
  95184. b.position.vadd(interpvelo, b.interpolatedPosition);
  95185. }
  95186. else {
  95187. b.interpolatedPosition.copy(b.position);
  95188. b.interpolatedQuaternion.copy(b.quaternion);
  95189. }
  95190. }
  95191. }
  95192. };
  95193. };
  95194. return CannonJSPlugin;
  95195. }());
  95196. BABYLON.CannonJSPlugin = CannonJSPlugin;
  95197. })(BABYLON || (BABYLON = {}));
  95198. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  95199. var BABYLON;
  95200. (function (BABYLON) {
  95201. /** @hidden */
  95202. var OimoJSPlugin = /** @class */ (function () {
  95203. function OimoJSPlugin(iterations) {
  95204. this.name = "OimoJSPlugin";
  95205. this._tmpImpostorsArray = [];
  95206. this._tmpPositionVector = BABYLON.Vector3.Zero();
  95207. this.BJSOIMO = OIMO;
  95208. this.world = new this.BJSOIMO.World({
  95209. iterations: iterations
  95210. });
  95211. this.world.clear();
  95212. }
  95213. OimoJSPlugin.prototype.setGravity = function (gravity) {
  95214. this.world.gravity.copy(gravity);
  95215. };
  95216. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  95217. this.world.timeStep = timeStep;
  95218. };
  95219. OimoJSPlugin.prototype.getTimeStep = function () {
  95220. return this.world.timeStep;
  95221. };
  95222. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  95223. var _this = this;
  95224. impostors.forEach(function (impostor) {
  95225. impostor.beforeStep();
  95226. });
  95227. this.world.step();
  95228. impostors.forEach(function (impostor) {
  95229. impostor.afterStep();
  95230. //update the ordered impostors array
  95231. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  95232. });
  95233. //check for collisions
  95234. var contact = this.world.contacts;
  95235. while (contact !== null) {
  95236. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  95237. contact = contact.next;
  95238. continue;
  95239. }
  95240. //is this body colliding with any other? get the impostor
  95241. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  95242. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  95243. if (!mainImpostor || !collidingImpostor) {
  95244. contact = contact.next;
  95245. continue;
  95246. }
  95247. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  95248. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  95249. contact = contact.next;
  95250. }
  95251. };
  95252. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  95253. var mass = impostor.physicsBody.mass;
  95254. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  95255. };
  95256. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  95257. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  95258. this.applyImpulse(impostor, force, contactPoint);
  95259. };
  95260. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  95261. var _this = this;
  95262. //parent-child relationship. Does this impostor has a parent impostor?
  95263. if (impostor.parent) {
  95264. if (impostor.physicsBody) {
  95265. this.removePhysicsBody(impostor);
  95266. //TODO is that needed?
  95267. impostor.forceUpdate();
  95268. }
  95269. return;
  95270. }
  95271. if (impostor.isBodyInitRequired()) {
  95272. var bodyConfig = {
  95273. name: impostor.uniqueId,
  95274. //Oimo must have mass, also for static objects.
  95275. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  95276. size: [],
  95277. type: [],
  95278. pos: [],
  95279. posShape: [],
  95280. rot: [],
  95281. rotShape: [],
  95282. move: impostor.getParam("mass") !== 0,
  95283. density: impostor.getParam("mass"),
  95284. friction: impostor.getParam("friction"),
  95285. restitution: impostor.getParam("restitution"),
  95286. //Supporting older versions of Oimo
  95287. world: this.world
  95288. };
  95289. var impostors = [impostor];
  95290. var addToArray = function (parent) {
  95291. if (!parent.getChildMeshes)
  95292. return;
  95293. parent.getChildMeshes().forEach(function (m) {
  95294. if (m.physicsImpostor) {
  95295. impostors.push(m.physicsImpostor);
  95296. //m.physicsImpostor._init();
  95297. }
  95298. });
  95299. };
  95300. addToArray(impostor.object);
  95301. var checkWithEpsilon_1 = function (value) {
  95302. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  95303. };
  95304. var globalQuaternion_1 = new BABYLON.Quaternion();
  95305. impostors.forEach(function (i) {
  95306. if (!i.object.rotationQuaternion) {
  95307. return;
  95308. }
  95309. //get the correct bounding box
  95310. var oldQuaternion = i.object.rotationQuaternion;
  95311. globalQuaternion_1 = oldQuaternion.clone();
  95312. var rot = oldQuaternion.toEulerAngles();
  95313. var extendSize = i.getObjectExtendSize();
  95314. var radToDeg = 57.295779513082320876;
  95315. if (i === impostor) {
  95316. var center = impostor.getObjectCenter();
  95317. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  95318. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  95319. //Can also use Array.prototype.push.apply
  95320. bodyConfig.pos.push(center.x);
  95321. bodyConfig.pos.push(center.y);
  95322. bodyConfig.pos.push(center.z);
  95323. bodyConfig.posShape.push(0, 0, 0);
  95324. //tmp solution
  95325. bodyConfig.rot.push(0);
  95326. bodyConfig.rot.push(0);
  95327. bodyConfig.rot.push(0);
  95328. bodyConfig.rotShape.push(0, 0, 0);
  95329. }
  95330. else {
  95331. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  95332. bodyConfig.posShape.push(localPosition.x);
  95333. bodyConfig.posShape.push(localPosition.y);
  95334. bodyConfig.posShape.push(localPosition.z);
  95335. bodyConfig.pos.push(0, 0, 0);
  95336. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  95337. bodyConfig.rot.push(0);
  95338. bodyConfig.rot.push(0);
  95339. bodyConfig.rot.push(0);
  95340. bodyConfig.rotShape.push(rot.x * radToDeg);
  95341. bodyConfig.rotShape.push(rot.y * radToDeg);
  95342. bodyConfig.rotShape.push(rot.z * radToDeg);
  95343. }
  95344. // register mesh
  95345. switch (i.type) {
  95346. case BABYLON.PhysicsImpostor.ParticleImpostor:
  95347. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  95348. case BABYLON.PhysicsImpostor.SphereImpostor:
  95349. var radiusX = extendSize.x;
  95350. var radiusY = extendSize.y;
  95351. var radiusZ = extendSize.z;
  95352. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  95353. bodyConfig.type.push('sphere');
  95354. //due to the way oimo works with compounds, add 3 times
  95355. bodyConfig.size.push(size);
  95356. bodyConfig.size.push(size);
  95357. bodyConfig.size.push(size);
  95358. break;
  95359. case BABYLON.PhysicsImpostor.CylinderImpostor:
  95360. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  95361. var sizeY = checkWithEpsilon_1(extendSize.y);
  95362. bodyConfig.type.push('cylinder');
  95363. bodyConfig.size.push(sizeX);
  95364. bodyConfig.size.push(sizeY);
  95365. //due to the way oimo works with compounds, add one more value.
  95366. bodyConfig.size.push(sizeY);
  95367. break;
  95368. case BABYLON.PhysicsImpostor.PlaneImpostor:
  95369. case BABYLON.PhysicsImpostor.BoxImpostor:
  95370. default:
  95371. var sizeX = checkWithEpsilon_1(extendSize.x);
  95372. var sizeY = checkWithEpsilon_1(extendSize.y);
  95373. var sizeZ = checkWithEpsilon_1(extendSize.z);
  95374. bodyConfig.type.push('box');
  95375. //if (i === impostor) {
  95376. bodyConfig.size.push(sizeX);
  95377. bodyConfig.size.push(sizeY);
  95378. bodyConfig.size.push(sizeZ);
  95379. //} else {
  95380. // bodyConfig.size.push(0,0,0);
  95381. //}
  95382. break;
  95383. }
  95384. //actually not needed, but hey...
  95385. i.object.rotationQuaternion = oldQuaternion;
  95386. });
  95387. impostor.physicsBody = this.world.add(bodyConfig);
  95388. // set the quaternion, ignoring the previously defined (euler) rotation
  95389. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  95390. // update with delta 0, so the body will reveive the new rotation.
  95391. impostor.physicsBody.updatePosition(0);
  95392. }
  95393. else {
  95394. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  95395. }
  95396. impostor.setDeltaPosition(this._tmpPositionVector);
  95397. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  95398. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  95399. };
  95400. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  95401. //impostor.physicsBody.dispose();
  95402. //Same as : (older oimo versions)
  95403. this.world.removeRigidBody(impostor.physicsBody);
  95404. };
  95405. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  95406. var mainBody = impostorJoint.mainImpostor.physicsBody;
  95407. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  95408. if (!mainBody || !connectedBody) {
  95409. return;
  95410. }
  95411. var jointData = impostorJoint.joint.jointData;
  95412. var options = jointData.nativeParams || {};
  95413. var type;
  95414. var nativeJointData = {
  95415. body1: mainBody,
  95416. body2: connectedBody,
  95417. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  95418. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  95419. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  95420. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  95421. min: options.min,
  95422. max: options.max,
  95423. collision: options.collision || jointData.collision,
  95424. spring: options.spring,
  95425. //supporting older version of Oimo
  95426. world: this.world
  95427. };
  95428. switch (impostorJoint.joint.type) {
  95429. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  95430. type = "jointBall";
  95431. break;
  95432. case BABYLON.PhysicsJoint.SpringJoint:
  95433. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  95434. var springData = jointData;
  95435. nativeJointData.min = springData.length || nativeJointData.min;
  95436. //Max should also be set, just make sure it is at least min
  95437. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  95438. case BABYLON.PhysicsJoint.DistanceJoint:
  95439. type = "jointDistance";
  95440. nativeJointData.max = jointData.maxDistance;
  95441. break;
  95442. case BABYLON.PhysicsJoint.PrismaticJoint:
  95443. type = "jointPrisme";
  95444. break;
  95445. case BABYLON.PhysicsJoint.SliderJoint:
  95446. type = "jointSlide";
  95447. break;
  95448. case BABYLON.PhysicsJoint.WheelJoint:
  95449. type = "jointWheel";
  95450. break;
  95451. case BABYLON.PhysicsJoint.HingeJoint:
  95452. default:
  95453. type = "jointHinge";
  95454. break;
  95455. }
  95456. nativeJointData.type = type;
  95457. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  95458. };
  95459. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  95460. //Bug in Oimo prevents us from disposing a joint in the playground
  95461. //joint.joint.physicsJoint.dispose();
  95462. //So we will bruteforce it!
  95463. try {
  95464. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  95465. }
  95466. catch (e) {
  95467. BABYLON.Tools.Warn(e);
  95468. }
  95469. };
  95470. OimoJSPlugin.prototype.isSupported = function () {
  95471. return this.BJSOIMO !== undefined;
  95472. };
  95473. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  95474. if (!impostor.physicsBody.sleeping) {
  95475. //TODO check that
  95476. /*if (impostor.physicsBody.shapes.next) {
  95477. var parentShape = this._getLastShape(impostor.physicsBody);
  95478. impostor.object.position.copyFrom(parentShape.position);
  95479. console.log(parentShape.position);
  95480. } else {*/
  95481. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  95482. //}
  95483. if (impostor.object.rotationQuaternion) {
  95484. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  95485. }
  95486. }
  95487. };
  95488. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  95489. var body = impostor.physicsBody;
  95490. body.position.copy(newPosition);
  95491. body.orientation.copy(newRotation);
  95492. body.syncShapes();
  95493. body.awake();
  95494. };
  95495. /*private _getLastShape(body: any): any {
  95496. var lastShape = body.shapes;
  95497. while (lastShape.next) {
  95498. lastShape = lastShape.next;
  95499. }
  95500. return lastShape;
  95501. }*/
  95502. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  95503. impostor.physicsBody.linearVelocity.copy(velocity);
  95504. };
  95505. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  95506. impostor.physicsBody.angularVelocity.copy(velocity);
  95507. };
  95508. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  95509. var v = impostor.physicsBody.linearVelocity;
  95510. if (!v) {
  95511. return null;
  95512. }
  95513. return new BABYLON.Vector3(v.x, v.y, v.z);
  95514. };
  95515. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  95516. var v = impostor.physicsBody.angularVelocity;
  95517. if (!v) {
  95518. return null;
  95519. }
  95520. return new BABYLON.Vector3(v.x, v.y, v.z);
  95521. };
  95522. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  95523. var staticBody = mass === 0;
  95524. //this will actually set the body's density and not its mass.
  95525. //But this is how oimo treats the mass variable.
  95526. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  95527. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  95528. };
  95529. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  95530. return impostor.physicsBody.shapes.density;
  95531. };
  95532. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  95533. return impostor.physicsBody.shapes.friction;
  95534. };
  95535. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  95536. impostor.physicsBody.shapes.friction = friction;
  95537. };
  95538. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  95539. return impostor.physicsBody.shapes.restitution;
  95540. };
  95541. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  95542. impostor.physicsBody.shapes.restitution = restitution;
  95543. };
  95544. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  95545. impostor.physicsBody.sleep();
  95546. };
  95547. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  95548. impostor.physicsBody.awake();
  95549. };
  95550. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  95551. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  95552. if (minDistance !== void 0) {
  95553. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  95554. }
  95555. };
  95556. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  95557. //TODO separate rotational and transational motors.
  95558. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  95559. if (motor) {
  95560. motor.setMotor(speed, maxForce);
  95561. }
  95562. };
  95563. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  95564. //TODO separate rotational and transational motors.
  95565. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  95566. if (motor) {
  95567. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  95568. }
  95569. };
  95570. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  95571. var body = impostor.physicsBody;
  95572. mesh.position.x = body.position.x;
  95573. mesh.position.y = body.position.y;
  95574. mesh.position.z = body.position.z;
  95575. if (mesh.rotationQuaternion) {
  95576. mesh.rotationQuaternion.x = body.orientation.x;
  95577. mesh.rotationQuaternion.y = body.orientation.y;
  95578. mesh.rotationQuaternion.z = body.orientation.z;
  95579. mesh.rotationQuaternion.w = body.orientation.s;
  95580. }
  95581. };
  95582. OimoJSPlugin.prototype.getRadius = function (impostor) {
  95583. return impostor.physicsBody.shapes.radius;
  95584. };
  95585. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  95586. var shape = impostor.physicsBody.shapes;
  95587. result.x = shape.halfWidth * 2;
  95588. result.y = shape.halfHeight * 2;
  95589. result.z = shape.halfDepth * 2;
  95590. };
  95591. OimoJSPlugin.prototype.dispose = function () {
  95592. this.world.clear();
  95593. };
  95594. return OimoJSPlugin;
  95595. }());
  95596. BABYLON.OimoJSPlugin = OimoJSPlugin;
  95597. })(BABYLON || (BABYLON = {}));
  95598. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  95599. var BABYLON;
  95600. (function (BABYLON) {
  95601. /**
  95602. * Gets the current physics engine
  95603. * @returns a IPhysicsEngine or null if none attached
  95604. */
  95605. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  95606. return this._physicsEngine;
  95607. };
  95608. /**
  95609. * Enables physics to the current scene
  95610. * @param gravity defines the scene's gravity for the physics engine
  95611. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  95612. * @return a boolean indicating if the physics engine was initialized
  95613. */
  95614. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  95615. if (gravity === void 0) { gravity = null; }
  95616. if (this._physicsEngine) {
  95617. return true;
  95618. }
  95619. // Register the component to the scene
  95620. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  95621. if (!component) {
  95622. component = new PhysicsEngineSceneComponent(this);
  95623. this._addComponent(component);
  95624. }
  95625. try {
  95626. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  95627. return true;
  95628. }
  95629. catch (e) {
  95630. BABYLON.Tools.Error(e.message);
  95631. return false;
  95632. }
  95633. };
  95634. /**
  95635. * Disables and disposes the physics engine associated with the scene
  95636. */
  95637. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  95638. if (!this._physicsEngine) {
  95639. return;
  95640. }
  95641. this._physicsEngine.dispose();
  95642. this._physicsEngine = null;
  95643. };
  95644. /**
  95645. * Gets a boolean indicating if there is an active physics engine
  95646. * @returns a boolean indicating if there is an active physics engine
  95647. */
  95648. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  95649. return this._physicsEngine !== undefined;
  95650. };
  95651. /**
  95652. * Deletes a physics compound impostor
  95653. * @param compound defines the compound to delete
  95654. */
  95655. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  95656. var mesh = compound.parts[0].mesh;
  95657. if (mesh.physicsImpostor) {
  95658. mesh.physicsImpostor.dispose( /*true*/);
  95659. mesh.physicsImpostor = null;
  95660. }
  95661. };
  95662. /** @hidden */
  95663. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  95664. if (this._physicsEngine) {
  95665. this.onBeforePhysicsObservable.notifyObservers(this);
  95666. this._physicsEngine._step(step / 1000);
  95667. this.onAfterPhysicsObservable.notifyObservers(this);
  95668. }
  95669. };
  95670. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  95671. get: function () {
  95672. return this._physicsImpostor;
  95673. },
  95674. set: function (value) {
  95675. var _this = this;
  95676. if (this._physicsImpostor === value) {
  95677. return;
  95678. }
  95679. if (this._disposePhysicsObserver) {
  95680. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  95681. }
  95682. this._physicsImpostor = value;
  95683. if (value) {
  95684. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  95685. // Physics
  95686. if (_this.physicsImpostor) {
  95687. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  95688. _this.physicsImpostor = null;
  95689. }
  95690. });
  95691. }
  95692. },
  95693. enumerable: true,
  95694. configurable: true
  95695. });
  95696. /**
  95697. * Gets the current physics impostor
  95698. * @see http://doc.babylonjs.com/features/physics_engine
  95699. * @returns a physics impostor or null
  95700. */
  95701. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  95702. return this.physicsImpostor;
  95703. };
  95704. /**
  95705. * Apply a physic impulse to the mesh
  95706. * @param force defines the force to apply
  95707. * @param contactPoint defines where to apply the force
  95708. * @returns the current mesh
  95709. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  95710. */
  95711. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  95712. if (!this.physicsImpostor) {
  95713. return this;
  95714. }
  95715. this.physicsImpostor.applyImpulse(force, contactPoint);
  95716. return this;
  95717. };
  95718. /**
  95719. * Creates a physic joint between two meshes
  95720. * @param otherMesh defines the other mesh to use
  95721. * @param pivot1 defines the pivot to use on this mesh
  95722. * @param pivot2 defines the pivot to use on the other mesh
  95723. * @param options defines additional options (can be plugin dependent)
  95724. * @returns the current mesh
  95725. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  95726. */
  95727. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  95728. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  95729. return this;
  95730. }
  95731. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  95732. mainPivot: pivot1,
  95733. connectedPivot: pivot2,
  95734. nativeParams: options
  95735. });
  95736. return this;
  95737. };
  95738. /**
  95739. * Defines the physics engine scene component responsible to manage a physics engine
  95740. */
  95741. var PhysicsEngineSceneComponent = /** @class */ (function () {
  95742. /**
  95743. * Creates a new instance of the component for the given scene
  95744. * @param scene Defines the scene to register the component in
  95745. */
  95746. function PhysicsEngineSceneComponent(scene) {
  95747. var _this = this;
  95748. /**
  95749. * The component name helpful to identify the component in the list of scene components.
  95750. */
  95751. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  95752. this.scene = scene;
  95753. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  95754. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  95755. // Replace the function used to get the deterministic frame time
  95756. this.scene.getDeterministicFrameTime = function () {
  95757. if (_this.scene._physicsEngine) {
  95758. return _this.scene._physicsEngine.getTimeStep() * 1000;
  95759. }
  95760. return 1000.0 / 60.0;
  95761. };
  95762. }
  95763. /**
  95764. * Registers the component in a given scene
  95765. */
  95766. PhysicsEngineSceneComponent.prototype.register = function () {
  95767. };
  95768. /**
  95769. * Rebuilds the elements related to this component in case of
  95770. * context lost for instance.
  95771. */
  95772. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  95773. // Nothing to do for this component
  95774. };
  95775. /**
  95776. * Disposes the component and the associated ressources
  95777. */
  95778. PhysicsEngineSceneComponent.prototype.dispose = function () {
  95779. this.scene.onBeforePhysicsObservable.clear();
  95780. this.scene.onAfterPhysicsObservable.clear();
  95781. if (this.scene._physicsEngine) {
  95782. this.scene.disablePhysicsEngine();
  95783. }
  95784. };
  95785. return PhysicsEngineSceneComponent;
  95786. }());
  95787. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  95788. })(BABYLON || (BABYLON = {}));
  95789. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  95790. var BABYLON;
  95791. (function (BABYLON) {
  95792. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  95793. // All values and structures referenced from:
  95794. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  95795. var DDS_MAGIC = 0x20534444;
  95796. var
  95797. //DDSD_CAPS = 0x1,
  95798. //DDSD_HEIGHT = 0x2,
  95799. //DDSD_WIDTH = 0x4,
  95800. //DDSD_PITCH = 0x8,
  95801. //DDSD_PIXELFORMAT = 0x1000,
  95802. DDSD_MIPMAPCOUNT = 0x20000;
  95803. //DDSD_LINEARSIZE = 0x80000,
  95804. //DDSD_DEPTH = 0x800000;
  95805. // var DDSCAPS_COMPLEX = 0x8,
  95806. // DDSCAPS_MIPMAP = 0x400000,
  95807. // DDSCAPS_TEXTURE = 0x1000;
  95808. var DDSCAPS2_CUBEMAP = 0x200;
  95809. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  95810. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  95811. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  95812. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  95813. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  95814. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  95815. // DDSCAPS2_VOLUME = 0x200000;
  95816. var
  95817. //DDPF_ALPHAPIXELS = 0x1,
  95818. //DDPF_ALPHA = 0x2,
  95819. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  95820. //DDPF_YUV = 0x200,
  95821. DDPF_LUMINANCE = 0x20000;
  95822. function FourCCToInt32(value) {
  95823. return value.charCodeAt(0) +
  95824. (value.charCodeAt(1) << 8) +
  95825. (value.charCodeAt(2) << 16) +
  95826. (value.charCodeAt(3) << 24);
  95827. }
  95828. function Int32ToFourCC(value) {
  95829. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  95830. }
  95831. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  95832. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  95833. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  95834. var FOURCC_DX10 = FourCCToInt32("DX10");
  95835. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  95836. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  95837. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  95838. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  95839. var headerLengthInt = 31; // The header length in 32 bit ints
  95840. // Offsets into the header array
  95841. var off_magic = 0;
  95842. var off_size = 1;
  95843. var off_flags = 2;
  95844. var off_height = 3;
  95845. var off_width = 4;
  95846. var off_mipmapCount = 7;
  95847. var off_pfFlags = 20;
  95848. var off_pfFourCC = 21;
  95849. var off_RGBbpp = 22;
  95850. var off_RMask = 23;
  95851. var off_GMask = 24;
  95852. var off_BMask = 25;
  95853. var off_AMask = 26;
  95854. // var off_caps1 = 27;
  95855. var off_caps2 = 28;
  95856. // var off_caps3 = 29;
  95857. // var off_caps4 = 30;
  95858. var off_dxgiFormat = 32;
  95859. ;
  95860. /**
  95861. * Class used to provide DDS decompression tools
  95862. */
  95863. var DDSTools = /** @class */ (function () {
  95864. function DDSTools() {
  95865. }
  95866. /**
  95867. * Gets DDS information from an array buffer
  95868. * @param arrayBuffer defines the array buffer to read data from
  95869. * @returns the DDS information
  95870. */
  95871. DDSTools.GetDDSInfo = function (arrayBuffer) {
  95872. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  95873. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  95874. var mipmapCount = 1;
  95875. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  95876. mipmapCount = Math.max(1, header[off_mipmapCount]);
  95877. }
  95878. var fourCC = header[off_pfFourCC];
  95879. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  95880. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95881. switch (fourCC) {
  95882. case FOURCC_D3DFMT_R16G16B16A16F:
  95883. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95884. break;
  95885. case FOURCC_D3DFMT_R32G32B32A32F:
  95886. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  95887. break;
  95888. case FOURCC_DX10:
  95889. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  95890. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95891. break;
  95892. }
  95893. }
  95894. return {
  95895. width: header[off_width],
  95896. height: header[off_height],
  95897. mipmapCount: mipmapCount,
  95898. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  95899. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  95900. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  95901. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  95902. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  95903. dxgiFormat: dxgiFormat,
  95904. textureType: textureType
  95905. };
  95906. };
  95907. DDSTools._ToHalfFloat = function (value) {
  95908. if (!DDSTools._FloatView) {
  95909. DDSTools._FloatView = new Float32Array(1);
  95910. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  95911. }
  95912. DDSTools._FloatView[0] = value;
  95913. var x = DDSTools._Int32View[0];
  95914. var bits = (x >> 16) & 0x8000; /* Get the sign */
  95915. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  95916. var e = (x >> 23) & 0xff; /* Using int is faster here */
  95917. /* If zero, or denormal, or exponent underflows too much for a denormal
  95918. * half, return signed zero. */
  95919. if (e < 103) {
  95920. return bits;
  95921. }
  95922. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  95923. if (e > 142) {
  95924. bits |= 0x7c00;
  95925. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  95926. * not Inf, so make sure we set one mantissa bit too. */
  95927. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  95928. return bits;
  95929. }
  95930. /* If exponent underflows but not too much, return a denormal */
  95931. if (e < 113) {
  95932. m |= 0x0800;
  95933. /* Extra rounding may overflow and set mantissa to 0 and exponent
  95934. * to 1, which is OK. */
  95935. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  95936. return bits;
  95937. }
  95938. bits |= ((e - 112) << 10) | (m >> 1);
  95939. bits += m & 1;
  95940. return bits;
  95941. };
  95942. DDSTools._FromHalfFloat = function (value) {
  95943. var s = (value & 0x8000) >> 15;
  95944. var e = (value & 0x7C00) >> 10;
  95945. var f = value & 0x03FF;
  95946. if (e === 0) {
  95947. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  95948. }
  95949. else if (e == 0x1F) {
  95950. return f ? NaN : ((s ? -1 : 1) * Infinity);
  95951. }
  95952. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  95953. };
  95954. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95955. var destArray = new Float32Array(dataLength);
  95956. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  95957. var index = 0;
  95958. for (var y = 0; y < height; y++) {
  95959. for (var x = 0; x < width; x++) {
  95960. var srcPos = (x + y * width) * 4;
  95961. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  95962. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  95963. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  95964. if (DDSTools.StoreLODInAlphaChannel) {
  95965. destArray[index + 3] = lod;
  95966. }
  95967. else {
  95968. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  95969. }
  95970. index += 4;
  95971. }
  95972. }
  95973. return destArray;
  95974. };
  95975. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95976. if (DDSTools.StoreLODInAlphaChannel) {
  95977. var destArray = new Uint16Array(dataLength);
  95978. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  95979. var index = 0;
  95980. for (var y = 0; y < height; y++) {
  95981. for (var x = 0; x < width; x++) {
  95982. var srcPos = (x + y * width) * 4;
  95983. destArray[index] = srcData[srcPos];
  95984. destArray[index + 1] = srcData[srcPos + 1];
  95985. destArray[index + 2] = srcData[srcPos + 2];
  95986. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  95987. index += 4;
  95988. }
  95989. }
  95990. return destArray;
  95991. }
  95992. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  95993. };
  95994. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  95995. if (DDSTools.StoreLODInAlphaChannel) {
  95996. var destArray = new Float32Array(dataLength);
  95997. var srcData = new Float32Array(arrayBuffer, dataOffset);
  95998. var index = 0;
  95999. for (var y = 0; y < height; y++) {
  96000. for (var x = 0; x < width; x++) {
  96001. var srcPos = (x + y * width) * 4;
  96002. destArray[index] = srcData[srcPos];
  96003. destArray[index + 1] = srcData[srcPos + 1];
  96004. destArray[index + 2] = srcData[srcPos + 2];
  96005. destArray[index + 3] = lod;
  96006. index += 4;
  96007. }
  96008. }
  96009. return destArray;
  96010. }
  96011. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  96012. };
  96013. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  96014. var destArray = new Uint8Array(dataLength);
  96015. var srcData = new Float32Array(arrayBuffer, dataOffset);
  96016. var index = 0;
  96017. for (var y = 0; y < height; y++) {
  96018. for (var x = 0; x < width; x++) {
  96019. var srcPos = (x + y * width) * 4;
  96020. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  96021. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  96022. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  96023. if (DDSTools.StoreLODInAlphaChannel) {
  96024. destArray[index + 3] = lod;
  96025. }
  96026. else {
  96027. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  96028. }
  96029. index += 4;
  96030. }
  96031. }
  96032. return destArray;
  96033. };
  96034. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  96035. var destArray = new Uint8Array(dataLength);
  96036. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  96037. var index = 0;
  96038. for (var y = 0; y < height; y++) {
  96039. for (var x = 0; x < width; x++) {
  96040. var srcPos = (x + y * width) * 4;
  96041. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  96042. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  96043. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  96044. if (DDSTools.StoreLODInAlphaChannel) {
  96045. destArray[index + 3] = lod;
  96046. }
  96047. else {
  96048. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  96049. }
  96050. index += 4;
  96051. }
  96052. }
  96053. return destArray;
  96054. };
  96055. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  96056. var byteArray = new Uint8Array(dataLength);
  96057. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  96058. var index = 0;
  96059. for (var y = 0; y < height; y++) {
  96060. for (var x = 0; x < width; x++) {
  96061. var srcPos = (x + y * width) * 4;
  96062. byteArray[index] = srcData[srcPos + rOffset];
  96063. byteArray[index + 1] = srcData[srcPos + gOffset];
  96064. byteArray[index + 2] = srcData[srcPos + bOffset];
  96065. byteArray[index + 3] = srcData[srcPos + aOffset];
  96066. index += 4;
  96067. }
  96068. }
  96069. return byteArray;
  96070. };
  96071. DDSTools._ExtractLongWordOrder = function (value) {
  96072. if (value === 0 || value === 255 || value === -16777216) {
  96073. return 0;
  96074. }
  96075. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  96076. };
  96077. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  96078. var byteArray = new Uint8Array(dataLength);
  96079. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  96080. var index = 0;
  96081. for (var y = 0; y < height; y++) {
  96082. for (var x = 0; x < width; x++) {
  96083. var srcPos = (x + y * width) * 3;
  96084. byteArray[index] = srcData[srcPos + rOffset];
  96085. byteArray[index + 1] = srcData[srcPos + gOffset];
  96086. byteArray[index + 2] = srcData[srcPos + bOffset];
  96087. index += 3;
  96088. }
  96089. }
  96090. return byteArray;
  96091. };
  96092. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  96093. var byteArray = new Uint8Array(dataLength);
  96094. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  96095. var index = 0;
  96096. for (var y = 0; y < height; y++) {
  96097. for (var x = 0; x < width; x++) {
  96098. var srcPos = (x + y * width);
  96099. byteArray[index] = srcData[srcPos];
  96100. index++;
  96101. }
  96102. }
  96103. return byteArray;
  96104. };
  96105. /**
  96106. * Uploads DDS Levels to a Babylon Texture
  96107. * @hidden
  96108. */
  96109. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  96110. if (lodIndex === void 0) { lodIndex = -1; }
  96111. var sphericalPolynomialFaces = null;
  96112. if (info.sphericalPolynomial) {
  96113. sphericalPolynomialFaces = new Array();
  96114. }
  96115. var ext = engine.getCaps().s3tc;
  96116. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  96117. var fourCC, width, height, dataLength = 0, dataOffset;
  96118. var byteArray, mipmapCount, mip;
  96119. var internalCompressedFormat = 0;
  96120. var blockBytes = 1;
  96121. if (header[off_magic] !== DDS_MAGIC) {
  96122. BABYLON.Tools.Error("Invalid magic number in DDS header");
  96123. return;
  96124. }
  96125. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  96126. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  96127. return;
  96128. }
  96129. if (info.isCompressed && !ext) {
  96130. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  96131. return;
  96132. }
  96133. var bpp = header[off_RGBbpp];
  96134. dataOffset = header[off_size] + 4;
  96135. var computeFormats = false;
  96136. if (info.isFourCC) {
  96137. fourCC = header[off_pfFourCC];
  96138. switch (fourCC) {
  96139. case FOURCC_DXT1:
  96140. blockBytes = 8;
  96141. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  96142. break;
  96143. case FOURCC_DXT3:
  96144. blockBytes = 16;
  96145. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  96146. break;
  96147. case FOURCC_DXT5:
  96148. blockBytes = 16;
  96149. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  96150. break;
  96151. case FOURCC_D3DFMT_R16G16B16A16F:
  96152. computeFormats = true;
  96153. break;
  96154. case FOURCC_D3DFMT_R32G32B32A32F:
  96155. computeFormats = true;
  96156. break;
  96157. case FOURCC_DX10:
  96158. // There is an additionnal header so dataOffset need to be changed
  96159. dataOffset += 5 * 4; // 5 uints
  96160. var supported = false;
  96161. switch (info.dxgiFormat) {
  96162. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  96163. computeFormats = true;
  96164. supported = true;
  96165. break;
  96166. case DXGI_FORMAT_B8G8R8X8_UNORM:
  96167. info.isRGB = true;
  96168. info.isFourCC = false;
  96169. bpp = 32;
  96170. supported = true;
  96171. break;
  96172. }
  96173. if (supported) {
  96174. break;
  96175. }
  96176. default:
  96177. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  96178. return;
  96179. }
  96180. }
  96181. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  96182. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  96183. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  96184. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  96185. if (computeFormats) {
  96186. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  96187. }
  96188. mipmapCount = 1;
  96189. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  96190. mipmapCount = Math.max(1, header[off_mipmapCount]);
  96191. }
  96192. for (var face = 0; face < faces; face++) {
  96193. width = header[off_width];
  96194. height = header[off_height];
  96195. for (mip = 0; mip < mipmapCount; ++mip) {
  96196. if (lodIndex === -1 || lodIndex === mip) {
  96197. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  96198. var i = (lodIndex === -1) ? mip : 0;
  96199. if (!info.isCompressed && info.isFourCC) {
  96200. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  96201. dataLength = width * height * 4;
  96202. var floatArray = null;
  96203. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  96204. if (bpp === 128) {
  96205. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  96206. if (sphericalPolynomialFaces && i == 0) {
  96207. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  96208. }
  96209. }
  96210. else if (bpp === 64) {
  96211. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  96212. if (sphericalPolynomialFaces && i == 0) {
  96213. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  96214. }
  96215. }
  96216. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96217. }
  96218. else {
  96219. if (bpp === 128) {
  96220. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  96221. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  96222. if (sphericalPolynomialFaces && i == 0) {
  96223. sphericalPolynomialFaces.push(floatArray);
  96224. }
  96225. }
  96226. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  96227. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  96228. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  96229. if (sphericalPolynomialFaces && i == 0) {
  96230. sphericalPolynomialFaces.push(floatArray);
  96231. }
  96232. }
  96233. else { // 64
  96234. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96235. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  96236. if (sphericalPolynomialFaces && i == 0) {
  96237. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  96238. }
  96239. }
  96240. }
  96241. if (floatArray) {
  96242. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  96243. }
  96244. }
  96245. else if (info.isRGB) {
  96246. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96247. if (bpp === 24) {
  96248. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  96249. dataLength = width * height * 3;
  96250. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  96251. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  96252. }
  96253. else { // 32
  96254. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  96255. dataLength = width * height * 4;
  96256. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  96257. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  96258. }
  96259. }
  96260. else if (info.isLuminance) {
  96261. var unpackAlignment = engine._getUnpackAlignement();
  96262. var unpaddedRowSize = width;
  96263. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  96264. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  96265. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  96266. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  96267. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96268. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  96269. }
  96270. else {
  96271. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  96272. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  96273. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96274. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  96275. }
  96276. }
  96277. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  96278. width *= 0.5;
  96279. height *= 0.5;
  96280. width = Math.max(1.0, width);
  96281. height = Math.max(1.0, height);
  96282. }
  96283. if (currentFace !== undefined) {
  96284. // Loading a single face
  96285. break;
  96286. }
  96287. }
  96288. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  96289. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  96290. size: header[off_width],
  96291. right: sphericalPolynomialFaces[0],
  96292. left: sphericalPolynomialFaces[1],
  96293. up: sphericalPolynomialFaces[2],
  96294. down: sphericalPolynomialFaces[3],
  96295. front: sphericalPolynomialFaces[4],
  96296. back: sphericalPolynomialFaces[5],
  96297. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  96298. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  96299. gammaSpace: false,
  96300. });
  96301. }
  96302. else {
  96303. info.sphericalPolynomial = undefined;
  96304. }
  96305. };
  96306. /**
  96307. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  96308. */
  96309. DDSTools.StoreLODInAlphaChannel = false;
  96310. return DDSTools;
  96311. }());
  96312. BABYLON.DDSTools = DDSTools;
  96313. })(BABYLON || (BABYLON = {}));
  96314. //# sourceMappingURL=babylon.dds.js.map
  96315. var BABYLON;
  96316. (function (BABYLON) {
  96317. /**
  96318. * Implementation of the DDS Texture Loader.
  96319. */
  96320. var DDSTextureLoader = /** @class */ (function () {
  96321. function DDSTextureLoader() {
  96322. /**
  96323. * Defines wether the loader supports cascade loading the different faces.
  96324. */
  96325. this.supportCascades = true;
  96326. }
  96327. /**
  96328. * This returns if the loader support the current file information.
  96329. * @param extension defines the file extension of the file being loaded
  96330. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96331. * @param fallback defines the fallback internal texture if any
  96332. * @param isBase64 defines whether the texture is encoded as a base64
  96333. * @param isBuffer defines whether the texture data are stored as a buffer
  96334. * @returns true if the loader can load the specified file
  96335. */
  96336. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  96337. return extension.indexOf(".dds") === 0;
  96338. };
  96339. /**
  96340. * Transform the url before loading if required.
  96341. * @param rootUrl the url of the texture
  96342. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96343. * @returns the transformed texture
  96344. */
  96345. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  96346. return rootUrl;
  96347. };
  96348. /**
  96349. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  96350. * @param rootUrl the url of the texture
  96351. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96352. * @returns the fallback texture
  96353. */
  96354. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  96355. return null;
  96356. };
  96357. /**
  96358. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  96359. * @param data contains the texture data
  96360. * @param texture defines the BabylonJS internal texture
  96361. * @param createPolynomials will be true if polynomials have been requested
  96362. * @param onLoad defines the callback to trigger once the texture is ready
  96363. * @param onError defines the callback to trigger in case of error
  96364. */
  96365. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  96366. var engine = texture.getEngine();
  96367. var info;
  96368. var loadMipmap = false;
  96369. if (Array.isArray(imgs)) {
  96370. for (var index = 0; index < imgs.length; index++) {
  96371. var data_1 = imgs[index];
  96372. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  96373. texture.width = info.width;
  96374. texture.height = info.height;
  96375. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  96376. engine._unpackFlipY(info.isCompressed);
  96377. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  96378. if (!info.isFourCC && info.mipmapCount === 1) {
  96379. engine.generateMipMapsForCubemap(texture);
  96380. }
  96381. }
  96382. }
  96383. else {
  96384. var data = imgs;
  96385. info = BABYLON.DDSTools.GetDDSInfo(data);
  96386. texture.width = info.width;
  96387. texture.height = info.height;
  96388. if (createPolynomials) {
  96389. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  96390. }
  96391. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  96392. engine._unpackFlipY(info.isCompressed);
  96393. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  96394. if (!info.isFourCC && info.mipmapCount === 1) {
  96395. engine.generateMipMapsForCubemap(texture);
  96396. }
  96397. }
  96398. engine._setCubeMapTextureParams(loadMipmap);
  96399. texture.isReady = true;
  96400. if (onLoad) {
  96401. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  96402. }
  96403. };
  96404. /**
  96405. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  96406. * @param data contains the texture data
  96407. * @param texture defines the BabylonJS internal texture
  96408. * @param callback defines the method to call once ready to upload
  96409. */
  96410. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  96411. var info = BABYLON.DDSTools.GetDDSInfo(data);
  96412. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  96413. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  96414. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  96415. });
  96416. };
  96417. return DDSTextureLoader;
  96418. }());
  96419. // Register the loader.
  96420. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  96421. })(BABYLON || (BABYLON = {}));
  96422. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  96423. var BABYLON;
  96424. (function (BABYLON) {
  96425. /**
  96426. * Based on jsTGALoader - Javascript loader for TGA file
  96427. * By Vincent Thibault
  96428. * @see http://blog.robrowser.com/javascript-tga-loader.html
  96429. */
  96430. var TGATools = /** @class */ (function () {
  96431. function TGATools() {
  96432. }
  96433. /**
  96434. * Gets the header of a TGA file
  96435. * @param data defines the TGA data
  96436. * @returns the header
  96437. */
  96438. TGATools.GetTGAHeader = function (data) {
  96439. var offset = 0;
  96440. var header = {
  96441. id_length: data[offset++],
  96442. colormap_type: data[offset++],
  96443. image_type: data[offset++],
  96444. colormap_index: data[offset++] | data[offset++] << 8,
  96445. colormap_length: data[offset++] | data[offset++] << 8,
  96446. colormap_size: data[offset++],
  96447. origin: [
  96448. data[offset++] | data[offset++] << 8,
  96449. data[offset++] | data[offset++] << 8
  96450. ],
  96451. width: data[offset++] | data[offset++] << 8,
  96452. height: data[offset++] | data[offset++] << 8,
  96453. pixel_size: data[offset++],
  96454. flags: data[offset++]
  96455. };
  96456. return header;
  96457. };
  96458. /**
  96459. * Uploads TGA content to a Babylon Texture
  96460. * @hidden
  96461. */
  96462. TGATools.UploadContent = function (texture, data) {
  96463. // Not enough data to contain header ?
  96464. if (data.length < 19) {
  96465. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  96466. return;
  96467. }
  96468. // Read Header
  96469. var offset = 18;
  96470. var header = TGATools.GetTGAHeader(data);
  96471. // Assume it's a valid Targa file.
  96472. if (header.id_length + offset > data.length) {
  96473. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  96474. return;
  96475. }
  96476. // Skip not needed data
  96477. offset += header.id_length;
  96478. var use_rle = false;
  96479. var use_pal = false;
  96480. var use_grey = false;
  96481. // Get some informations.
  96482. switch (header.image_type) {
  96483. case TGATools._TYPE_RLE_INDEXED:
  96484. use_rle = true;
  96485. case TGATools._TYPE_INDEXED:
  96486. use_pal = true;
  96487. break;
  96488. case TGATools._TYPE_RLE_RGB:
  96489. use_rle = true;
  96490. case TGATools._TYPE_RGB:
  96491. // use_rgb = true;
  96492. break;
  96493. case TGATools._TYPE_RLE_GREY:
  96494. use_rle = true;
  96495. case TGATools._TYPE_GREY:
  96496. use_grey = true;
  96497. break;
  96498. }
  96499. var pixel_data;
  96500. // var numAlphaBits = header.flags & 0xf;
  96501. var pixel_size = header.pixel_size >> 3;
  96502. var pixel_total = header.width * header.height * pixel_size;
  96503. // Read palettes
  96504. var palettes;
  96505. if (use_pal) {
  96506. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  96507. }
  96508. // Read LRE
  96509. if (use_rle) {
  96510. pixel_data = new Uint8Array(pixel_total);
  96511. var c, count, i;
  96512. var localOffset = 0;
  96513. var pixels = new Uint8Array(pixel_size);
  96514. while (offset < pixel_total && localOffset < pixel_total) {
  96515. c = data[offset++];
  96516. count = (c & 0x7f) + 1;
  96517. // RLE pixels
  96518. if (c & 0x80) {
  96519. // Bind pixel tmp array
  96520. for (i = 0; i < pixel_size; ++i) {
  96521. pixels[i] = data[offset++];
  96522. }
  96523. // Copy pixel array
  96524. for (i = 0; i < count; ++i) {
  96525. pixel_data.set(pixels, localOffset + i * pixel_size);
  96526. }
  96527. localOffset += pixel_size * count;
  96528. }
  96529. // Raw pixels
  96530. else {
  96531. count *= pixel_size;
  96532. for (i = 0; i < count; ++i) {
  96533. pixel_data[localOffset + i] = data[offset++];
  96534. }
  96535. localOffset += count;
  96536. }
  96537. }
  96538. }
  96539. // RAW Pixels
  96540. else {
  96541. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  96542. }
  96543. // Load to texture
  96544. var x_start, y_start, x_step, y_step, y_end, x_end;
  96545. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  96546. default:
  96547. case TGATools._ORIGIN_UL:
  96548. x_start = 0;
  96549. x_step = 1;
  96550. x_end = header.width;
  96551. y_start = 0;
  96552. y_step = 1;
  96553. y_end = header.height;
  96554. break;
  96555. case TGATools._ORIGIN_BL:
  96556. x_start = 0;
  96557. x_step = 1;
  96558. x_end = header.width;
  96559. y_start = header.height - 1;
  96560. y_step = -1;
  96561. y_end = -1;
  96562. break;
  96563. case TGATools._ORIGIN_UR:
  96564. x_start = header.width - 1;
  96565. x_step = -1;
  96566. x_end = -1;
  96567. y_start = 0;
  96568. y_step = 1;
  96569. y_end = header.height;
  96570. break;
  96571. case TGATools._ORIGIN_BR:
  96572. x_start = header.width - 1;
  96573. x_step = -1;
  96574. x_end = -1;
  96575. y_start = header.height - 1;
  96576. y_step = -1;
  96577. y_end = -1;
  96578. break;
  96579. }
  96580. // Load the specify method
  96581. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  96582. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  96583. var engine = texture.getEngine();
  96584. engine._uploadDataToTextureDirectly(texture, imageData);
  96585. };
  96586. /** @hidden */
  96587. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96588. var image = pixel_data, colormap = palettes;
  96589. var width = header.width, height = header.height;
  96590. var color, i = 0, x, y;
  96591. var imageData = new Uint8Array(width * height * 4);
  96592. for (y = y_start; y !== y_end; y += y_step) {
  96593. for (x = x_start; x !== x_end; x += x_step, i++) {
  96594. color = image[i];
  96595. imageData[(x + width * y) * 4 + 3] = 255;
  96596. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  96597. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  96598. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  96599. }
  96600. }
  96601. return imageData;
  96602. };
  96603. /** @hidden */
  96604. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96605. var image = pixel_data;
  96606. var width = header.width, height = header.height;
  96607. var color, i = 0, x, y;
  96608. var imageData = new Uint8Array(width * height * 4);
  96609. for (y = y_start; y !== y_end; y += y_step) {
  96610. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  96611. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  96612. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  96613. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  96614. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  96615. imageData[(x + width * y) * 4 + 0] = r;
  96616. imageData[(x + width * y) * 4 + 1] = g;
  96617. imageData[(x + width * y) * 4 + 2] = b;
  96618. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  96619. }
  96620. }
  96621. return imageData;
  96622. };
  96623. /** @hidden */
  96624. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96625. var image = pixel_data;
  96626. var width = header.width, height = header.height;
  96627. var i = 0, x, y;
  96628. var imageData = new Uint8Array(width * height * 4);
  96629. for (y = y_start; y !== y_end; y += y_step) {
  96630. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  96631. imageData[(x + width * y) * 4 + 3] = 255;
  96632. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  96633. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  96634. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  96635. }
  96636. }
  96637. return imageData;
  96638. };
  96639. /** @hidden */
  96640. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96641. var image = pixel_data;
  96642. var width = header.width, height = header.height;
  96643. var i = 0, x, y;
  96644. var imageData = new Uint8Array(width * height * 4);
  96645. for (y = y_start; y !== y_end; y += y_step) {
  96646. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  96647. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  96648. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  96649. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  96650. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  96651. }
  96652. }
  96653. return imageData;
  96654. };
  96655. /** @hidden */
  96656. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96657. var image = pixel_data;
  96658. var width = header.width, height = header.height;
  96659. var color, i = 0, x, y;
  96660. var imageData = new Uint8Array(width * height * 4);
  96661. for (y = y_start; y !== y_end; y += y_step) {
  96662. for (x = x_start; x !== x_end; x += x_step, i++) {
  96663. color = image[i];
  96664. imageData[(x + width * y) * 4 + 0] = color;
  96665. imageData[(x + width * y) * 4 + 1] = color;
  96666. imageData[(x + width * y) * 4 + 2] = color;
  96667. imageData[(x + width * y) * 4 + 3] = 255;
  96668. }
  96669. }
  96670. return imageData;
  96671. };
  96672. /** @hidden */
  96673. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  96674. var image = pixel_data;
  96675. var width = header.width, height = header.height;
  96676. var i = 0, x, y;
  96677. var imageData = new Uint8Array(width * height * 4);
  96678. for (y = y_start; y !== y_end; y += y_step) {
  96679. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  96680. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  96681. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  96682. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  96683. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  96684. }
  96685. }
  96686. return imageData;
  96687. };
  96688. //private static _TYPE_NO_DATA = 0;
  96689. TGATools._TYPE_INDEXED = 1;
  96690. TGATools._TYPE_RGB = 2;
  96691. TGATools._TYPE_GREY = 3;
  96692. TGATools._TYPE_RLE_INDEXED = 9;
  96693. TGATools._TYPE_RLE_RGB = 10;
  96694. TGATools._TYPE_RLE_GREY = 11;
  96695. TGATools._ORIGIN_MASK = 0x30;
  96696. TGATools._ORIGIN_SHIFT = 0x04;
  96697. TGATools._ORIGIN_BL = 0x00;
  96698. TGATools._ORIGIN_BR = 0x01;
  96699. TGATools._ORIGIN_UL = 0x02;
  96700. TGATools._ORIGIN_UR = 0x03;
  96701. return TGATools;
  96702. }());
  96703. BABYLON.TGATools = TGATools;
  96704. })(BABYLON || (BABYLON = {}));
  96705. //# sourceMappingURL=babylon.tga.js.map
  96706. var BABYLON;
  96707. (function (BABYLON) {
  96708. /**
  96709. * Implementation of the TGA Texture Loader.
  96710. */
  96711. var TGATextureLoader = /** @class */ (function () {
  96712. function TGATextureLoader() {
  96713. /**
  96714. * Defines wether the loader supports cascade loading the different faces.
  96715. */
  96716. this.supportCascades = false;
  96717. }
  96718. /**
  96719. * This returns if the loader support the current file information.
  96720. * @param extension defines the file extension of the file being loaded
  96721. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96722. * @param fallback defines the fallback internal texture if any
  96723. * @param isBase64 defines whether the texture is encoded as a base64
  96724. * @param isBuffer defines whether the texture data are stored as a buffer
  96725. * @returns true if the loader can load the specified file
  96726. */
  96727. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  96728. return extension.indexOf(".tga") === 0;
  96729. };
  96730. /**
  96731. * Transform the url before loading if required.
  96732. * @param rootUrl the url of the texture
  96733. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96734. * @returns the transformed texture
  96735. */
  96736. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  96737. return rootUrl;
  96738. };
  96739. /**
  96740. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  96741. * @param rootUrl the url of the texture
  96742. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96743. * @returns the fallback texture
  96744. */
  96745. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  96746. return null;
  96747. };
  96748. /**
  96749. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  96750. * @param data contains the texture data
  96751. * @param texture defines the BabylonJS internal texture
  96752. * @param createPolynomials will be true if polynomials have been requested
  96753. * @param onLoad defines the callback to trigger once the texture is ready
  96754. * @param onError defines the callback to trigger in case of error
  96755. */
  96756. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  96757. throw ".env not supported in Cube.";
  96758. };
  96759. /**
  96760. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  96761. * @param data contains the texture data
  96762. * @param texture defines the BabylonJS internal texture
  96763. * @param callback defines the method to call once ready to upload
  96764. */
  96765. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  96766. var uintData = new Uint8Array(data);
  96767. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  96768. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  96769. BABYLON.TGATools.UploadContent(texture, uintData);
  96770. });
  96771. };
  96772. return TGATextureLoader;
  96773. }());
  96774. // Register the loader.
  96775. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  96776. })(BABYLON || (BABYLON = {}));
  96777. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  96778. var BABYLON;
  96779. (function (BABYLON) {
  96780. /**
  96781. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  96782. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  96783. */
  96784. var KhronosTextureContainer = /** @class */ (function () {
  96785. /**
  96786. * Creates a new KhronosTextureContainer
  96787. * @param arrayBuffer contents of the KTX container file
  96788. * @param facesExpected should be either 1 or 6, based whether a cube texture or or
  96789. * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
  96790. * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
  96791. */
  96792. function KhronosTextureContainer(
  96793. /** contents of the KTX container file */
  96794. arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  96795. this.arrayBuffer = arrayBuffer;
  96796. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  96797. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  96798. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  96799. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  96800. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  96801. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  96802. BABYLON.Tools.Error("texture missing KTX identifier");
  96803. return;
  96804. }
  96805. // load the reset of the header in native 32 bit int
  96806. var header = new Int32Array(this.arrayBuffer, 12, 13);
  96807. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  96808. var oppositeEndianess = header[0] === 0x01020304;
  96809. // read all the header elements in order they exist in the file, without modification (sans endainness)
  96810. this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1]; // must be 0 for compressed textures
  96811. this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2]; // must be 1 for compressed textures
  96812. this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3]; // must be 0 for compressed textures
  96813. this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  96814. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  96815. this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  96816. this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  96817. this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  96818. this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9]; // used for texture arrays
  96819. this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  96820. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  96821. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12]; // the amount of space after the header for meta-data
  96822. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  96823. if (this.glType !== 0) {
  96824. BABYLON.Tools.Error("only compressed formats currently supported");
  96825. return;
  96826. }
  96827. else {
  96828. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  96829. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  96830. }
  96831. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  96832. BABYLON.Tools.Error("only 2D textures currently supported");
  96833. return;
  96834. }
  96835. if (this.numberOfArrayElements !== 0) {
  96836. BABYLON.Tools.Error("texture arrays not currently supported");
  96837. return;
  96838. }
  96839. if (this.numberOfFaces !== facesExpected) {
  96840. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  96841. return;
  96842. }
  96843. // we now have a completely validated file, so could use existence of loadType as success
  96844. // would need to make this more elaborate & adjust checks above to support more than one load type
  96845. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  96846. }
  96847. //
  96848. /**
  96849. * Revert the endianness of a value.
  96850. * Not as fast hardware based, but will probably never need to use
  96851. * @param val defines the value to convert
  96852. * @returns the new value
  96853. */
  96854. KhronosTextureContainer.prototype.switchEndianness = function (val) {
  96855. return ((val & 0xFF) << 24)
  96856. | ((val & 0xFF00) << 8)
  96857. | ((val >> 8) & 0xFF00)
  96858. | ((val >> 24) & 0xFF);
  96859. };
  96860. /**
  96861. * Uploads KTX content to a Babylon Texture.
  96862. * It is assumed that the texture has already been created & is currently bound
  96863. * @hidden
  96864. */
  96865. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  96866. switch (this.loadType) {
  96867. case KhronosTextureContainer.COMPRESSED_2D:
  96868. this._upload2DCompressedLevels(texture, loadMipmaps);
  96869. break;
  96870. case KhronosTextureContainer.TEX_2D:
  96871. case KhronosTextureContainer.COMPRESSED_3D:
  96872. case KhronosTextureContainer.TEX_3D:
  96873. }
  96874. };
  96875. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  96876. // initialize width & height for level 1
  96877. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  96878. var width = this.pixelWidth;
  96879. var height = this.pixelHeight;
  96880. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  96881. for (var level = 0; level < mipmapCount; level++) {
  96882. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  96883. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  96884. for (var face = 0; face < this.numberOfFaces; face++) {
  96885. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  96886. var engine = texture.getEngine();
  96887. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  96888. dataOffset += imageSize; // add size of the image for the next face/mipmap
  96889. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  96890. }
  96891. width = Math.max(1.0, width * 0.5);
  96892. height = Math.max(1.0, height * 0.5);
  96893. }
  96894. };
  96895. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  96896. // load types
  96897. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  96898. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  96899. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  96900. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  96901. return KhronosTextureContainer;
  96902. }());
  96903. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  96904. })(BABYLON || (BABYLON = {}));
  96905. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  96906. var BABYLON;
  96907. (function (BABYLON) {
  96908. /**
  96909. * Implementation of the KTX Texture Loader.
  96910. */
  96911. var KTXTextureLoader = /** @class */ (function () {
  96912. function KTXTextureLoader() {
  96913. /**
  96914. * Defines wether the loader supports cascade loading the different faces.
  96915. */
  96916. this.supportCascades = false;
  96917. }
  96918. /**
  96919. * This returns if the loader support the current file information.
  96920. * @param extension defines the file extension of the file being loaded
  96921. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96922. * @param fallback defines the fallback internal texture if any
  96923. * @param isBase64 defines whether the texture is encoded as a base64
  96924. * @param isBuffer defines whether the texture data are stored as a buffer
  96925. * @returns true if the loader can load the specified file
  96926. */
  96927. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  96928. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  96929. return true;
  96930. }
  96931. return false;
  96932. };
  96933. /**
  96934. * Transform the url before loading if required.
  96935. * @param rootUrl the url of the texture
  96936. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96937. * @returns the transformed texture
  96938. */
  96939. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  96940. var lastDot = rootUrl.lastIndexOf('.');
  96941. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  96942. };
  96943. /**
  96944. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  96945. * @param rootUrl the url of the texture
  96946. * @param textureFormatInUse defines the current compressed format in use iun the engine
  96947. * @returns the fallback texture
  96948. */
  96949. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  96950. // remove the format appended to the rootUrl in the original createCubeTexture call.
  96951. var exp = new RegExp("" + textureFormatInUse + "$");
  96952. return rootUrl.replace(exp, "");
  96953. };
  96954. /**
  96955. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  96956. * @param data contains the texture data
  96957. * @param texture defines the BabylonJS internal texture
  96958. * @param createPolynomials will be true if polynomials have been requested
  96959. * @param onLoad defines the callback to trigger once the texture is ready
  96960. * @param onError defines the callback to trigger in case of error
  96961. */
  96962. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  96963. if (Array.isArray(data)) {
  96964. return;
  96965. }
  96966. var engine = texture.getEngine();
  96967. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  96968. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  96969. engine._unpackFlipY(true);
  96970. ktx.uploadLevels(texture, texture.generateMipMaps);
  96971. texture.width = ktx.pixelWidth;
  96972. texture.height = ktx.pixelHeight;
  96973. engine._setCubeMapTextureParams(loadMipmap);
  96974. texture.isReady = true;
  96975. };
  96976. /**
  96977. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  96978. * @param data contains the texture data
  96979. * @param texture defines the BabylonJS internal texture
  96980. * @param callback defines the method to call once ready to upload
  96981. */
  96982. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  96983. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  96984. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  96985. ktx.uploadLevels(texture, texture.generateMipMaps);
  96986. });
  96987. };
  96988. return KTXTextureLoader;
  96989. }());
  96990. // Register the loader.
  96991. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  96992. })(BABYLON || (BABYLON = {}));
  96993. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  96994. var BABYLON;
  96995. (function (BABYLON) {
  96996. /**
  96997. * Sets of helpers addressing the serialization and deserialization of environment texture
  96998. * stored in a BabylonJS env file.
  96999. * Those files are usually stored as .env files.
  97000. */
  97001. var EnvironmentTextureTools = /** @class */ (function () {
  97002. function EnvironmentTextureTools() {
  97003. }
  97004. /**
  97005. * Gets the environment info from an env file.
  97006. * @param data The array buffer containing the .env bytes.
  97007. * @returns the environment file info (the json header) if successfully parsed.
  97008. */
  97009. EnvironmentTextureTools.GetEnvInfo = function (data) {
  97010. var dataView = new DataView(data);
  97011. var pos = 0;
  97012. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  97013. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  97014. BABYLON.Tools.Error('Not a babylon environment map');
  97015. return null;
  97016. }
  97017. }
  97018. // Read json manifest - collect characters up to null terminator
  97019. var manifestString = '';
  97020. var charCode = 0x00;
  97021. while ((charCode = dataView.getUint8(pos++))) {
  97022. manifestString += String.fromCharCode(charCode);
  97023. }
  97024. var manifest = JSON.parse(manifestString);
  97025. if (manifest.specular) {
  97026. // Extend the header with the position of the payload.
  97027. manifest.specular.specularDataPosition = pos;
  97028. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  97029. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  97030. }
  97031. return manifest;
  97032. };
  97033. /**
  97034. * Creates an environment texture from a loaded cube texture.
  97035. * @param texture defines the cube texture to convert in env file
  97036. * @return a promise containing the environment data if succesfull.
  97037. */
  97038. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  97039. var _this = this;
  97040. var internalTexture = texture.getInternalTexture();
  97041. if (!internalTexture) {
  97042. return Promise.reject("The cube texture is invalid.");
  97043. }
  97044. if (!texture._prefiltered) {
  97045. return Promise.reject("The cube texture is invalid (not prefiltered).");
  97046. }
  97047. var engine = internalTexture.getEngine();
  97048. if (engine && engine.premultipliedAlpha) {
  97049. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  97050. }
  97051. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  97052. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  97053. }
  97054. var canvas = engine.getRenderingCanvas();
  97055. if (!canvas) {
  97056. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  97057. }
  97058. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97059. if (!engine.getCaps().textureFloatRender) {
  97060. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97061. if (!engine.getCaps().textureHalfFloatRender) {
  97062. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  97063. }
  97064. }
  97065. var cubeWidth = internalTexture.width;
  97066. var hostingScene = new BABYLON.Scene(engine);
  97067. var specularTextures = {};
  97068. var promises = [];
  97069. // Read and collect all mipmaps data from the cube.
  97070. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  97071. mipmapsCount = Math.round(mipmapsCount);
  97072. var _loop_1 = function (i) {
  97073. var faceWidth = Math.pow(2, mipmapsCount - i);
  97074. var _loop_2 = function (face) {
  97075. var data = texture.readPixels(face, i);
  97076. // Creates a temp texture with the face data.
  97077. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  97078. // And rgbdEncode them.
  97079. var promise = new Promise(function (resolve, reject) {
  97080. 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);
  97081. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  97082. rgbdPostProcess.onApply = function (effect) {
  97083. effect._bindTexture("textureSampler", tempTexture);
  97084. };
  97085. // As the process needs to happen on the main canvas, keep track of the current size
  97086. var currentW = engine.getRenderWidth();
  97087. var currentH = engine.getRenderHeight();
  97088. // Set the desired size for the texture
  97089. engine.setSize(faceWidth, faceWidth);
  97090. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  97091. // Reading datas from WebGL
  97092. BABYLON.Tools.ToBlob(canvas, function (blob) {
  97093. var fileReader = new FileReader();
  97094. fileReader.onload = function (event) {
  97095. var arrayBuffer = event.target.result;
  97096. specularTextures[i * 6 + face] = arrayBuffer;
  97097. resolve();
  97098. };
  97099. fileReader.readAsArrayBuffer(blob);
  97100. });
  97101. // Reapply the previous canvas size
  97102. engine.setSize(currentW, currentH);
  97103. });
  97104. });
  97105. promises.push(promise);
  97106. };
  97107. // All faces of the cube.
  97108. for (var face = 0; face < 6; face++) {
  97109. _loop_2(face);
  97110. }
  97111. };
  97112. for (var i = 0; i <= mipmapsCount; i++) {
  97113. _loop_1(i);
  97114. }
  97115. // Once all the textures haves been collected as RGBD stored in PNGs
  97116. return Promise.all(promises).then(function () {
  97117. // We can delete the hosting scene keeping track of all the creation objects
  97118. hostingScene.dispose();
  97119. // Creates the json header for the env texture
  97120. var info = {
  97121. version: 1,
  97122. width: cubeWidth,
  97123. irradiance: _this._CreateEnvTextureIrradiance(texture),
  97124. specular: {
  97125. mipmaps: [],
  97126. lodGenerationScale: texture.lodGenerationScale
  97127. }
  97128. };
  97129. // Sets the specular image data information
  97130. var position = 0;
  97131. for (var i = 0; i <= mipmapsCount; i++) {
  97132. for (var face = 0; face < 6; face++) {
  97133. var byteLength = specularTextures[i * 6 + face].byteLength;
  97134. info.specular.mipmaps.push({
  97135. length: byteLength,
  97136. position: position
  97137. });
  97138. position += byteLength;
  97139. }
  97140. }
  97141. // Encode the JSON as an array buffer
  97142. var infoString = JSON.stringify(info);
  97143. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  97144. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  97145. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  97146. infoView[i] = infoString.charCodeAt(i);
  97147. }
  97148. // Ends up with a null terminator for easier parsing
  97149. infoView[infoString.length] = 0x00;
  97150. // Computes the final required size and creates the storage
  97151. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  97152. var finalBuffer = new ArrayBuffer(totalSize);
  97153. var finalBufferView = new Uint8Array(finalBuffer);
  97154. var dataView = new DataView(finalBuffer);
  97155. // Copy the magic bytes identifying the file in
  97156. var pos = 0;
  97157. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  97158. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  97159. }
  97160. // Add the json info
  97161. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  97162. pos += infoBuffer.byteLength;
  97163. // Finally inserts the texture data
  97164. for (var i = 0; i <= mipmapsCount; i++) {
  97165. for (var face = 0; face < 6; face++) {
  97166. var dataBuffer = specularTextures[i * 6 + face];
  97167. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  97168. pos += dataBuffer.byteLength;
  97169. }
  97170. }
  97171. // Voila
  97172. return finalBuffer;
  97173. });
  97174. };
  97175. /**
  97176. * Creates a JSON representation of the spherical data.
  97177. * @param texture defines the texture containing the polynomials
  97178. * @return the JSON representation of the spherical info
  97179. */
  97180. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  97181. var polynmials = texture.sphericalPolynomial;
  97182. if (polynmials == null) {
  97183. return null;
  97184. }
  97185. return {
  97186. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  97187. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  97188. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  97189. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  97190. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  97191. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  97192. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  97193. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  97194. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  97195. };
  97196. };
  97197. /**
  97198. * Uploads the texture info contained in the env file to the GPU.
  97199. * @param texture defines the internal texture to upload to
  97200. * @param arrayBuffer defines the buffer cotaining the data to load
  97201. * @param info defines the texture info retrieved through the GetEnvInfo method
  97202. * @returns a promise
  97203. */
  97204. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  97205. if (info.version !== 1) {
  97206. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  97207. }
  97208. var specularInfo = info.specular;
  97209. if (!specularInfo) {
  97210. // Nothing else parsed so far
  97211. return Promise.resolve();
  97212. }
  97213. // Double checks the enclosed info
  97214. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  97215. mipmapsCount = Math.round(mipmapsCount) + 1;
  97216. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  97217. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  97218. }
  97219. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  97220. var imageData = new Array(mipmapsCount);
  97221. for (var i = 0; i < mipmapsCount; i++) {
  97222. imageData[i] = new Array(6);
  97223. for (var face = 0; face < 6; face++) {
  97224. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  97225. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  97226. }
  97227. }
  97228. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  97229. };
  97230. /**
  97231. * Uploads the levels of image data to the GPU.
  97232. * @param texture defines the internal texture to upload to
  97233. * @param imageData defines the array buffer views of image data [mipmap][face]
  97234. * @returns a promise
  97235. */
  97236. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  97237. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  97238. throw new Error("Texture size must be a power of two");
  97239. }
  97240. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  97241. // Gets everything ready.
  97242. var engine = texture.getEngine();
  97243. var expandTexture = false;
  97244. var generateNonLODTextures = false;
  97245. var rgbdPostProcess = null;
  97246. var cubeRtt = null;
  97247. var lodTextures = null;
  97248. var caps = engine.getCaps();
  97249. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  97250. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97251. texture.generateMipMaps = true;
  97252. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  97253. // Add extra process if texture lod is not supported
  97254. if (!caps.textureLOD) {
  97255. expandTexture = false;
  97256. generateNonLODTextures = true;
  97257. lodTextures = {};
  97258. }
  97259. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  97260. else if (engine.webGLVersion < 2) {
  97261. expandTexture = false;
  97262. }
  97263. // If half float available we can uncompress the texture
  97264. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  97265. expandTexture = true;
  97266. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97267. }
  97268. // If full float available we can uncompress the texture
  97269. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  97270. expandTexture = true;
  97271. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97272. }
  97273. // Expand the texture if possible
  97274. if (expandTexture) {
  97275. // Simply run through the decode PP
  97276. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  97277. texture._isRGBD = false;
  97278. texture.invertY = false;
  97279. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  97280. generateDepthBuffer: false,
  97281. generateMipMaps: true,
  97282. generateStencilBuffer: false,
  97283. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  97284. type: texture.type,
  97285. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  97286. });
  97287. }
  97288. else {
  97289. texture._isRGBD = true;
  97290. texture.invertY = true;
  97291. // In case of missing support, applies the same patch than DDS files.
  97292. if (generateNonLODTextures) {
  97293. var mipSlices = 3;
  97294. var scale = texture._lodGenerationScale;
  97295. var offset = texture._lodGenerationOffset;
  97296. for (var i = 0; i < mipSlices; i++) {
  97297. //compute LOD from even spacing in smoothness (matching shader calculation)
  97298. var smoothness = i / (mipSlices - 1);
  97299. var roughness = 1 - smoothness;
  97300. var minLODIndex = offset; // roughness = 0
  97301. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  97302. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  97303. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  97304. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  97305. glTextureFromLod.isCube = true;
  97306. glTextureFromLod.invertY = true;
  97307. glTextureFromLod.generateMipMaps = false;
  97308. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  97309. // Wrap in a base texture for easy binding.
  97310. var lodTexture = new BABYLON.BaseTexture(null);
  97311. lodTexture.isCube = true;
  97312. lodTexture._texture = glTextureFromLod;
  97313. lodTextures[mipmapIndex] = lodTexture;
  97314. switch (i) {
  97315. case 0:
  97316. texture._lodTextureLow = lodTexture;
  97317. break;
  97318. case 1:
  97319. texture._lodTextureMid = lodTexture;
  97320. break;
  97321. case 2:
  97322. texture._lodTextureHigh = lodTexture;
  97323. break;
  97324. }
  97325. }
  97326. }
  97327. }
  97328. var promises = [];
  97329. var _loop_3 = function (i) {
  97330. var _loop_4 = function (face) {
  97331. // Constructs an image element from image data
  97332. var bytes = imageData[i][face];
  97333. var blob = new Blob([bytes], { type: 'image/png' });
  97334. var url = URL.createObjectURL(blob);
  97335. var image = new Image();
  97336. image.src = url;
  97337. // Enqueue promise to upload to the texture.
  97338. var promise = new Promise(function (resolve, reject) {
  97339. image.onload = function () {
  97340. if (expandTexture) {
  97341. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  97342. reject(message);
  97343. }, image);
  97344. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  97345. // Uncompress the data to a RTT
  97346. rgbdPostProcess.onApply = function (effect) {
  97347. effect._bindTexture("textureSampler", tempTexture_1);
  97348. effect.setFloat2("scale", 1, 1);
  97349. };
  97350. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  97351. // Cleanup
  97352. engine.restoreDefaultFramebuffer();
  97353. tempTexture_1.dispose();
  97354. window.URL.revokeObjectURL(url);
  97355. resolve();
  97356. });
  97357. }
  97358. else {
  97359. engine._uploadImageToTexture(texture, image, face, i);
  97360. // Upload the face to the non lod texture support
  97361. if (generateNonLODTextures) {
  97362. var lodTexture = lodTextures[i];
  97363. if (lodTexture) {
  97364. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  97365. }
  97366. }
  97367. resolve();
  97368. }
  97369. };
  97370. image.onerror = function (error) {
  97371. reject(error);
  97372. };
  97373. });
  97374. promises.push(promise);
  97375. };
  97376. // All faces
  97377. for (var face = 0; face < 6; face++) {
  97378. _loop_4(face);
  97379. }
  97380. };
  97381. // All mipmaps up to provided number of images
  97382. for (var i = 0; i < imageData.length; i++) {
  97383. _loop_3(i);
  97384. }
  97385. // Fill remaining mipmaps with black textures.
  97386. if (imageData.length < mipmapsCount) {
  97387. var data = void 0;
  97388. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  97389. var dataLength = size * size * 4;
  97390. switch (texture.type) {
  97391. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  97392. data = new Uint8Array(dataLength);
  97393. break;
  97394. }
  97395. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  97396. data = new Uint16Array(dataLength);
  97397. break;
  97398. }
  97399. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  97400. data = new Float32Array(dataLength);
  97401. break;
  97402. }
  97403. }
  97404. for (var i = imageData.length; i < mipmapsCount; i++) {
  97405. for (var face = 0; face < 6; face++) {
  97406. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  97407. }
  97408. }
  97409. }
  97410. // Once all done, finishes the cleanup and return
  97411. return Promise.all(promises).then(function () {
  97412. // Release temp RTT.
  97413. if (cubeRtt) {
  97414. engine._releaseFramebufferObjects(cubeRtt);
  97415. cubeRtt._swapAndDie(texture);
  97416. }
  97417. // Release temp Post Process.
  97418. if (rgbdPostProcess) {
  97419. rgbdPostProcess.dispose();
  97420. }
  97421. // Flag internal texture as ready in case they are in use.
  97422. if (generateNonLODTextures) {
  97423. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  97424. texture._lodTextureHigh._texture.isReady = true;
  97425. }
  97426. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  97427. texture._lodTextureMid._texture.isReady = true;
  97428. }
  97429. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  97430. texture._lodTextureLow._texture.isReady = true;
  97431. }
  97432. }
  97433. });
  97434. };
  97435. /**
  97436. * Uploads spherical polynomials information to the texture.
  97437. * @param texture defines the texture we are trying to upload the information to
  97438. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  97439. */
  97440. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  97441. if (info.version !== 1) {
  97442. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  97443. }
  97444. var irradianceInfo = info.irradiance;
  97445. if (!irradianceInfo) {
  97446. return;
  97447. }
  97448. var sp = new BABYLON.SphericalPolynomial();
  97449. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  97450. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  97451. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  97452. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  97453. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  97454. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  97455. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  97456. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  97457. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  97458. texture._sphericalPolynomial = sp;
  97459. };
  97460. /**
  97461. * Magic number identifying the env file.
  97462. */
  97463. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  97464. return EnvironmentTextureTools;
  97465. }());
  97466. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  97467. })(BABYLON || (BABYLON = {}));
  97468. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  97469. var BABYLON;
  97470. (function (BABYLON) {
  97471. /**
  97472. * Implementation of the ENV Texture Loader.
  97473. */
  97474. var ENVTextureLoader = /** @class */ (function () {
  97475. function ENVTextureLoader() {
  97476. /**
  97477. * Defines wether the loader supports cascade loading the different faces.
  97478. */
  97479. this.supportCascades = false;
  97480. }
  97481. /**
  97482. * This returns if the loader support the current file information.
  97483. * @param extension defines the file extension of the file being loaded
  97484. * @param textureFormatInUse defines the current compressed format in use iun the engine
  97485. * @param fallback defines the fallback internal texture if any
  97486. * @param isBase64 defines whether the texture is encoded as a base64
  97487. * @param isBuffer defines whether the texture data are stored as a buffer
  97488. * @returns true if the loader can load the specified file
  97489. */
  97490. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  97491. return extension.indexOf(".env") === 0;
  97492. };
  97493. /**
  97494. * Transform the url before loading if required.
  97495. * @param rootUrl the url of the texture
  97496. * @param textureFormatInUse defines the current compressed format in use iun the engine
  97497. * @returns the transformed texture
  97498. */
  97499. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  97500. return rootUrl;
  97501. };
  97502. /**
  97503. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  97504. * @param rootUrl the url of the texture
  97505. * @param textureFormatInUse defines the current compressed format in use iun the engine
  97506. * @returns the fallback texture
  97507. */
  97508. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  97509. return null;
  97510. };
  97511. /**
  97512. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  97513. * @param data contains the texture data
  97514. * @param texture defines the BabylonJS internal texture
  97515. * @param createPolynomials will be true if polynomials have been requested
  97516. * @param onLoad defines the callback to trigger once the texture is ready
  97517. * @param onError defines the callback to trigger in case of error
  97518. */
  97519. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  97520. if (Array.isArray(data)) {
  97521. return;
  97522. }
  97523. data = data;
  97524. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  97525. if (info) {
  97526. texture.width = info.width;
  97527. texture.height = info.width;
  97528. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  97529. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  97530. texture.isReady = true;
  97531. if (onLoad) {
  97532. onLoad();
  97533. }
  97534. });
  97535. }
  97536. else if (onError) {
  97537. onError("Can not parse the environment file", null);
  97538. }
  97539. };
  97540. /**
  97541. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  97542. * @param data contains the texture data
  97543. * @param texture defines the BabylonJS internal texture
  97544. * @param callback defines the method to call once ready to upload
  97545. */
  97546. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  97547. throw ".env not supported in 2d.";
  97548. };
  97549. return ENVTextureLoader;
  97550. }());
  97551. // Register the loader.
  97552. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  97553. })(BABYLON || (BABYLON = {}));
  97554. //# sourceMappingURL=babylon.envTextureLoader.js.map
  97555. var BABYLON;
  97556. (function (BABYLON) {
  97557. /**
  97558. * Renders a layer on top of an existing scene
  97559. */
  97560. var UtilityLayerRenderer = /** @class */ (function () {
  97561. /**
  97562. * Instantiates a UtilityLayerRenderer
  97563. * @param originalScene the original scene that will be rendered on top of
  97564. */
  97565. function UtilityLayerRenderer(
  97566. /** the original scene that will be rendered on top of */
  97567. originalScene) {
  97568. var _this = this;
  97569. this.originalScene = originalScene;
  97570. this._pointerCaptures = {};
  97571. this._lastPointerEvents = {};
  97572. /**
  97573. * If the utility layer should automatically be rendered on top of existing scene
  97574. */
  97575. this.shouldRender = true;
  97576. /**
  97577. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  97578. */
  97579. this.onlyCheckPointerDownEvents = true;
  97580. /**
  97581. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  97582. */
  97583. this.processAllEvents = false;
  97584. /**
  97585. * Observable raised when the pointer move from the utility layer scene to the main scene
  97586. */
  97587. this.onPointerOutObservable = new BABYLON.Observable();
  97588. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  97589. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  97590. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  97591. this.utilityLayerScene._allowPostProcessClearColor = false;
  97592. originalScene.getEngine().scenes.pop();
  97593. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  97594. this.utilityLayerScene.detachControl();
  97595. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  97596. if (!_this.processAllEvents) {
  97597. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  97598. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  97599. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  97600. return;
  97601. }
  97602. }
  97603. var pointerEvent = (prePointerInfo.event);
  97604. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  97605. _this._pointerCaptures[pointerEvent.pointerId] = false;
  97606. return;
  97607. }
  97608. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  97609. if (!prePointerInfo.ray && utilityScenePick) {
  97610. prePointerInfo.ray = utilityScenePick.ray;
  97611. }
  97612. // always fire the prepointer oversvable
  97613. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  97614. // allow every non pointer down event to flow to the utility layer
  97615. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  97616. if (!prePointerInfo.skipOnPointerObservable) {
  97617. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  97618. }
  97619. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  97620. _this._pointerCaptures[pointerEvent.pointerId] = false;
  97621. }
  97622. return;
  97623. }
  97624. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  97625. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  97626. if (utilityScenePick && utilityScenePick.hit) {
  97627. if (!prePointerInfo.skipOnPointerObservable) {
  97628. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  97629. }
  97630. prePointerInfo.skipOnPointerObservable = true;
  97631. }
  97632. }
  97633. else {
  97634. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  97635. var pointerEvent_1 = (prePointerInfo.event);
  97636. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  97637. if (originalScenePick && utilityScenePick) {
  97638. // No pick in utility scene
  97639. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  97640. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  97641. // We touched an utility mesh present in the main scene
  97642. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  97643. prePointerInfo.skipOnPointerObservable = true;
  97644. }
  97645. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  97646. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  97647. }
  97648. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  97649. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  97650. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  97651. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  97652. }
  97653. }
  97654. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  97655. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  97656. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  97657. // If a previous utility layer set this, do not unset this
  97658. if (!prePointerInfo.skipOnPointerObservable) {
  97659. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  97660. }
  97661. }
  97662. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  97663. // We have a pick in both scenes but main is closer than utility
  97664. // We touched an utility mesh present in the main scene
  97665. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  97666. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  97667. prePointerInfo.skipOnPointerObservable = true;
  97668. }
  97669. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  97670. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  97671. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  97672. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  97673. }
  97674. }
  97675. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  97676. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  97677. }
  97678. }
  97679. }
  97680. });
  97681. // Render directly on top of existing scene without clearing
  97682. this.utilityLayerScene.autoClear = false;
  97683. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  97684. if (_this.shouldRender) {
  97685. _this.render();
  97686. }
  97687. });
  97688. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  97689. _this.dispose();
  97690. });
  97691. this._updateCamera();
  97692. }
  97693. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  97694. /**
  97695. * 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)
  97696. */
  97697. get: function () {
  97698. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  97699. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  97700. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  97701. UtilityLayerRenderer._DefaultUtilityLayer = null;
  97702. });
  97703. }
  97704. return UtilityLayerRenderer._DefaultUtilityLayer;
  97705. },
  97706. enumerable: true,
  97707. configurable: true
  97708. });
  97709. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  97710. /**
  97711. * 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)
  97712. */
  97713. get: function () {
  97714. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  97715. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  97716. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  97717. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  97718. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  97719. });
  97720. }
  97721. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  97722. },
  97723. enumerable: true,
  97724. configurable: true
  97725. });
  97726. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  97727. if (!prePointerInfo.skipOnPointerObservable) {
  97728. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  97729. this._lastPointerEvents[pointerEvent.pointerId] = true;
  97730. }
  97731. };
  97732. /**
  97733. * Renders the utility layers scene on top of the original scene
  97734. */
  97735. UtilityLayerRenderer.prototype.render = function () {
  97736. this._updateCamera();
  97737. if (this.utilityLayerScene.activeCamera) {
  97738. // Set the camera's scene to utility layers scene
  97739. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  97740. var camera = this.utilityLayerScene.activeCamera;
  97741. camera._scene = this.utilityLayerScene;
  97742. if (camera.leftCamera) {
  97743. camera.leftCamera._scene = this.utilityLayerScene;
  97744. }
  97745. if (camera.rightCamera) {
  97746. camera.rightCamera._scene = this.utilityLayerScene;
  97747. }
  97748. this.utilityLayerScene.render(false);
  97749. // Reset camera's scene back to original
  97750. camera._scene = oldScene;
  97751. if (camera.leftCamera) {
  97752. camera.leftCamera._scene = oldScene;
  97753. }
  97754. if (camera.rightCamera) {
  97755. camera.rightCamera._scene = oldScene;
  97756. }
  97757. }
  97758. };
  97759. /**
  97760. * Disposes of the renderer
  97761. */
  97762. UtilityLayerRenderer.prototype.dispose = function () {
  97763. this.onPointerOutObservable.clear();
  97764. if (this._afterRenderObserver) {
  97765. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  97766. }
  97767. if (this._sceneDisposeObserver) {
  97768. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  97769. }
  97770. if (this._originalPointerObserver) {
  97771. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  97772. }
  97773. this.utilityLayerScene.dispose();
  97774. };
  97775. UtilityLayerRenderer.prototype._updateCamera = function () {
  97776. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  97777. };
  97778. UtilityLayerRenderer._DefaultUtilityLayer = null;
  97779. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  97780. return UtilityLayerRenderer;
  97781. }());
  97782. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  97783. })(BABYLON || (BABYLON = {}));
  97784. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  97785. //# sourceMappingURL=babylon.behavior.js.map
  97786. var BABYLON;
  97787. (function (BABYLON) {
  97788. /**
  97789. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  97790. */
  97791. var PointerDragBehavior = /** @class */ (function () {
  97792. /**
  97793. * Creates a pointer drag behavior that can be attached to a mesh
  97794. * @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)
  97795. */
  97796. function PointerDragBehavior(options) {
  97797. /**
  97798. * 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)
  97799. */
  97800. this.maxDragAngle = 0;
  97801. /**
  97802. * @hidden
  97803. */
  97804. this._useAlternatePickedPointAboveMaxDragAngle = false;
  97805. /**
  97806. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  97807. */
  97808. this.currentDraggingPointerID = -1;
  97809. /**
  97810. * If the behavior is currently in a dragging state
  97811. */
  97812. this.dragging = false;
  97813. /**
  97814. * 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)
  97815. */
  97816. this.dragDeltaRatio = 0.2;
  97817. /**
  97818. * If the drag plane orientation should be updated during the dragging (Default: true)
  97819. */
  97820. this.updateDragPlane = true;
  97821. // Debug mode will display drag planes to help visualize behavior
  97822. this._debugMode = false;
  97823. this._moving = false;
  97824. /**
  97825. * Fires each time the attached mesh is dragged with the pointer
  97826. * * delta between last drag position and current drag position in world space
  97827. * * dragDistance along the drag axis
  97828. * * dragPlaneNormal normal of the current drag plane used during the drag
  97829. * * dragPlanePoint in world space where the drag intersects the drag plane
  97830. */
  97831. this.onDragObservable = new BABYLON.Observable();
  97832. /**
  97833. * Fires each time a drag begins (eg. mouse down on mesh)
  97834. */
  97835. this.onDragStartObservable = new BABYLON.Observable();
  97836. /**
  97837. * Fires each time a drag ends (eg. mouse release after drag)
  97838. */
  97839. this.onDragEndObservable = new BABYLON.Observable();
  97840. /**
  97841. * If the attached mesh should be moved when dragged
  97842. */
  97843. this.moveAttached = true;
  97844. /**
  97845. * If the drag behavior will react to drag events (Default: true)
  97846. */
  97847. this.enabled = true;
  97848. /**
  97849. * If camera controls should be detached during the drag
  97850. */
  97851. this.detachCameraControls = true;
  97852. /**
  97853. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  97854. */
  97855. this.useObjectOrienationForDragging = true;
  97856. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  97857. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  97858. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  97859. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  97860. this._attachedElement = null;
  97861. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  97862. this._lastPointerRay = {};
  97863. this._dragDelta = new BABYLON.Vector3();
  97864. // Variables to avoid instantiation in the below method
  97865. this._pointA = new BABYLON.Vector3(0, 0, 0);
  97866. this._pointB = new BABYLON.Vector3(0, 0, 0);
  97867. this._pointC = new BABYLON.Vector3(0, 0, 0);
  97868. this._lineA = new BABYLON.Vector3(0, 0, 0);
  97869. this._lineB = new BABYLON.Vector3(0, 0, 0);
  97870. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  97871. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  97872. this._options = options ? options : {};
  97873. var optionCount = 0;
  97874. if (this._options.dragAxis) {
  97875. optionCount++;
  97876. }
  97877. if (this._options.dragPlaneNormal) {
  97878. optionCount++;
  97879. }
  97880. if (optionCount > 1) {
  97881. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  97882. }
  97883. }
  97884. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  97885. /**
  97886. * The name of the behavior
  97887. */
  97888. get: function () {
  97889. return "PointerDrag";
  97890. },
  97891. enumerable: true,
  97892. configurable: true
  97893. });
  97894. /**
  97895. * Initializes the behavior
  97896. */
  97897. PointerDragBehavior.prototype.init = function () { };
  97898. /**
  97899. * Attaches the drag behavior the passed in mesh
  97900. * @param ownerNode The mesh that will be dragged around once attached
  97901. */
  97902. PointerDragBehavior.prototype.attach = function (ownerNode) {
  97903. var _this = this;
  97904. this._scene = ownerNode.getScene();
  97905. this._attachedNode = ownerNode;
  97906. // Initialize drag plane to not interfere with existing scene
  97907. if (!PointerDragBehavior._planeScene) {
  97908. if (this._debugMode) {
  97909. PointerDragBehavior._planeScene = this._scene;
  97910. }
  97911. else {
  97912. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  97913. PointerDragBehavior._planeScene.detachControl();
  97914. this._scene.getEngine().scenes.pop();
  97915. this._scene.onDisposeObservable.addOnce(function () {
  97916. PointerDragBehavior._planeScene.dispose();
  97917. PointerDragBehavior._planeScene = null;
  97918. });
  97919. }
  97920. }
  97921. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  97922. // State of the drag
  97923. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  97924. var pickPredicate = function (m) {
  97925. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  97926. };
  97927. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  97928. if (!_this.enabled) {
  97929. return;
  97930. }
  97931. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  97932. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  97933. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  97934. }
  97935. }
  97936. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  97937. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  97938. _this.releaseDrag();
  97939. }
  97940. }
  97941. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  97942. var pointerId = pointerInfo.event.pointerId;
  97943. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  97944. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  97945. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  97946. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  97947. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  97948. }
  97949. _this.currentDraggingPointerID = pointerId;
  97950. }
  97951. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  97952. if (!_this._lastPointerRay[pointerId]) {
  97953. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  97954. }
  97955. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  97956. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  97957. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  97958. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  97959. _this._moveDrag(pointerInfo.pickInfo.ray);
  97960. }
  97961. }
  97962. }
  97963. });
  97964. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  97965. if (_this._moving && _this.moveAttached) {
  97966. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  97967. // Slowly move mesh to avoid jitter
  97968. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  97969. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  97970. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  97971. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  97972. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  97973. }
  97974. });
  97975. };
  97976. /**
  97977. * Force relase the drag action by code.
  97978. */
  97979. PointerDragBehavior.prototype.releaseDrag = function () {
  97980. this.dragging = false;
  97981. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  97982. this.currentDraggingPointerID = -1;
  97983. this._moving = false;
  97984. // Reattach camera controls
  97985. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  97986. this._scene.activeCamera.attachControl(this._attachedElement, true);
  97987. }
  97988. };
  97989. /**
  97990. * Simulates the start of a pointer drag event on the behavior
  97991. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  97992. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  97993. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  97994. */
  97995. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  97996. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  97997. this._startDrag(pointerId, fromRay, startPickedPoint);
  97998. var lastRay = this._lastPointerRay[pointerId];
  97999. if (pointerId === PointerDragBehavior._AnyMouseID) {
  98000. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  98001. }
  98002. if (lastRay) {
  98003. // if there was a last pointer ray drag the object there
  98004. this._moveDrag(lastRay);
  98005. }
  98006. };
  98007. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  98008. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  98009. return;
  98010. }
  98011. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  98012. // Create start ray from the camera to the object
  98013. if (fromRay) {
  98014. this._startDragRay.direction.copyFrom(fromRay.direction);
  98015. this._startDragRay.origin.copyFrom(fromRay.origin);
  98016. }
  98017. else {
  98018. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  98019. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  98020. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  98021. }
  98022. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  98023. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  98024. if (pickedPoint) {
  98025. this.dragging = true;
  98026. this.currentDraggingPointerID = pointerId;
  98027. this.lastDragPosition.copyFrom(pickedPoint);
  98028. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  98029. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  98030. // Detatch camera controls
  98031. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  98032. if (this._scene.activeCamera.inputs.attachedElement) {
  98033. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  98034. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  98035. }
  98036. else {
  98037. this._attachedElement = null;
  98038. }
  98039. }
  98040. }
  98041. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  98042. };
  98043. PointerDragBehavior.prototype._moveDrag = function (ray) {
  98044. this._moving = true;
  98045. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  98046. if (pickedPoint) {
  98047. if (this.updateDragPlane) {
  98048. this._updateDragPlanePosition(ray, pickedPoint);
  98049. }
  98050. var dragLength = 0;
  98051. // depending on the drag mode option drag accordingly
  98052. if (this._options.dragAxis) {
  98053. // Convert local drag axis to world
  98054. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  98055. // Project delta drag from the drag plane onto the drag axis
  98056. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  98057. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  98058. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  98059. }
  98060. else {
  98061. dragLength = this._dragDelta.length();
  98062. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  98063. }
  98064. this._targetPosition.addInPlace(this._dragDelta);
  98065. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  98066. this.lastDragPosition.copyFrom(pickedPoint);
  98067. }
  98068. };
  98069. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  98070. var _this = this;
  98071. if (!ray) {
  98072. return null;
  98073. }
  98074. // Calculate angle between plane normal and ray
  98075. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  98076. // Correct if ray is casted from oposite side
  98077. if (angle > Math.PI / 2) {
  98078. angle = Math.PI - angle;
  98079. }
  98080. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  98081. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  98082. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  98083. // Invert ray direction along the towards object axis
  98084. this._tmpVector.copyFrom(ray.direction);
  98085. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  98086. this._alternatePickedPoint.normalize();
  98087. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  98088. this._tmpVector.addInPlace(this._alternatePickedPoint);
  98089. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  98090. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  98091. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  98092. this._alternatePickedPoint.addInPlace(this._tmpVector);
  98093. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  98094. return this._alternatePickedPoint;
  98095. }
  98096. else {
  98097. return null;
  98098. }
  98099. }
  98100. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  98101. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  98102. return pickResult.pickedPoint;
  98103. }
  98104. else {
  98105. return null;
  98106. }
  98107. };
  98108. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  98109. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  98110. this._pointA.copyFrom(dragPlanePosition);
  98111. if (this._options.dragAxis) {
  98112. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  98113. // Calculate plane normal in direction of camera but perpendicular to drag axis
  98114. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  98115. ray.origin.subtractToRef(this._pointA, this._pointC);
  98116. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  98117. // Get perpendicular line from direction to camera and drag axis
  98118. this._pointB.subtractToRef(this._pointA, this._lineA);
  98119. this._pointC.subtractToRef(this._pointA, this._lineB);
  98120. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  98121. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  98122. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  98123. this._lookAt.normalize();
  98124. this._dragPlane.position.copyFrom(this._pointA);
  98125. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  98126. this._dragPlane.lookAt(this._lookAt);
  98127. }
  98128. else if (this._options.dragPlaneNormal) {
  98129. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  98130. this._dragPlane.position.copyFrom(this._pointA);
  98131. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  98132. this._dragPlane.lookAt(this._lookAt);
  98133. }
  98134. else {
  98135. this._dragPlane.position.copyFrom(this._pointA);
  98136. this._dragPlane.lookAt(ray.origin);
  98137. }
  98138. this._dragPlane.computeWorldMatrix(true);
  98139. };
  98140. /**
  98141. * Detaches the behavior from the mesh
  98142. */
  98143. PointerDragBehavior.prototype.detach = function () {
  98144. if (this._pointerObserver) {
  98145. this._scene.onPointerObservable.remove(this._pointerObserver);
  98146. }
  98147. if (this._beforeRenderObserver) {
  98148. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  98149. }
  98150. };
  98151. PointerDragBehavior._AnyMouseID = -2;
  98152. return PointerDragBehavior;
  98153. }());
  98154. BABYLON.PointerDragBehavior = PointerDragBehavior;
  98155. })(BABYLON || (BABYLON = {}));
  98156. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  98157. var BABYLON;
  98158. (function (BABYLON) {
  98159. /**
  98160. * A behavior that when attached to a mesh will allow the mesh to be scaled
  98161. */
  98162. var MultiPointerScaleBehavior = /** @class */ (function () {
  98163. /**
  98164. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  98165. */
  98166. function MultiPointerScaleBehavior() {
  98167. this._startDistance = 0;
  98168. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  98169. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  98170. this._sceneRenderObserver = null;
  98171. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  98172. this._dragBehaviorA.moveAttached = false;
  98173. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  98174. this._dragBehaviorB.moveAttached = false;
  98175. }
  98176. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  98177. /**
  98178. * The name of the behavior
  98179. */
  98180. get: function () {
  98181. return "MultiPointerScale";
  98182. },
  98183. enumerable: true,
  98184. configurable: true
  98185. });
  98186. /**
  98187. * Initializes the behavior
  98188. */
  98189. MultiPointerScaleBehavior.prototype.init = function () { };
  98190. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  98191. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  98192. };
  98193. /**
  98194. * Attaches the scale behavior the passed in mesh
  98195. * @param ownerNode The mesh that will be scaled around once attached
  98196. */
  98197. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  98198. var _this = this;
  98199. this._ownerNode = ownerNode;
  98200. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  98201. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  98202. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  98203. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  98204. _this._dragBehaviorA.releaseDrag();
  98205. }
  98206. else {
  98207. _this._initialScale.copyFrom(ownerNode.scaling);
  98208. _this._startDistance = _this._getCurrentDistance();
  98209. }
  98210. }
  98211. });
  98212. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  98213. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  98214. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  98215. _this._dragBehaviorB.releaseDrag();
  98216. }
  98217. else {
  98218. _this._initialScale.copyFrom(ownerNode.scaling);
  98219. _this._startDistance = _this._getCurrentDistance();
  98220. }
  98221. }
  98222. });
  98223. // Once both drag behaviors are active scale based on the distance between the two pointers
  98224. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  98225. behavior.onDragObservable.add(function () {
  98226. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  98227. var ratio = _this._getCurrentDistance() / _this._startDistance;
  98228. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  98229. }
  98230. });
  98231. });
  98232. ownerNode.addBehavior(this._dragBehaviorA);
  98233. ownerNode.addBehavior(this._dragBehaviorB);
  98234. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  98235. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  98236. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  98237. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  98238. if (change.length() > 0.01) {
  98239. ownerNode.scaling.addInPlace(change);
  98240. }
  98241. }
  98242. });
  98243. };
  98244. /**
  98245. * Detaches the behavior from the mesh
  98246. */
  98247. MultiPointerScaleBehavior.prototype.detach = function () {
  98248. var _this = this;
  98249. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  98250. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  98251. behavior.onDragStartObservable.clear();
  98252. behavior.onDragObservable.clear();
  98253. _this._ownerNode.removeBehavior(behavior);
  98254. });
  98255. };
  98256. return MultiPointerScaleBehavior;
  98257. }());
  98258. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  98259. })(BABYLON || (BABYLON = {}));
  98260. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  98261. var BABYLON;
  98262. (function (BABYLON) {
  98263. /**
  98264. * 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
  98265. */
  98266. var SixDofDragBehavior = /** @class */ (function () {
  98267. /**
  98268. * Instantiates 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
  98269. */
  98270. function SixDofDragBehavior() {
  98271. this._sceneRenderObserver = null;
  98272. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  98273. this._moving = false;
  98274. this._startingOrientation = new BABYLON.Quaternion();
  98275. /**
  98276. * 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)
  98277. */
  98278. this.zDragFactor = 3;
  98279. /**
  98280. * If the behavior is currently in a dragging state
  98281. */
  98282. this.dragging = false;
  98283. /**
  98284. * 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)
  98285. */
  98286. this.dragDeltaRatio = 0.2;
  98287. /**
  98288. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  98289. */
  98290. this.currentDraggingPointerID = -1;
  98291. /**
  98292. * If camera controls should be detached during the drag
  98293. */
  98294. this.detachCameraControls = true;
  98295. /**
  98296. * Fires each time a drag starts
  98297. */
  98298. this.onDragStartObservable = new BABYLON.Observable();
  98299. /**
  98300. * Fires each time a drag ends (eg. mouse release after drag)
  98301. */
  98302. this.onDragEndObservable = new BABYLON.Observable();
  98303. }
  98304. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  98305. /**
  98306. * The name of the behavior
  98307. */
  98308. get: function () {
  98309. return "SixDofDrag";
  98310. },
  98311. enumerable: true,
  98312. configurable: true
  98313. });
  98314. /**
  98315. * Initializes the behavior
  98316. */
  98317. SixDofDragBehavior.prototype.init = function () { };
  98318. /**
  98319. * Attaches the scale behavior the passed in mesh
  98320. * @param ownerNode The mesh that will be scaled around once attached
  98321. */
  98322. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  98323. var _this = this;
  98324. this._ownerNode = ownerNode;
  98325. this._scene = this._ownerNode.getScene();
  98326. if (!SixDofDragBehavior._virtualScene) {
  98327. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  98328. this._scene.getEngine().scenes.pop();
  98329. }
  98330. var pickedMesh = null;
  98331. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  98332. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  98333. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  98334. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  98335. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  98336. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  98337. var pickPredicate = function (m) {
  98338. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  98339. };
  98340. var attachedElement = null;
  98341. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  98342. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  98343. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  98344. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  98345. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  98346. }
  98347. pickedMesh = _this._ownerNode;
  98348. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  98349. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  98350. // Set position and orientation of the controller
  98351. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  98352. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  98353. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  98354. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  98355. pickedMesh.computeWorldMatrix();
  98356. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  98357. if (!pickedMesh.rotationQuaternion) {
  98358. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  98359. }
  98360. var oldParent = pickedMesh.parent;
  98361. pickedMesh.setParent(null);
  98362. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  98363. pickedMesh.setParent(oldParent);
  98364. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  98365. // Update state
  98366. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  98367. _this.dragging = true;
  98368. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  98369. // Detatch camera controls
  98370. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  98371. if (_this._scene.activeCamera.inputs.attachedElement) {
  98372. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  98373. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  98374. }
  98375. else {
  98376. attachedElement = null;
  98377. }
  98378. }
  98379. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  98380. _this.onDragStartObservable.notifyObservers({});
  98381. }
  98382. }
  98383. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  98384. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  98385. _this.dragging = false;
  98386. _this._moving = false;
  98387. _this.currentDraggingPointerID = -1;
  98388. pickedMesh = null;
  98389. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  98390. // Reattach camera controls
  98391. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  98392. _this._scene.activeCamera.attachControl(attachedElement, true);
  98393. }
  98394. _this.onDragEndObservable.notifyObservers({});
  98395. }
  98396. }
  98397. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  98398. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  98399. var zDragFactor = _this.zDragFactor;
  98400. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  98401. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  98402. zDragFactor = 0;
  98403. }
  98404. // Calculate controller drag distance in controller space
  98405. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  98406. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  98407. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  98408. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  98409. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  98410. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  98411. if (_this._virtualDragMesh.position.z < 0) {
  98412. _this._virtualDragMesh.position.z = 0;
  98413. }
  98414. // Update the controller position
  98415. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  98416. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  98417. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  98418. // Move the virtualObjectsPosition into the picked mesh's space if needed
  98419. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  98420. if (pickedMesh.parent) {
  98421. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  98422. }
  98423. if (!_this._moving) {
  98424. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  98425. }
  98426. _this._moving = true;
  98427. }
  98428. }
  98429. });
  98430. var tmpQuaternion = new BABYLON.Quaternion();
  98431. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  98432. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  98433. if (_this.dragging && _this._moving && pickedMesh) {
  98434. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  98435. // Slowly move mesh to avoid jitter
  98436. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  98437. // Get change in rotation
  98438. tmpQuaternion.copyFrom(_this._startingOrientation);
  98439. tmpQuaternion.x = -tmpQuaternion.x;
  98440. tmpQuaternion.y = -tmpQuaternion.y;
  98441. tmpQuaternion.z = -tmpQuaternion.z;
  98442. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  98443. // Convert change in rotation to only y axis rotation
  98444. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  98445. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  98446. // Slowly move mesh to avoid jitter
  98447. var oldParent = pickedMesh.parent;
  98448. pickedMesh.setParent(null);
  98449. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  98450. pickedMesh.setParent(oldParent);
  98451. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  98452. }
  98453. });
  98454. };
  98455. /**
  98456. * Detaches the behavior from the mesh
  98457. */
  98458. SixDofDragBehavior.prototype.detach = function () {
  98459. if (this._scene) {
  98460. this._scene.onPointerObservable.remove(this._pointerObserver);
  98461. }
  98462. if (this._ownerNode) {
  98463. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  98464. }
  98465. if (this._virtualOriginMesh) {
  98466. this._virtualOriginMesh.dispose();
  98467. }
  98468. if (this._virtualDragMesh) {
  98469. this._virtualDragMesh.dispose();
  98470. }
  98471. this.onDragEndObservable.clear();
  98472. this.onDragStartObservable.clear();
  98473. };
  98474. return SixDofDragBehavior;
  98475. }());
  98476. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  98477. })(BABYLON || (BABYLON = {}));
  98478. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  98479. var BABYLON;
  98480. (function (BABYLON) {
  98481. /**
  98482. * @hidden
  98483. */
  98484. var FaceDirectionInfo = /** @class */ (function () {
  98485. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  98486. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  98487. if (diff === void 0) { diff = 0; }
  98488. if (ignore === void 0) { ignore = false; }
  98489. this.direction = direction;
  98490. this.rotatedDirection = rotatedDirection;
  98491. this.diff = diff;
  98492. this.ignore = ignore;
  98493. }
  98494. return FaceDirectionInfo;
  98495. }());
  98496. /**
  98497. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  98498. */
  98499. var AttachToBoxBehavior = /** @class */ (function () {
  98500. /**
  98501. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  98502. * @param ui The transform node that should be attched to the mesh
  98503. */
  98504. function AttachToBoxBehavior(ui) {
  98505. this.ui = ui;
  98506. /**
  98507. * The name of the behavior
  98508. */
  98509. this.name = "AttachToBoxBehavior";
  98510. /**
  98511. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  98512. */
  98513. this.distanceAwayFromFace = 0.15;
  98514. /**
  98515. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  98516. */
  98517. this.distanceAwayFromBottomOfFace = 0.15;
  98518. 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))];
  98519. this._tmpMatrix = new BABYLON.Matrix();
  98520. this._tmpVector = new BABYLON.Vector3();
  98521. this._zeroVector = BABYLON.Vector3.Zero();
  98522. this._lookAtTmpMatrix = new BABYLON.Matrix();
  98523. /* Does nothing */
  98524. }
  98525. /**
  98526. * Initializes the behavior
  98527. */
  98528. AttachToBoxBehavior.prototype.init = function () {
  98529. /* Does nothing */
  98530. };
  98531. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  98532. var _this = this;
  98533. // Go over each face and calculate the angle between the face's normal and targetDirection
  98534. this._faceVectors.forEach(function (v) {
  98535. if (!_this._target.rotationQuaternion) {
  98536. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  98537. }
  98538. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  98539. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  98540. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  98541. });
  98542. // Return the face information of the one with the normal closeset to target direction
  98543. return this._faceVectors.reduce(function (min, p) {
  98544. if (min.ignore) {
  98545. return p;
  98546. }
  98547. else if (p.ignore) {
  98548. return min;
  98549. }
  98550. else {
  98551. return min.diff < p.diff ? min : p;
  98552. }
  98553. }, this._faceVectors[0]);
  98554. };
  98555. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  98556. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  98557. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  98558. this._lookAtTmpMatrix.invert();
  98559. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  98560. };
  98561. /**
  98562. * Attaches the AttachToBoxBehavior to the passed in mesh
  98563. * @param target The mesh that the specified node will be attached to
  98564. */
  98565. AttachToBoxBehavior.prototype.attach = function (target) {
  98566. var _this = this;
  98567. this._target = target;
  98568. this._scene = this._target.getScene();
  98569. // Every frame, update the app bars position
  98570. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  98571. if (!_this._scene.activeCamera) {
  98572. return;
  98573. }
  98574. // Find the face closest to the cameras position
  98575. var cameraPos = _this._scene.activeCamera.position;
  98576. if (_this._scene.activeCamera.devicePosition) {
  98577. cameraPos = _this._scene.activeCamera.devicePosition;
  98578. }
  98579. var facing = _this._closestFace(cameraPos.subtract(target.position));
  98580. if (_this._scene.activeCamera.leftCamera) {
  98581. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  98582. }
  98583. else {
  98584. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  98585. }
  98586. // Get camera up direction
  98587. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  98588. // Ignore faces to not select a parrelel face for the up vector of the UI
  98589. _this._faceVectors.forEach(function (v) {
  98590. if (facing.direction.x && v.direction.x) {
  98591. v.ignore = true;
  98592. }
  98593. if (facing.direction.y && v.direction.y) {
  98594. v.ignore = true;
  98595. }
  98596. if (facing.direction.z && v.direction.z) {
  98597. v.ignore = true;
  98598. }
  98599. });
  98600. var facingUp = _this._closestFace(_this._tmpVector);
  98601. // Unignore faces
  98602. _this._faceVectors.forEach(function (v) {
  98603. v.ignore = false;
  98604. });
  98605. // Position the app bar on that face
  98606. _this.ui.position.copyFrom(target.position);
  98607. if (facing.direction.x) {
  98608. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  98609. _this.ui.position.addInPlace(_this._tmpVector);
  98610. }
  98611. if (facing.direction.y) {
  98612. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  98613. _this.ui.position.addInPlace(_this._tmpVector);
  98614. }
  98615. if (facing.direction.z) {
  98616. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  98617. _this.ui.position.addInPlace(_this._tmpVector);
  98618. }
  98619. // Rotate to be oriented properly to the camera
  98620. if (!_this.ui.rotationQuaternion) {
  98621. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  98622. }
  98623. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  98624. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  98625. // Place ui the correct distance from the bottom of the mesh
  98626. if (facingUp.direction.x) {
  98627. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  98628. }
  98629. if (facingUp.direction.y) {
  98630. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  98631. }
  98632. if (facingUp.direction.z) {
  98633. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  98634. }
  98635. _this.ui.position.addInPlace(_this._tmpVector);
  98636. });
  98637. };
  98638. /**
  98639. * Detaches the behavior from the mesh
  98640. */
  98641. AttachToBoxBehavior.prototype.detach = function () {
  98642. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  98643. };
  98644. return AttachToBoxBehavior;
  98645. }());
  98646. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  98647. })(BABYLON || (BABYLON = {}));
  98648. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  98649. var BABYLON;
  98650. (function (BABYLON) {
  98651. /**
  98652. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  98653. */
  98654. var FadeInOutBehavior = /** @class */ (function () {
  98655. /**
  98656. * Instatiates the FadeInOutBehavior
  98657. */
  98658. function FadeInOutBehavior() {
  98659. var _this = this;
  98660. /**
  98661. * Time in milliseconds to delay before fading in (Default: 0)
  98662. */
  98663. this.delay = 0;
  98664. /**
  98665. * Time in milliseconds for the mesh to fade in (Default: 300)
  98666. */
  98667. this.fadeInTime = 300;
  98668. this._millisecondsPerFrame = 1000 / 60;
  98669. this._hovered = false;
  98670. this._hoverValue = 0;
  98671. this._ownerNode = null;
  98672. this._update = function () {
  98673. if (_this._ownerNode) {
  98674. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  98675. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  98676. if (_this._ownerNode.visibility > 1) {
  98677. _this._setAllVisibility(_this._ownerNode, 1);
  98678. _this._hoverValue = _this.fadeInTime + _this.delay;
  98679. return;
  98680. }
  98681. else if (_this._ownerNode.visibility < 0) {
  98682. _this._setAllVisibility(_this._ownerNode, 0);
  98683. if (_this._hoverValue < 0) {
  98684. _this._hoverValue = 0;
  98685. return;
  98686. }
  98687. }
  98688. setTimeout(_this._update, _this._millisecondsPerFrame);
  98689. }
  98690. };
  98691. }
  98692. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  98693. /**
  98694. * The name of the behavior
  98695. */
  98696. get: function () {
  98697. return "FadeInOut";
  98698. },
  98699. enumerable: true,
  98700. configurable: true
  98701. });
  98702. /**
  98703. * Initializes the behavior
  98704. */
  98705. FadeInOutBehavior.prototype.init = function () {
  98706. };
  98707. /**
  98708. * Attaches the fade behavior on the passed in mesh
  98709. * @param ownerNode The mesh that will be faded in/out once attached
  98710. */
  98711. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  98712. this._ownerNode = ownerNode;
  98713. this._setAllVisibility(this._ownerNode, 0);
  98714. };
  98715. /**
  98716. * Detaches the behavior from the mesh
  98717. */
  98718. FadeInOutBehavior.prototype.detach = function () {
  98719. this._ownerNode = null;
  98720. };
  98721. /**
  98722. * Triggers the mesh to begin fading in or out
  98723. * @param value if the object should fade in or out (true to fade in)
  98724. */
  98725. FadeInOutBehavior.prototype.fadeIn = function (value) {
  98726. this._hovered = value;
  98727. this._update();
  98728. };
  98729. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  98730. var _this = this;
  98731. mesh.visibility = value;
  98732. mesh.getChildMeshes().forEach(function (c) {
  98733. _this._setAllVisibility(c, value);
  98734. });
  98735. };
  98736. return FadeInOutBehavior;
  98737. }());
  98738. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  98739. })(BABYLON || (BABYLON = {}));
  98740. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  98741. var BABYLON;
  98742. (function (BABYLON) {
  98743. /**
  98744. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  98745. */
  98746. var Gizmo = /** @class */ (function () {
  98747. /**
  98748. * Creates a gizmo
  98749. * @param gizmoLayer The utility layer the gizmo will be added to
  98750. */
  98751. function Gizmo(
  98752. /** The utility layer the gizmo will be added to */
  98753. gizmoLayer) {
  98754. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  98755. var _this = this;
  98756. this.gizmoLayer = gizmoLayer;
  98757. /**
  98758. * Ratio for the scale of the gizmo (Default: 1)
  98759. */
  98760. this.scaleRatio = 1;
  98761. this._tmpMatrix = new BABYLON.Matrix();
  98762. /**
  98763. * If a custom mesh has been set (Default: false)
  98764. */
  98765. this._customMeshSet = false;
  98766. /**
  98767. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  98768. */
  98769. this.updateGizmoRotationToMatchAttachedMesh = true;
  98770. /**
  98771. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  98772. */
  98773. this.updateGizmoPositionToMatchAttachedMesh = true;
  98774. /**
  98775. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  98776. */
  98777. this._updateScale = true;
  98778. this._interactionsEnabled = true;
  98779. this._tempVector = new BABYLON.Vector3();
  98780. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  98781. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  98782. _this._update();
  98783. });
  98784. this.attachedMesh = null;
  98785. }
  98786. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  98787. /**
  98788. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  98789. * * When set, interactions will be enabled
  98790. */
  98791. get: function () {
  98792. return this._attachedMesh;
  98793. },
  98794. set: function (value) {
  98795. this._attachedMesh = value;
  98796. this._rootMesh.setEnabled(value ? true : false);
  98797. this._attachedMeshChanged(value);
  98798. },
  98799. enumerable: true,
  98800. configurable: true
  98801. });
  98802. /**
  98803. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  98804. * @param mesh The mesh to replace the default mesh of the gizmo
  98805. */
  98806. Gizmo.prototype.setCustomMesh = function (mesh) {
  98807. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  98808. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  98809. }
  98810. this._rootMesh.getChildMeshes().forEach(function (c) {
  98811. c.dispose();
  98812. });
  98813. mesh.parent = this._rootMesh;
  98814. this._customMeshSet = true;
  98815. };
  98816. Gizmo.prototype._attachedMeshChanged = function (value) {
  98817. };
  98818. /**
  98819. * @hidden
  98820. * Updates the gizmo to match the attached mesh's position/rotation
  98821. */
  98822. Gizmo.prototype._update = function () {
  98823. if (this.attachedMesh) {
  98824. if (this.updateGizmoRotationToMatchAttachedMesh) {
  98825. if (!this._rootMesh.rotationQuaternion) {
  98826. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  98827. }
  98828. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  98829. this._tempVector.copyFrom(this.attachedMesh.scaling);
  98830. if (this.attachedMesh.scaling.x < 0) {
  98831. this.attachedMesh.scaling.x *= -1;
  98832. }
  98833. if (this.attachedMesh.scaling.y < 0) {
  98834. this.attachedMesh.scaling.y *= -1;
  98835. }
  98836. if (this.attachedMesh.scaling.z < 0) {
  98837. this.attachedMesh.scaling.z *= -1;
  98838. }
  98839. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  98840. this.attachedMesh.scaling.copyFrom(this._tempVector);
  98841. this.attachedMesh.computeWorldMatrix();
  98842. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  98843. }
  98844. else if (this._rootMesh.rotationQuaternion) {
  98845. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  98846. }
  98847. if (this.updateGizmoPositionToMatchAttachedMesh) {
  98848. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  98849. }
  98850. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  98851. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  98852. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  98853. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  98854. }
  98855. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  98856. var dist = this._tempVector.length() * this.scaleRatio;
  98857. this._rootMesh.scaling.set(dist, dist, dist);
  98858. }
  98859. }
  98860. };
  98861. /**
  98862. * Disposes of the gizmo
  98863. */
  98864. Gizmo.prototype.dispose = function () {
  98865. this._rootMesh.dispose();
  98866. if (this._beforeRenderObserver) {
  98867. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  98868. }
  98869. };
  98870. return Gizmo;
  98871. }());
  98872. BABYLON.Gizmo = Gizmo;
  98873. })(BABYLON || (BABYLON = {}));
  98874. //# sourceMappingURL=babylon.gizmo.js.map
  98875. var BABYLON;
  98876. (function (BABYLON) {
  98877. /**
  98878. * Single axis drag gizmo
  98879. */
  98880. var AxisDragGizmo = /** @class */ (function (_super) {
  98881. __extends(AxisDragGizmo, _super);
  98882. /**
  98883. * Creates an AxisDragGizmo
  98884. * @param gizmoLayer The utility layer the gizmo will be added to
  98885. * @param dragAxis The axis which the gizmo will be able to drag on
  98886. * @param color The color of the gizmo
  98887. */
  98888. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  98889. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  98890. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  98891. var _this = _super.call(this, gizmoLayer) || this;
  98892. _this._pointerObserver = null;
  98893. /**
  98894. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  98895. */
  98896. _this.snapDistance = 0;
  98897. /**
  98898. * Event that fires each time the gizmo snaps to a new location.
  98899. * * snapDistance is the the change in distance
  98900. */
  98901. _this.onSnapObservable = new BABYLON.Observable();
  98902. // Create Material
  98903. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98904. coloredMaterial.disableLighting = true;
  98905. coloredMaterial.emissiveColor = color;
  98906. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  98907. hoverMaterial.disableLighting = true;
  98908. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  98909. // Build mesh on root node
  98910. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  98911. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  98912. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  98913. arrowTail.color = coloredMaterial.emissiveColor;
  98914. arrow.addChild(arrowMesh);
  98915. arrow.addChild(arrowTail);
  98916. // Position arrow pointing in its drag axis
  98917. arrowMesh.scaling.scaleInPlace(0.05);
  98918. arrowMesh.material = coloredMaterial;
  98919. arrowMesh.rotation.x = Math.PI / 2;
  98920. arrowMesh.position.z += 0.3;
  98921. arrowTail.scaling.scaleInPlace(0.26);
  98922. arrowTail.rotation.x = Math.PI / 2;
  98923. arrowTail.material = coloredMaterial;
  98924. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  98925. arrow.scaling.scaleInPlace(1 / 3);
  98926. _this._rootMesh.addChild(arrow);
  98927. var currentSnapDragDistance = 0;
  98928. var tmpVector = new BABYLON.Vector3();
  98929. var tmpSnapEvent = { snapDistance: 0 };
  98930. // Add drag behavior to handle events when the gizmo is dragged
  98931. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  98932. _this.dragBehavior.moveAttached = false;
  98933. _this._rootMesh.addBehavior(_this.dragBehavior);
  98934. var localDelta = new BABYLON.Vector3();
  98935. var tmpMatrix = new BABYLON.Matrix();
  98936. _this.dragBehavior.onDragObservable.add(function (event) {
  98937. if (_this.attachedMesh) {
  98938. // Convert delta to local translation if it has a parent
  98939. if (_this.attachedMesh.parent) {
  98940. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  98941. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  98942. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  98943. }
  98944. else {
  98945. localDelta.copyFrom(event.delta);
  98946. }
  98947. // Snapping logic
  98948. if (_this.snapDistance == 0) {
  98949. _this.attachedMesh.position.addInPlace(localDelta);
  98950. }
  98951. else {
  98952. currentSnapDragDistance += event.dragDistance;
  98953. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  98954. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  98955. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  98956. localDelta.normalizeToRef(tmpVector);
  98957. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  98958. _this.attachedMesh.position.addInPlace(tmpVector);
  98959. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  98960. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  98961. }
  98962. }
  98963. }
  98964. });
  98965. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  98966. if (_this._customMeshSet) {
  98967. return;
  98968. }
  98969. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  98970. var material = isHovered ? hoverMaterial : coloredMaterial;
  98971. _this._rootMesh.getChildMeshes().forEach(function (m) {
  98972. m.material = material;
  98973. if (m.color) {
  98974. m.color = material.emissiveColor;
  98975. }
  98976. });
  98977. });
  98978. return _this;
  98979. }
  98980. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  98981. if (this.dragBehavior) {
  98982. this.dragBehavior.enabled = value ? true : false;
  98983. }
  98984. };
  98985. /**
  98986. * Disposes of the gizmo
  98987. */
  98988. AxisDragGizmo.prototype.dispose = function () {
  98989. this.onSnapObservable.clear();
  98990. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  98991. this.dragBehavior.detach();
  98992. _super.prototype.dispose.call(this);
  98993. };
  98994. return AxisDragGizmo;
  98995. }(BABYLON.Gizmo));
  98996. BABYLON.AxisDragGizmo = AxisDragGizmo;
  98997. })(BABYLON || (BABYLON = {}));
  98998. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  98999. var BABYLON;
  99000. (function (BABYLON) {
  99001. /**
  99002. * Single axis scale gizmo
  99003. */
  99004. var AxisScaleGizmo = /** @class */ (function (_super) {
  99005. __extends(AxisScaleGizmo, _super);
  99006. /**
  99007. * Creates an AxisScaleGizmo
  99008. * @param gizmoLayer The utility layer the gizmo will be added to
  99009. * @param dragAxis The axis which the gizmo will be able to scale on
  99010. * @param color The color of the gizmo
  99011. */
  99012. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  99013. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  99014. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  99015. var _this = _super.call(this, gizmoLayer) || this;
  99016. _this._pointerObserver = null;
  99017. /**
  99018. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  99019. */
  99020. _this.snapDistance = 0;
  99021. /**
  99022. * Event that fires each time the gizmo snaps to a new location.
  99023. * * snapDistance is the the change in distance
  99024. */
  99025. _this.onSnapObservable = new BABYLON.Observable();
  99026. /**
  99027. * If the scaling operation should be done on all axis (default: false)
  99028. */
  99029. _this.uniformScaling = false;
  99030. // Create Material
  99031. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  99032. _this._coloredMaterial.disableLighting = true;
  99033. _this._coloredMaterial.emissiveColor = color;
  99034. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  99035. hoverMaterial.disableLighting = true;
  99036. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  99037. // Build mesh on root node
  99038. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  99039. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  99040. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  99041. arrowTail.color = _this._coloredMaterial.emissiveColor;
  99042. arrow.addChild(arrowMesh);
  99043. arrow.addChild(arrowTail);
  99044. // Position arrow pointing in its drag axis
  99045. arrowMesh.scaling.scaleInPlace(0.1);
  99046. arrowMesh.material = _this._coloredMaterial;
  99047. arrowMesh.rotation.x = Math.PI / 2;
  99048. arrowMesh.position.z += 0.3;
  99049. arrowTail.scaling.scaleInPlace(0.26);
  99050. arrowTail.rotation.x = Math.PI / 2;
  99051. arrowTail.material = _this._coloredMaterial;
  99052. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  99053. _this._rootMesh.addChild(arrow);
  99054. arrow.scaling.scaleInPlace(1 / 3);
  99055. // Add drag behavior to handle events when the gizmo is dragged
  99056. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  99057. _this.dragBehavior.moveAttached = false;
  99058. _this._rootMesh.addBehavior(_this.dragBehavior);
  99059. var currentSnapDragDistance = 0;
  99060. var tmpVector = new BABYLON.Vector3();
  99061. var tmpSnapEvent = { snapDistance: 0 };
  99062. _this.dragBehavior.onDragObservable.add(function (event) {
  99063. if (_this.attachedMesh) {
  99064. // Snapping logic
  99065. var snapped = false;
  99066. var dragSteps = 0;
  99067. if (_this.uniformScaling) {
  99068. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  99069. if (tmpVector.y < 0) {
  99070. tmpVector.scaleInPlace(-1);
  99071. }
  99072. }
  99073. else {
  99074. tmpVector.copyFrom(dragAxis);
  99075. }
  99076. if (_this.snapDistance == 0) {
  99077. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  99078. }
  99079. else {
  99080. currentSnapDragDistance += event.dragDistance;
  99081. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  99082. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  99083. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  99084. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  99085. snapped = true;
  99086. }
  99087. else {
  99088. tmpVector.scaleInPlace(0);
  99089. }
  99090. }
  99091. _this.attachedMesh.scaling.addInPlace(tmpVector);
  99092. if (snapped) {
  99093. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  99094. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  99095. }
  99096. }
  99097. });
  99098. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  99099. if (_this._customMeshSet) {
  99100. return;
  99101. }
  99102. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  99103. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  99104. _this._rootMesh.getChildMeshes().forEach(function (m) {
  99105. m.material = material;
  99106. if (m.color) {
  99107. m.color = material.emissiveColor;
  99108. }
  99109. });
  99110. });
  99111. return _this;
  99112. }
  99113. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  99114. if (this.dragBehavior) {
  99115. this.dragBehavior.enabled = value ? true : false;
  99116. }
  99117. };
  99118. /**
  99119. * Disposes of the gizmo
  99120. */
  99121. AxisScaleGizmo.prototype.dispose = function () {
  99122. this.onSnapObservable.clear();
  99123. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  99124. this.dragBehavior.detach();
  99125. _super.prototype.dispose.call(this);
  99126. };
  99127. /**
  99128. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  99129. * @param mesh The mesh to replace the default mesh of the gizmo
  99130. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  99131. */
  99132. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  99133. var _this = this;
  99134. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  99135. _super.prototype.setCustomMesh.call(this, mesh);
  99136. if (useGizmoMaterial) {
  99137. this._rootMesh.getChildMeshes().forEach(function (m) {
  99138. m.material = _this._coloredMaterial;
  99139. if (m.color) {
  99140. m.color = _this._coloredMaterial.emissiveColor;
  99141. }
  99142. });
  99143. this._customMeshSet = false;
  99144. }
  99145. };
  99146. return AxisScaleGizmo;
  99147. }(BABYLON.Gizmo));
  99148. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  99149. })(BABYLON || (BABYLON = {}));
  99150. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  99151. var BABYLON;
  99152. (function (BABYLON) {
  99153. /**
  99154. * Single plane rotation gizmo
  99155. */
  99156. var PlaneRotationGizmo = /** @class */ (function (_super) {
  99157. __extends(PlaneRotationGizmo, _super);
  99158. /**
  99159. * Creates a PlaneRotationGizmo
  99160. * @param gizmoLayer The utility layer the gizmo will be added to
  99161. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  99162. * @param color The color of the gizmo
  99163. */
  99164. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  99165. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  99166. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  99167. var _this = _super.call(this, gizmoLayer) || this;
  99168. _this._pointerObserver = null;
  99169. /**
  99170. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  99171. */
  99172. _this.snapDistance = 0;
  99173. /**
  99174. * Event that fires each time the gizmo snaps to a new location.
  99175. * * snapDistance is the the change in distance
  99176. */
  99177. _this.onSnapObservable = new BABYLON.Observable();
  99178. // Create Material
  99179. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  99180. coloredMaterial.disableLighting = true;
  99181. coloredMaterial.emissiveColor = color;
  99182. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  99183. hoverMaterial.disableLighting = true;
  99184. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  99185. // Build mesh on root node
  99186. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  99187. // Create circle out of lines
  99188. var tessellation = 20;
  99189. var radius = 0.8;
  99190. var points = new Array();
  99191. for (var i = 0; i < tessellation; i++) {
  99192. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  99193. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  99194. }
  99195. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  99196. rotationMesh.color = coloredMaterial.emissiveColor;
  99197. // Position arrow pointing in its drag axis
  99198. rotationMesh.scaling.scaleInPlace(0.26);
  99199. rotationMesh.material = coloredMaterial;
  99200. rotationMesh.rotation.x = Math.PI / 2;
  99201. parentMesh.addChild(rotationMesh);
  99202. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  99203. _this._rootMesh.addChild(parentMesh);
  99204. parentMesh.scaling.scaleInPlace(1 / 3);
  99205. // Add drag behavior to handle events when the gizmo is dragged
  99206. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  99207. _this.dragBehavior.moveAttached = false;
  99208. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  99209. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  99210. _this._rootMesh.addBehavior(_this.dragBehavior);
  99211. var lastDragPosition = new BABYLON.Vector3();
  99212. _this.dragBehavior.onDragStartObservable.add(function (e) {
  99213. if (_this.attachedMesh) {
  99214. lastDragPosition.copyFrom(e.dragPlanePoint);
  99215. }
  99216. });
  99217. var rotationMatrix = new BABYLON.Matrix();
  99218. var planeNormalTowardsCamera = new BABYLON.Vector3();
  99219. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  99220. var tmpSnapEvent = { snapDistance: 0 };
  99221. var currentSnapDragDistance = 0;
  99222. var tmpMatrix = new BABYLON.Matrix();
  99223. var tmpVector = new BABYLON.Vector3();
  99224. var amountToRotate = new BABYLON.Quaternion();
  99225. _this.dragBehavior.onDragObservable.add(function (event) {
  99226. if (_this.attachedMesh) {
  99227. if (!_this.attachedMesh.rotationQuaternion) {
  99228. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  99229. }
  99230. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  99231. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  99232. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  99233. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  99234. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  99235. var angle = Math.atan2(cross.length(), dot);
  99236. planeNormalTowardsCamera.copyFrom(planeNormal);
  99237. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  99238. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  99239. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  99240. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  99241. }
  99242. // Flip up vector depending on which side the camera is on
  99243. if (gizmoLayer.utilityLayerScene.activeCamera) {
  99244. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  99245. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  99246. planeNormalTowardsCamera.scaleInPlace(-1);
  99247. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  99248. }
  99249. }
  99250. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  99251. if (halfCircleSide)
  99252. angle = -angle;
  99253. // Snapping logic
  99254. var snapped = false;
  99255. if (_this.snapDistance != 0) {
  99256. currentSnapDragDistance += angle;
  99257. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  99258. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  99259. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  99260. angle = _this.snapDistance * dragSteps;
  99261. snapped = true;
  99262. }
  99263. else {
  99264. angle = 0;
  99265. }
  99266. }
  99267. // If the mesh has a parent, convert needed world rotation to local rotation
  99268. tmpMatrix.reset();
  99269. if (_this.attachedMesh.parent) {
  99270. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  99271. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  99272. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  99273. }
  99274. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  99275. var quaternionCoefficient = Math.sin(angle / 2);
  99276. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  99277. // 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
  99278. if (tmpMatrix.determinant() > 0) {
  99279. amountToRotate.toEulerAnglesToRef(tmpVector);
  99280. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  99281. }
  99282. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  99283. // Rotate selected mesh quaternion over fixed axis
  99284. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  99285. }
  99286. else {
  99287. // Rotate selected mesh quaternion over rotated axis
  99288. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  99289. }
  99290. lastDragPosition.copyFrom(event.dragPlanePoint);
  99291. if (snapped) {
  99292. tmpSnapEvent.snapDistance = angle;
  99293. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  99294. }
  99295. }
  99296. });
  99297. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  99298. if (_this._customMeshSet) {
  99299. return;
  99300. }
  99301. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  99302. var material = isHovered ? hoverMaterial : coloredMaterial;
  99303. _this._rootMesh.getChildMeshes().forEach(function (m) {
  99304. m.material = material;
  99305. if (m.color) {
  99306. m.color = material.emissiveColor;
  99307. }
  99308. });
  99309. });
  99310. return _this;
  99311. }
  99312. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  99313. if (this.dragBehavior) {
  99314. this.dragBehavior.enabled = value ? true : false;
  99315. }
  99316. };
  99317. /**
  99318. * Disposes of the gizmo
  99319. */
  99320. PlaneRotationGizmo.prototype.dispose = function () {
  99321. this.onSnapObservable.clear();
  99322. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  99323. this.dragBehavior.detach();
  99324. _super.prototype.dispose.call(this);
  99325. };
  99326. return PlaneRotationGizmo;
  99327. }(BABYLON.Gizmo));
  99328. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  99329. })(BABYLON || (BABYLON = {}));
  99330. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  99331. var BABYLON;
  99332. (function (BABYLON) {
  99333. /**
  99334. * Gizmo that enables dragging a mesh along 3 axis
  99335. */
  99336. var PositionGizmo = /** @class */ (function (_super) {
  99337. __extends(PositionGizmo, _super);
  99338. /**
  99339. * Creates a PositionGizmo
  99340. * @param gizmoLayer The utility layer the gizmo will be added to
  99341. */
  99342. function PositionGizmo(gizmoLayer) {
  99343. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  99344. var _this = _super.call(this, gizmoLayer) || this;
  99345. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  99346. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  99347. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  99348. _this.attachedMesh = null;
  99349. return _this;
  99350. }
  99351. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  99352. set: function (mesh) {
  99353. if (this.xGizmo) {
  99354. this.xGizmo.attachedMesh = mesh;
  99355. this.yGizmo.attachedMesh = mesh;
  99356. this.zGizmo.attachedMesh = mesh;
  99357. }
  99358. },
  99359. enumerable: true,
  99360. configurable: true
  99361. });
  99362. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  99363. get: function () {
  99364. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  99365. },
  99366. set: function (value) {
  99367. if (this.xGizmo) {
  99368. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99369. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99370. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99371. }
  99372. },
  99373. enumerable: true,
  99374. configurable: true
  99375. });
  99376. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  99377. get: function () {
  99378. return this.xGizmo.snapDistance;
  99379. },
  99380. /**
  99381. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  99382. */
  99383. set: function (value) {
  99384. if (this.xGizmo) {
  99385. this.xGizmo.snapDistance = value;
  99386. this.yGizmo.snapDistance = value;
  99387. this.zGizmo.snapDistance = value;
  99388. }
  99389. },
  99390. enumerable: true,
  99391. configurable: true
  99392. });
  99393. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  99394. get: function () {
  99395. return this.xGizmo.scaleRatio;
  99396. },
  99397. /**
  99398. * Ratio for the scale of the gizmo (Default: 1)
  99399. */
  99400. set: function (value) {
  99401. if (this.xGizmo) {
  99402. this.xGizmo.scaleRatio = value;
  99403. this.yGizmo.scaleRatio = value;
  99404. this.zGizmo.scaleRatio = value;
  99405. }
  99406. },
  99407. enumerable: true,
  99408. configurable: true
  99409. });
  99410. /**
  99411. * Disposes of the gizmo
  99412. */
  99413. PositionGizmo.prototype.dispose = function () {
  99414. this.xGizmo.dispose();
  99415. this.yGizmo.dispose();
  99416. this.zGizmo.dispose();
  99417. };
  99418. /**
  99419. * CustomMeshes are not supported by this gizmo
  99420. * @param mesh The mesh to replace the default mesh of the gizmo
  99421. */
  99422. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  99423. 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)");
  99424. };
  99425. return PositionGizmo;
  99426. }(BABYLON.Gizmo));
  99427. BABYLON.PositionGizmo = PositionGizmo;
  99428. })(BABYLON || (BABYLON = {}));
  99429. //# sourceMappingURL=babylon.positionGizmo.js.map
  99430. var BABYLON;
  99431. (function (BABYLON) {
  99432. /**
  99433. * Gizmo that enables rotating a mesh along 3 axis
  99434. */
  99435. var RotationGizmo = /** @class */ (function (_super) {
  99436. __extends(RotationGizmo, _super);
  99437. /**
  99438. * Creates a RotationGizmo
  99439. * @param gizmoLayer The utility layer the gizmo will be added to
  99440. */
  99441. function RotationGizmo(gizmoLayer) {
  99442. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  99443. var _this = _super.call(this, gizmoLayer) || this;
  99444. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  99445. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  99446. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  99447. _this.attachedMesh = null;
  99448. return _this;
  99449. }
  99450. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  99451. set: function (mesh) {
  99452. if (this.xGizmo) {
  99453. this.xGizmo.attachedMesh = mesh;
  99454. this.yGizmo.attachedMesh = mesh;
  99455. this.zGizmo.attachedMesh = mesh;
  99456. }
  99457. },
  99458. enumerable: true,
  99459. configurable: true
  99460. });
  99461. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  99462. get: function () {
  99463. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  99464. },
  99465. set: function (value) {
  99466. if (this.xGizmo) {
  99467. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99468. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99469. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99470. }
  99471. },
  99472. enumerable: true,
  99473. configurable: true
  99474. });
  99475. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  99476. get: function () {
  99477. return this.xGizmo.snapDistance;
  99478. },
  99479. /**
  99480. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  99481. */
  99482. set: function (value) {
  99483. if (this.xGizmo) {
  99484. this.xGizmo.snapDistance = value;
  99485. this.yGizmo.snapDistance = value;
  99486. this.zGizmo.snapDistance = value;
  99487. }
  99488. },
  99489. enumerable: true,
  99490. configurable: true
  99491. });
  99492. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  99493. get: function () {
  99494. return this.xGizmo.scaleRatio;
  99495. },
  99496. /**
  99497. * Ratio for the scale of the gizmo (Default: 1)
  99498. */
  99499. set: function (value) {
  99500. if (this.xGizmo) {
  99501. this.xGizmo.scaleRatio = value;
  99502. this.yGizmo.scaleRatio = value;
  99503. this.zGizmo.scaleRatio = value;
  99504. }
  99505. },
  99506. enumerable: true,
  99507. configurable: true
  99508. });
  99509. /**
  99510. * Disposes of the gizmo
  99511. */
  99512. RotationGizmo.prototype.dispose = function () {
  99513. this.xGizmo.dispose();
  99514. this.yGizmo.dispose();
  99515. this.zGizmo.dispose();
  99516. };
  99517. /**
  99518. * CustomMeshes are not supported by this gizmo
  99519. * @param mesh The mesh to replace the default mesh of the gizmo
  99520. */
  99521. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  99522. 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)");
  99523. };
  99524. return RotationGizmo;
  99525. }(BABYLON.Gizmo));
  99526. BABYLON.RotationGizmo = RotationGizmo;
  99527. })(BABYLON || (BABYLON = {}));
  99528. //# sourceMappingURL=babylon.rotationGizmo.js.map
  99529. var BABYLON;
  99530. (function (BABYLON) {
  99531. /**
  99532. * Gizmo that enables scaling a mesh along 3 axis
  99533. */
  99534. var ScaleGizmo = /** @class */ (function (_super) {
  99535. __extends(ScaleGizmo, _super);
  99536. /**
  99537. * Creates a ScaleGizmo
  99538. * @param gizmoLayer The utility layer the gizmo will be added to
  99539. */
  99540. function ScaleGizmo(gizmoLayer) {
  99541. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  99542. var _this = _super.call(this, gizmoLayer) || this;
  99543. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  99544. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  99545. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  99546. // Create uniform scale gizmo
  99547. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  99548. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  99549. _this.uniformScaleGizmo.uniformScaling = true;
  99550. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  99551. octahedron.scaling.scaleInPlace(0.007);
  99552. _this.uniformScaleGizmo.setCustomMesh(octahedron, true);
  99553. _this.attachedMesh = null;
  99554. return _this;
  99555. }
  99556. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  99557. set: function (mesh) {
  99558. if (this.xGizmo) {
  99559. this.xGizmo.attachedMesh = mesh;
  99560. this.yGizmo.attachedMesh = mesh;
  99561. this.zGizmo.attachedMesh = mesh;
  99562. this.uniformScaleGizmo.attachedMesh = mesh;
  99563. }
  99564. },
  99565. enumerable: true,
  99566. configurable: true
  99567. });
  99568. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  99569. get: function () {
  99570. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  99571. },
  99572. set: function (value) {
  99573. if (this.xGizmo) {
  99574. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99575. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99576. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  99577. }
  99578. },
  99579. enumerable: true,
  99580. configurable: true
  99581. });
  99582. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  99583. get: function () {
  99584. return this.xGizmo.snapDistance;
  99585. },
  99586. /**
  99587. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  99588. */
  99589. set: function (value) {
  99590. if (this.xGizmo) {
  99591. this.xGizmo.snapDistance = value;
  99592. this.yGizmo.snapDistance = value;
  99593. this.zGizmo.snapDistance = value;
  99594. this.uniformScaleGizmo.snapDistance = value;
  99595. }
  99596. },
  99597. enumerable: true,
  99598. configurable: true
  99599. });
  99600. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  99601. get: function () {
  99602. return this.xGizmo.scaleRatio;
  99603. },
  99604. /**
  99605. * Ratio for the scale of the gizmo (Default: 1)
  99606. */
  99607. set: function (value) {
  99608. if (this.xGizmo) {
  99609. this.xGizmo.scaleRatio = value;
  99610. this.yGizmo.scaleRatio = value;
  99611. this.zGizmo.scaleRatio = value;
  99612. this.uniformScaleGizmo.scaleRatio = value;
  99613. }
  99614. },
  99615. enumerable: true,
  99616. configurable: true
  99617. });
  99618. /**
  99619. * Disposes of the gizmo
  99620. */
  99621. ScaleGizmo.prototype.dispose = function () {
  99622. this.xGizmo.dispose();
  99623. this.yGizmo.dispose();
  99624. this.zGizmo.dispose();
  99625. this.uniformScaleGizmo.dispose();
  99626. };
  99627. return ScaleGizmo;
  99628. }(BABYLON.Gizmo));
  99629. BABYLON.ScaleGizmo = ScaleGizmo;
  99630. })(BABYLON || (BABYLON = {}));
  99631. //# sourceMappingURL=babylon.scaleGizmo.js.map
  99632. var BABYLON;
  99633. (function (BABYLON) {
  99634. /**
  99635. * Bounding box gizmo
  99636. */
  99637. var BoundingBoxGizmo = /** @class */ (function (_super) {
  99638. __extends(BoundingBoxGizmo, _super);
  99639. /**
  99640. * Creates an BoundingBoxGizmo
  99641. * @param gizmoLayer The utility layer the gizmo will be added to
  99642. * @param color The color of the gizmo
  99643. */
  99644. function BoundingBoxGizmo(color, gizmoLayer) {
  99645. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  99646. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  99647. var _this = _super.call(this, gizmoLayer) || this;
  99648. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  99649. _this._renderObserver = null;
  99650. _this._pointerObserver = null;
  99651. _this._scaleDragSpeed = 0.2;
  99652. _this._tmpQuaternion = new BABYLON.Quaternion();
  99653. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  99654. _this._tmpRotationMatrix = new BABYLON.Matrix();
  99655. /**
  99656. * 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)
  99657. */
  99658. _this.ignoreChildren = false;
  99659. /**
  99660. * 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)
  99661. */
  99662. _this.includeChildPredicate = null;
  99663. /**
  99664. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  99665. */
  99666. _this.rotationSphereSize = 0.1;
  99667. /**
  99668. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  99669. */
  99670. _this.scaleBoxSize = 0.1;
  99671. /**
  99672. * 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)
  99673. */
  99674. _this.fixedDragMeshScreenSize = false;
  99675. /**
  99676. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  99677. */
  99678. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  99679. /**
  99680. * Fired when a rotation sphere or scale box is dragged
  99681. */
  99682. _this.onDragStartObservable = new BABYLON.Observable();
  99683. /**
  99684. * Fired when a scale box is dragged
  99685. */
  99686. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  99687. /**
  99688. * Fired when a scale box drag is ended
  99689. */
  99690. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  99691. /**
  99692. * Fired when a rotation sphere is dragged
  99693. */
  99694. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  99695. /**
  99696. * Fired when a rotation sphere drag is ended
  99697. */
  99698. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  99699. /**
  99700. * 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)
  99701. */
  99702. _this.scalePivot = null;
  99703. _this._existingMeshScale = new BABYLON.Vector3();
  99704. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  99705. _this._updateScale = false;
  99706. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  99707. // Create Materials
  99708. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  99709. coloredMaterial.disableLighting = true;
  99710. coloredMaterial.emissiveColor = color;
  99711. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  99712. hoverColoredMaterial.disableLighting = true;
  99713. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  99714. // Build bounding box out of lines
  99715. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  99716. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  99717. var lines = [];
  99718. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  99719. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  99720. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  99721. 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));
  99722. 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));
  99723. 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));
  99724. 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));
  99725. 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));
  99726. 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));
  99727. 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));
  99728. 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));
  99729. 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));
  99730. lines.forEach(function (l) {
  99731. l.color = color;
  99732. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  99733. l.isPickable = false;
  99734. _this._lineBoundingBox.addChild(l);
  99735. });
  99736. _this._rootMesh.addChild(_this._lineBoundingBox);
  99737. // Create rotation spheres
  99738. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  99739. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  99740. var _loop_1 = function (i_1) {
  99741. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  99742. sphere.rotationQuaternion = new BABYLON.Quaternion();
  99743. sphere.material = coloredMaterial;
  99744. // Drag behavior
  99745. _dragBehavior = new BABYLON.PointerDragBehavior({});
  99746. _dragBehavior.moveAttached = false;
  99747. _dragBehavior.updateDragPlane = false;
  99748. sphere.addBehavior(_dragBehavior);
  99749. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  99750. var totalTurnAmountOfDrag = 0;
  99751. _dragBehavior.onDragStartObservable.add(function (event) {
  99752. startingTurnDirection.copyFrom(sphere.forward);
  99753. totalTurnAmountOfDrag = 0;
  99754. });
  99755. _dragBehavior.onDragObservable.add(function (event) {
  99756. _this.onRotationSphereDragObservable.notifyObservers({});
  99757. if (_this.attachedMesh) {
  99758. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  99759. var worldDragDirection = startingTurnDirection;
  99760. // Project the world right on to the drag plane
  99761. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  99762. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  99763. // project drag delta on to the resulting drag axis and rotate based on that
  99764. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  99765. // Make rotation relative to size of mesh.
  99766. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  99767. // Rotate based on axis
  99768. if (!_this.attachedMesh.rotationQuaternion) {
  99769. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  99770. }
  99771. if (!_this._anchorMesh.rotationQuaternion) {
  99772. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  99773. }
  99774. // Do not allow the object to turn more than a full circle
  99775. totalTurnAmountOfDrag += projectDist;
  99776. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  99777. if (i_1 >= 8) {
  99778. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  99779. }
  99780. else if (i_1 >= 4) {
  99781. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  99782. }
  99783. else {
  99784. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  99785. }
  99786. // Rotate around center of bounding box
  99787. _this._anchorMesh.addChild(_this.attachedMesh);
  99788. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  99789. _this._anchorMesh.removeChild(_this.attachedMesh);
  99790. }
  99791. _this.updateBoundingBox();
  99792. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  99793. }
  99794. });
  99795. // Selection/deselection
  99796. _dragBehavior.onDragStartObservable.add(function () {
  99797. _this.onDragStartObservable.notifyObservers({});
  99798. _this._selectNode(sphere);
  99799. });
  99800. _dragBehavior.onDragEndObservable.add(function () {
  99801. _this.onRotationSphereDragEndObservable.notifyObservers({});
  99802. _this._selectNode(null);
  99803. });
  99804. this_1._rotateSpheresParent.addChild(sphere);
  99805. };
  99806. var this_1 = this, _dragBehavior;
  99807. for (var i_1 = 0; i_1 < 12; i_1++) {
  99808. _loop_1(i_1);
  99809. }
  99810. _this._rootMesh.addChild(_this._rotateSpheresParent);
  99811. // Create scale cubes
  99812. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  99813. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  99814. for (var i = 0; i < 2; i++) {
  99815. for (var j = 0; j < 2; j++) {
  99816. var _loop_2 = function () {
  99817. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  99818. box.material = coloredMaterial;
  99819. // Dragging logic
  99820. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  99821. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  99822. _dragBehavior.moveAttached = false;
  99823. box.addBehavior(_dragBehavior);
  99824. _dragBehavior.onDragObservable.add(function (event) {
  99825. _this.onScaleBoxDragObservable.notifyObservers({});
  99826. if (_this.attachedMesh) {
  99827. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  99828. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  99829. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  99830. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  99831. _this.updateBoundingBox();
  99832. if (_this.scalePivot) {
  99833. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  99834. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  99835. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  99836. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  99837. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  99838. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  99839. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  99840. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  99841. }
  99842. else {
  99843. // Scale from the position of the opposite corner
  99844. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  99845. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  99846. }
  99847. _this._anchorMesh.addChild(_this.attachedMesh);
  99848. _this._anchorMesh.scaling.addInPlace(deltaScale);
  99849. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  99850. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  99851. }
  99852. _this._anchorMesh.removeChild(_this.attachedMesh);
  99853. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  99854. }
  99855. });
  99856. // Selection/deselection
  99857. _dragBehavior.onDragStartObservable.add(function () {
  99858. _this.onDragStartObservable.notifyObservers({});
  99859. _this._selectNode(box);
  99860. });
  99861. _dragBehavior.onDragEndObservable.add(function () {
  99862. _this.onScaleBoxDragEndObservable.notifyObservers({});
  99863. _this._selectNode(null);
  99864. });
  99865. this_2._scaleBoxesParent.addChild(box);
  99866. };
  99867. var this_2 = this, _dragBehavior;
  99868. for (var k = 0; k < 2; k++) {
  99869. _loop_2();
  99870. }
  99871. }
  99872. }
  99873. _this._rootMesh.addChild(_this._scaleBoxesParent);
  99874. // Hover color change
  99875. var pointerIds = new Array();
  99876. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  99877. if (!pointerIds[pointerInfo.event.pointerId]) {
  99878. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  99879. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  99880. pointerIds[pointerInfo.event.pointerId] = mesh;
  99881. mesh.material = hoverColoredMaterial;
  99882. }
  99883. });
  99884. }
  99885. else {
  99886. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  99887. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  99888. delete pointerIds[pointerInfo.event.pointerId];
  99889. }
  99890. }
  99891. });
  99892. // Update bounding box positions
  99893. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  99894. // Only update the bouding box if scaling has changed
  99895. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  99896. _this.updateBoundingBox();
  99897. }
  99898. });
  99899. _this.updateBoundingBox();
  99900. return _this;
  99901. }
  99902. /** @hidden */
  99903. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  99904. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  99905. // Save old pivot and set pivot to 0,0,0
  99906. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  99907. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  99908. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  99909. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  99910. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  99911. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  99912. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  99913. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  99914. }
  99915. }
  99916. BoundingBoxGizmo._PivotCached++;
  99917. };
  99918. /** @hidden */
  99919. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  99920. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  99921. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  99922. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  99923. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  99924. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  99925. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  99926. }
  99927. this._PivotCached--;
  99928. };
  99929. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  99930. if (value) {
  99931. // Reset anchor mesh to match attached mesh's scale
  99932. // This is needed to avoid invalid box/sphere position on first drag
  99933. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  99934. this._anchorMesh.addChild(value);
  99935. this._anchorMesh.removeChild(value);
  99936. BoundingBoxGizmo._RestorePivotPoint(value);
  99937. this.updateBoundingBox();
  99938. }
  99939. };
  99940. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  99941. this._rotateSpheresParent.getChildMeshes()
  99942. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  99943. m.isVisible = (!selectedMesh || m == selectedMesh);
  99944. });
  99945. };
  99946. /**
  99947. * Updates the bounding box information for the Gizmo
  99948. */
  99949. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  99950. if (this.attachedMesh) {
  99951. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  99952. this._update();
  99953. // Rotate based on axis
  99954. if (!this.attachedMesh.rotationQuaternion) {
  99955. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  99956. }
  99957. if (!this._anchorMesh.rotationQuaternion) {
  99958. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  99959. }
  99960. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  99961. // Store original position and reset mesh to origin before computing the bounding box
  99962. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  99963. this._tmpVector.copyFrom(this.attachedMesh.position);
  99964. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  99965. this.attachedMesh.position.set(0, 0, 0);
  99966. // Update bounding dimensions/positions
  99967. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  99968. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  99969. // Update gizmo to match bounding box scaling and rotation
  99970. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  99971. 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);
  99972. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  99973. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  99974. this._lineBoundingBox.computeWorldMatrix();
  99975. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  99976. // restore position/rotation values
  99977. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  99978. this.attachedMesh.position.copyFrom(this._tmpVector);
  99979. }
  99980. // Update rotation sphere locations
  99981. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  99982. for (var i = 0; i < 3; i++) {
  99983. for (var j = 0; j < 2; j++) {
  99984. for (var k = 0; k < 2; k++) {
  99985. var index = ((i * 4) + (j * 2)) + k;
  99986. if (i == 0) {
  99987. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  99988. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  99989. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  99990. }
  99991. if (i == 1) {
  99992. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  99993. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  99994. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  99995. }
  99996. if (i == 2) {
  99997. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  99998. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  99999. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  100000. }
  100001. if (this.fixedDragMeshScreenSize) {
  100002. this._rootMesh.computeWorldMatrix();
  100003. this._rotateSpheresParent.computeWorldMatrix();
  100004. rotateSpheres[index].computeWorldMatrix();
  100005. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  100006. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  100007. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  100008. }
  100009. else {
  100010. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  100011. }
  100012. }
  100013. }
  100014. }
  100015. // Update scale box locations
  100016. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  100017. for (var i = 0; i < 2; i++) {
  100018. for (var j = 0; j < 2; j++) {
  100019. for (var k = 0; k < 2; k++) {
  100020. var index = ((i * 4) + (j * 2)) + k;
  100021. if (scaleBoxes[index]) {
  100022. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  100023. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  100024. if (this.fixedDragMeshScreenSize) {
  100025. this._rootMesh.computeWorldMatrix();
  100026. this._scaleBoxesParent.computeWorldMatrix();
  100027. scaleBoxes[index].computeWorldMatrix();
  100028. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  100029. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  100030. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  100031. }
  100032. else {
  100033. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  100034. }
  100035. }
  100036. }
  100037. }
  100038. }
  100039. if (this.attachedMesh) {
  100040. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  100041. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  100042. }
  100043. };
  100044. /**
  100045. * Enables rotation on the specified axis and disables rotation on the others
  100046. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  100047. */
  100048. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  100049. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  100050. if (i < 4) {
  100051. m.setEnabled(axis.indexOf("x") != -1);
  100052. }
  100053. else if (i < 8) {
  100054. m.setEnabled(axis.indexOf("y") != -1);
  100055. }
  100056. else {
  100057. m.setEnabled(axis.indexOf("z") != -1);
  100058. }
  100059. });
  100060. };
  100061. /**
  100062. * Disposes of the gizmo
  100063. */
  100064. BoundingBoxGizmo.prototype.dispose = function () {
  100065. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  100066. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  100067. this._lineBoundingBox.dispose();
  100068. this._rotateSpheresParent.dispose();
  100069. this._scaleBoxesParent.dispose();
  100070. _super.prototype.dispose.call(this);
  100071. };
  100072. /**
  100073. * 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)
  100074. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  100075. * @returns the bounding box mesh with the passed in mesh as a child
  100076. */
  100077. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  100078. var makeNotPickable = function (root) {
  100079. root.isPickable = false;
  100080. root.getChildMeshes().forEach(function (c) {
  100081. makeNotPickable(c);
  100082. });
  100083. };
  100084. makeNotPickable(mesh);
  100085. // Reset position to get boudning box from origin with no rotation
  100086. if (!mesh.rotationQuaternion) {
  100087. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  100088. }
  100089. var oldPos = mesh.position.clone();
  100090. var oldRot = mesh.rotationQuaternion.clone();
  100091. mesh.rotationQuaternion.set(0, 0, 0, 1);
  100092. mesh.position.set(0, 0, 0);
  100093. // Update bounding dimensions/positions
  100094. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  100095. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  100096. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  100097. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  100098. // Restore original positions
  100099. mesh.addChild(box);
  100100. mesh.rotationQuaternion.copyFrom(oldRot);
  100101. mesh.position.copyFrom(oldPos);
  100102. // Reverse parenting
  100103. mesh.removeChild(box);
  100104. box.addChild(mesh);
  100105. box.visibility = 0;
  100106. return box;
  100107. };
  100108. /**
  100109. * CustomMeshes are not supported by this gizmo
  100110. * @param mesh The mesh to replace the default mesh of the gizmo
  100111. */
  100112. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  100113. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  100114. };
  100115. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  100116. // store/remove pivot point should only be applied during their outermost calls
  100117. BoundingBoxGizmo._PivotCached = 0;
  100118. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  100119. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  100120. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  100121. return BoundingBoxGizmo;
  100122. }(BABYLON.Gizmo));
  100123. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  100124. })(BABYLON || (BABYLON = {}));
  100125. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  100126. var BABYLON;
  100127. (function (BABYLON) {
  100128. /**
  100129. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  100130. */
  100131. var GizmoManager = /** @class */ (function () {
  100132. /**
  100133. * Instatiates a gizmo manager
  100134. * @param scene the scene to overlay the gizmos on top of
  100135. */
  100136. function GizmoManager(scene) {
  100137. var _this = this;
  100138. this.scene = scene;
  100139. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  100140. this._pointerObserver = null;
  100141. this._attachedMesh = null;
  100142. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  100143. /**
  100144. * When bounding box gizmo is enabled, this can be used to track drag/end events
  100145. */
  100146. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  100147. /**
  100148. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  100149. */
  100150. this.attachableMeshes = null;
  100151. /**
  100152. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  100153. */
  100154. this.usePointerToAttachGizmos = true;
  100155. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  100156. // Instatiate/dispose gizmos based on pointer actions
  100157. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  100158. if (!_this.usePointerToAttachGizmos) {
  100159. return;
  100160. }
  100161. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  100162. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  100163. var node = pointerInfo.pickInfo.pickedMesh;
  100164. if (_this.attachableMeshes == null) {
  100165. // Attach to the most parent node
  100166. while (node && node.parent != null) {
  100167. node = node.parent;
  100168. }
  100169. }
  100170. else {
  100171. // Attach to the parent node that is an attachableMesh
  100172. var found = false;
  100173. _this.attachableMeshes.forEach(function (mesh) {
  100174. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  100175. node = mesh;
  100176. found = true;
  100177. }
  100178. });
  100179. if (!found) {
  100180. node = null;
  100181. }
  100182. }
  100183. if (node instanceof BABYLON.AbstractMesh) {
  100184. _this.attachToMesh(node);
  100185. }
  100186. else {
  100187. _this.attachToMesh(null);
  100188. }
  100189. }
  100190. else {
  100191. _this.attachToMesh(null);
  100192. }
  100193. }
  100194. });
  100195. }
  100196. /**
  100197. * Attaches a set of gizmos to the specified mesh
  100198. * @param mesh The mesh the gizmo's should be attached to
  100199. */
  100200. GizmoManager.prototype.attachToMesh = function (mesh) {
  100201. if (this._attachedMesh) {
  100202. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  100203. }
  100204. this._attachedMesh = mesh;
  100205. for (var key in this.gizmos) {
  100206. var gizmo = (this.gizmos[key]);
  100207. if (gizmo && this._gizmosEnabled[key]) {
  100208. gizmo.attachedMesh = mesh;
  100209. }
  100210. }
  100211. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  100212. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  100213. }
  100214. };
  100215. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  100216. get: function () {
  100217. return this._gizmosEnabled.positionGizmo;
  100218. },
  100219. /**
  100220. * If the position gizmo is enabled
  100221. */
  100222. set: function (value) {
  100223. if (value) {
  100224. if (!this.gizmos.positionGizmo) {
  100225. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  100226. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  100227. }
  100228. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  100229. }
  100230. else if (this.gizmos.positionGizmo) {
  100231. this.gizmos.positionGizmo.attachedMesh = null;
  100232. }
  100233. this._gizmosEnabled.positionGizmo = value;
  100234. },
  100235. enumerable: true,
  100236. configurable: true
  100237. });
  100238. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  100239. get: function () {
  100240. return this._gizmosEnabled.rotationGizmo;
  100241. },
  100242. /**
  100243. * If the rotation gizmo is enabled
  100244. */
  100245. set: function (value) {
  100246. if (value) {
  100247. if (!this.gizmos.rotationGizmo) {
  100248. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  100249. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  100250. }
  100251. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  100252. }
  100253. else if (this.gizmos.rotationGizmo) {
  100254. this.gizmos.rotationGizmo.attachedMesh = null;
  100255. }
  100256. this._gizmosEnabled.rotationGizmo = value;
  100257. },
  100258. enumerable: true,
  100259. configurable: true
  100260. });
  100261. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  100262. get: function () {
  100263. return this._gizmosEnabled.scaleGizmo;
  100264. },
  100265. /**
  100266. * If the scale gizmo is enabled
  100267. */
  100268. set: function (value) {
  100269. if (value) {
  100270. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  100271. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  100272. }
  100273. else if (this.gizmos.scaleGizmo) {
  100274. this.gizmos.scaleGizmo.attachedMesh = null;
  100275. }
  100276. this._gizmosEnabled.scaleGizmo = value;
  100277. },
  100278. enumerable: true,
  100279. configurable: true
  100280. });
  100281. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  100282. get: function () {
  100283. return this._gizmosEnabled.boundingBoxGizmo;
  100284. },
  100285. /**
  100286. * If the boundingBox gizmo is enabled
  100287. */
  100288. set: function (value) {
  100289. if (value) {
  100290. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  100291. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  100292. if (this._attachedMesh) {
  100293. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  100294. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  100295. }
  100296. }
  100297. else if (this.gizmos.boundingBoxGizmo) {
  100298. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  100299. }
  100300. this._gizmosEnabled.boundingBoxGizmo = value;
  100301. },
  100302. enumerable: true,
  100303. configurable: true
  100304. });
  100305. /**
  100306. * Disposes of the gizmo manager
  100307. */
  100308. GizmoManager.prototype.dispose = function () {
  100309. this.scene.onPointerObservable.remove(this._pointerObserver);
  100310. for (var key in this.gizmos) {
  100311. var gizmo = (this.gizmos[key]);
  100312. if (gizmo) {
  100313. gizmo.dispose();
  100314. }
  100315. }
  100316. this.boundingBoxDragBehavior.detach();
  100317. };
  100318. return GizmoManager;
  100319. }());
  100320. BABYLON.GizmoManager = GizmoManager;
  100321. })(BABYLON || (BABYLON = {}));
  100322. //# sourceMappingURL=babylon.gizmoManager.js.map
  100323. var BABYLON;
  100324. (function (BABYLON) {
  100325. /**
  100326. * Defines a target to use with MorphTargetManager
  100327. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  100328. */
  100329. var MorphTarget = /** @class */ (function () {
  100330. /**
  100331. * Creates a new MorphTarget
  100332. * @param name defines the name of the target
  100333. * @param influence defines the influence to use
  100334. */
  100335. function MorphTarget(
  100336. /** defines the name of the target */
  100337. name, influence, scene) {
  100338. if (influence === void 0) { influence = 0; }
  100339. if (scene === void 0) { scene = null; }
  100340. this.name = name;
  100341. /**
  100342. * Gets or sets the list of animations
  100343. */
  100344. this.animations = new Array();
  100345. this._positions = null;
  100346. this._normals = null;
  100347. this._tangents = null;
  100348. /**
  100349. * Observable raised when the influence changes
  100350. */
  100351. this.onInfluenceChanged = new BABYLON.Observable();
  100352. this._animationPropertiesOverride = null;
  100353. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  100354. this.influence = influence;
  100355. }
  100356. Object.defineProperty(MorphTarget.prototype, "influence", {
  100357. /**
  100358. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  100359. */
  100360. get: function () {
  100361. return this._influence;
  100362. },
  100363. set: function (influence) {
  100364. if (this._influence === influence) {
  100365. return;
  100366. }
  100367. var previous = this._influence;
  100368. this._influence = influence;
  100369. if (this.onInfluenceChanged.hasObservers) {
  100370. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  100371. }
  100372. },
  100373. enumerable: true,
  100374. configurable: true
  100375. });
  100376. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  100377. /**
  100378. * Gets or sets the animation properties override
  100379. */
  100380. get: function () {
  100381. if (!this._animationPropertiesOverride && this._scene) {
  100382. return this._scene.animationPropertiesOverride;
  100383. }
  100384. return this._animationPropertiesOverride;
  100385. },
  100386. set: function (value) {
  100387. this._animationPropertiesOverride = value;
  100388. },
  100389. enumerable: true,
  100390. configurable: true
  100391. });
  100392. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  100393. /**
  100394. * Gets a boolean defining if the target contains position data
  100395. */
  100396. get: function () {
  100397. return !!this._positions;
  100398. },
  100399. enumerable: true,
  100400. configurable: true
  100401. });
  100402. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  100403. /**
  100404. * Gets a boolean defining if the target contains normal data
  100405. */
  100406. get: function () {
  100407. return !!this._normals;
  100408. },
  100409. enumerable: true,
  100410. configurable: true
  100411. });
  100412. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  100413. /**
  100414. * Gets a boolean defining if the target contains tangent data
  100415. */
  100416. get: function () {
  100417. return !!this._tangents;
  100418. },
  100419. enumerable: true,
  100420. configurable: true
  100421. });
  100422. /**
  100423. * Affects position data to this target
  100424. * @param data defines the position data to use
  100425. */
  100426. MorphTarget.prototype.setPositions = function (data) {
  100427. this._positions = data;
  100428. };
  100429. /**
  100430. * Gets the position data stored in this target
  100431. * @returns a FloatArray containing the position data (or null if not present)
  100432. */
  100433. MorphTarget.prototype.getPositions = function () {
  100434. return this._positions;
  100435. };
  100436. /**
  100437. * Affects normal data to this target
  100438. * @param data defines the normal data to use
  100439. */
  100440. MorphTarget.prototype.setNormals = function (data) {
  100441. this._normals = data;
  100442. };
  100443. /**
  100444. * Gets the normal data stored in this target
  100445. * @returns a FloatArray containing the normal data (or null if not present)
  100446. */
  100447. MorphTarget.prototype.getNormals = function () {
  100448. return this._normals;
  100449. };
  100450. /**
  100451. * Affects tangent data to this target
  100452. * @param data defines the tangent data to use
  100453. */
  100454. MorphTarget.prototype.setTangents = function (data) {
  100455. this._tangents = data;
  100456. };
  100457. /**
  100458. * Gets the tangent data stored in this target
  100459. * @returns a FloatArray containing the tangent data (or null if not present)
  100460. */
  100461. MorphTarget.prototype.getTangents = function () {
  100462. return this._tangents;
  100463. };
  100464. /**
  100465. * Serializes the current target into a Serialization object
  100466. * @returns the serialized object
  100467. */
  100468. MorphTarget.prototype.serialize = function () {
  100469. var serializationObject = {};
  100470. serializationObject.name = this.name;
  100471. serializationObject.influence = this.influence;
  100472. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  100473. if (this.hasNormals) {
  100474. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  100475. }
  100476. if (this.hasTangents) {
  100477. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  100478. }
  100479. // Animations
  100480. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  100481. return serializationObject;
  100482. };
  100483. // Statics
  100484. /**
  100485. * Creates a new target from serialized data
  100486. * @param serializationObject defines the serialized data to use
  100487. * @returns a new MorphTarget
  100488. */
  100489. MorphTarget.Parse = function (serializationObject) {
  100490. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  100491. result.setPositions(serializationObject.positions);
  100492. if (serializationObject.normals) {
  100493. result.setNormals(serializationObject.normals);
  100494. }
  100495. if (serializationObject.tangents) {
  100496. result.setTangents(serializationObject.tangents);
  100497. }
  100498. // Animations
  100499. if (serializationObject.animations) {
  100500. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  100501. var parsedAnimation = serializationObject.animations[animationIndex];
  100502. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  100503. }
  100504. }
  100505. return result;
  100506. };
  100507. /**
  100508. * Creates a MorphTarget from mesh data
  100509. * @param mesh defines the source mesh
  100510. * @param name defines the name to use for the new target
  100511. * @param influence defines the influence to attach to the target
  100512. * @returns a new MorphTarget
  100513. */
  100514. MorphTarget.FromMesh = function (mesh, name, influence) {
  100515. if (!name) {
  100516. name = mesh.name;
  100517. }
  100518. var result = new MorphTarget(name, influence, mesh.getScene());
  100519. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  100520. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  100521. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  100522. }
  100523. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  100524. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  100525. }
  100526. return result;
  100527. };
  100528. return MorphTarget;
  100529. }());
  100530. BABYLON.MorphTarget = MorphTarget;
  100531. })(BABYLON || (BABYLON = {}));
  100532. //# sourceMappingURL=babylon.morphTarget.js.map
  100533. var BABYLON;
  100534. (function (BABYLON) {
  100535. /**
  100536. * This class is used to deform meshes using morphing between different targets
  100537. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  100538. */
  100539. var MorphTargetManager = /** @class */ (function () {
  100540. /**
  100541. * Creates a new MorphTargetManager
  100542. * @param scene defines the current scene
  100543. */
  100544. function MorphTargetManager(scene) {
  100545. if (scene === void 0) { scene = null; }
  100546. this._targets = new Array();
  100547. this._targetObservable = new Array();
  100548. this._activeTargets = new BABYLON.SmartArray(16);
  100549. this._supportsNormals = false;
  100550. this._supportsTangents = false;
  100551. this._vertexCount = 0;
  100552. this._uniqueId = 0;
  100553. this._tempInfluences = new Array();
  100554. if (!scene) {
  100555. scene = BABYLON.Engine.LastCreatedScene;
  100556. }
  100557. this._scene = scene;
  100558. if (this._scene) {
  100559. this._scene.morphTargetManagers.push(this);
  100560. this._uniqueId = this._scene.getUniqueId();
  100561. }
  100562. }
  100563. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  100564. /**
  100565. * Gets the unique ID of this manager
  100566. */
  100567. get: function () {
  100568. return this._uniqueId;
  100569. },
  100570. enumerable: true,
  100571. configurable: true
  100572. });
  100573. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  100574. /**
  100575. * Gets the number of vertices handled by this manager
  100576. */
  100577. get: function () {
  100578. return this._vertexCount;
  100579. },
  100580. enumerable: true,
  100581. configurable: true
  100582. });
  100583. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  100584. /**
  100585. * Gets a boolean indicating if this manager supports morphing of normals
  100586. */
  100587. get: function () {
  100588. return this._supportsNormals;
  100589. },
  100590. enumerable: true,
  100591. configurable: true
  100592. });
  100593. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  100594. /**
  100595. * Gets a boolean indicating if this manager supports morphing of tangents
  100596. */
  100597. get: function () {
  100598. return this._supportsTangents;
  100599. },
  100600. enumerable: true,
  100601. configurable: true
  100602. });
  100603. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  100604. /**
  100605. * Gets the number of targets stored in this manager
  100606. */
  100607. get: function () {
  100608. return this._targets.length;
  100609. },
  100610. enumerable: true,
  100611. configurable: true
  100612. });
  100613. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  100614. /**
  100615. * Gets the number of influencers (ie. the number of targets with influences > 0)
  100616. */
  100617. get: function () {
  100618. return this._activeTargets.length;
  100619. },
  100620. enumerable: true,
  100621. configurable: true
  100622. });
  100623. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  100624. /**
  100625. * Gets the list of influences (one per target)
  100626. */
  100627. get: function () {
  100628. return this._influences;
  100629. },
  100630. enumerable: true,
  100631. configurable: true
  100632. });
  100633. /**
  100634. * Gets the active target at specified index. An active target is a target with an influence > 0
  100635. * @param index defines the index to check
  100636. * @returns the requested target
  100637. */
  100638. MorphTargetManager.prototype.getActiveTarget = function (index) {
  100639. return this._activeTargets.data[index];
  100640. };
  100641. /**
  100642. * Gets the target at specified index
  100643. * @param index defines the index to check
  100644. * @returns the requested target
  100645. */
  100646. MorphTargetManager.prototype.getTarget = function (index) {
  100647. return this._targets[index];
  100648. };
  100649. /**
  100650. * Add a new target to this manager
  100651. * @param target defines the target to add
  100652. */
  100653. MorphTargetManager.prototype.addTarget = function (target) {
  100654. var _this = this;
  100655. this._targets.push(target);
  100656. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  100657. _this._syncActiveTargets(needUpdate);
  100658. }));
  100659. this._syncActiveTargets(true);
  100660. };
  100661. /**
  100662. * Removes a target from the manager
  100663. * @param target defines the target to remove
  100664. */
  100665. MorphTargetManager.prototype.removeTarget = function (target) {
  100666. var index = this._targets.indexOf(target);
  100667. if (index >= 0) {
  100668. this._targets.splice(index, 1);
  100669. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  100670. this._syncActiveTargets(true);
  100671. }
  100672. };
  100673. /**
  100674. * Serializes the current manager into a Serialization object
  100675. * @returns the serialized object
  100676. */
  100677. MorphTargetManager.prototype.serialize = function () {
  100678. var serializationObject = {};
  100679. serializationObject.id = this.uniqueId;
  100680. serializationObject.targets = [];
  100681. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  100682. var target = _a[_i];
  100683. serializationObject.targets.push(target.serialize());
  100684. }
  100685. return serializationObject;
  100686. };
  100687. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  100688. var influenceCount = 0;
  100689. this._activeTargets.reset();
  100690. this._supportsNormals = true;
  100691. this._supportsTangents = true;
  100692. this._vertexCount = 0;
  100693. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  100694. var target = _a[_i];
  100695. this._activeTargets.push(target);
  100696. this._tempInfluences[influenceCount++] = target.influence;
  100697. var positions = target.getPositions();
  100698. if (positions) {
  100699. this._supportsNormals = this._supportsNormals && target.hasNormals;
  100700. this._supportsTangents = this._supportsTangents && target.hasTangents;
  100701. var vertexCount = positions.length / 3;
  100702. if (this._vertexCount === 0) {
  100703. this._vertexCount = vertexCount;
  100704. }
  100705. else if (this._vertexCount !== vertexCount) {
  100706. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  100707. return;
  100708. }
  100709. }
  100710. }
  100711. if (!this._influences || this._influences.length !== influenceCount) {
  100712. this._influences = new Float32Array(influenceCount);
  100713. }
  100714. for (var index = 0; index < influenceCount; index++) {
  100715. this._influences[index] = this._tempInfluences[index];
  100716. }
  100717. if (needUpdate) {
  100718. this.synchronize();
  100719. }
  100720. };
  100721. /**
  100722. * Syncrhonize the targets with all the meshes using this morph target manager
  100723. */
  100724. MorphTargetManager.prototype.synchronize = function () {
  100725. if (!this._scene) {
  100726. return;
  100727. }
  100728. // Flag meshes as dirty to resync with the active targets
  100729. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  100730. var mesh = _a[_i];
  100731. if (mesh.morphTargetManager === this) {
  100732. mesh._syncGeometryWithMorphTargetManager();
  100733. }
  100734. }
  100735. };
  100736. // Statics
  100737. /**
  100738. * Creates a new MorphTargetManager from serialized data
  100739. * @param serializationObject defines the serialized data
  100740. * @param scene defines the hosting scene
  100741. * @returns the new MorphTargetManager
  100742. */
  100743. MorphTargetManager.Parse = function (serializationObject, scene) {
  100744. var result = new MorphTargetManager(scene);
  100745. result._uniqueId = serializationObject.id;
  100746. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  100747. var targetData = _a[_i];
  100748. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  100749. }
  100750. return result;
  100751. };
  100752. return MorphTargetManager;
  100753. }());
  100754. BABYLON.MorphTargetManager = MorphTargetManager;
  100755. })(BABYLON || (BABYLON = {}));
  100756. //# sourceMappingURL=babylon.morphTargetManager.js.map
  100757. var BABYLON;
  100758. (function (BABYLON) {
  100759. /**
  100760. * Octrees are a really powerful data structure that can quickly select entities based on space coordinates.
  100761. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  100762. */
  100763. var Octree = /** @class */ (function () {
  100764. /**
  100765. * Creates a octree
  100766. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  100767. * @param creationFunc function to be used to instatiate the octree
  100768. * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64)
  100769. * @param maxDepth defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.)
  100770. */
  100771. function Octree(creationFunc, maxBlockCapacity,
  100772. /** Defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.) */
  100773. maxDepth) {
  100774. if (maxDepth === void 0) { maxDepth = 2; }
  100775. this.maxDepth = maxDepth;
  100776. /**
  100777. * Content stored in the octree
  100778. */
  100779. this.dynamicContent = new Array();
  100780. this._maxBlockCapacity = maxBlockCapacity || 64;
  100781. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  100782. this._creationFunc = creationFunc;
  100783. }
  100784. // Methods
  100785. /**
  100786. * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters
  100787. * @param worldMin worldMin for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  100788. * @param worldMax worldMax for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  100789. * @param entries meshes to be added to the octree blocks
  100790. */
  100791. Octree.prototype.update = function (worldMin, worldMax, entries) {
  100792. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  100793. };
  100794. /**
  100795. * Adds a mesh to the octree
  100796. * @param entry Mesh to add to the octree
  100797. */
  100798. Octree.prototype.addMesh = function (entry) {
  100799. for (var index = 0; index < this.blocks.length; index++) {
  100800. var block = this.blocks[index];
  100801. block.addEntry(entry);
  100802. }
  100803. };
  100804. /**
  100805. * Selects an array of meshes within the frustum
  100806. * @param frustumPlanes The frustum planes to use which will select all meshes within it
  100807. * @param allowDuplicate If duplicate objects are allowed in the resulting object array
  100808. * @returns array of meshes within the frustum
  100809. */
  100810. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  100811. this._selectionContent.reset();
  100812. for (var index = 0; index < this.blocks.length; index++) {
  100813. var block = this.blocks[index];
  100814. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  100815. }
  100816. if (allowDuplicate) {
  100817. this._selectionContent.concat(this.dynamicContent);
  100818. }
  100819. else {
  100820. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  100821. }
  100822. return this._selectionContent;
  100823. };
  100824. /**
  100825. * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array
  100826. * @param sphereCenter defines the bounding sphere center
  100827. * @param sphereRadius defines the bounding sphere radius
  100828. * @param allowDuplicate defines if the selection array can contains duplicated entries
  100829. * @returns an array of objects that intersect the sphere
  100830. */
  100831. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  100832. this._selectionContent.reset();
  100833. for (var index = 0; index < this.blocks.length; index++) {
  100834. var block = this.blocks[index];
  100835. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  100836. }
  100837. if (allowDuplicate) {
  100838. this._selectionContent.concat(this.dynamicContent);
  100839. }
  100840. else {
  100841. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  100842. }
  100843. return this._selectionContent;
  100844. };
  100845. /**
  100846. * Test if the octree intersect with the given ray and if yes, then add its content to resulting array
  100847. * @param ray defines the ray to test with
  100848. * @returns array of intersected objects
  100849. */
  100850. Octree.prototype.intersectsRay = function (ray) {
  100851. this._selectionContent.reset();
  100852. for (var index = 0; index < this.blocks.length; index++) {
  100853. var block = this.blocks[index];
  100854. block.intersectsRay(ray, this._selectionContent);
  100855. }
  100856. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  100857. return this._selectionContent;
  100858. };
  100859. /**
  100860. * @hidden
  100861. */
  100862. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  100863. target.blocks = new Array();
  100864. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  100865. // Segmenting space
  100866. for (var x = 0; x < 2; x++) {
  100867. for (var y = 0; y < 2; y++) {
  100868. for (var z = 0; z < 2; z++) {
  100869. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  100870. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  100871. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  100872. block.addEntries(entries);
  100873. target.blocks.push(block);
  100874. }
  100875. }
  100876. }
  100877. };
  100878. /**
  100879. * Adds a mesh into the octree block if it intersects the block
  100880. */
  100881. Octree.CreationFuncForMeshes = function (entry, block) {
  100882. var boundingInfo = entry.getBoundingInfo();
  100883. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  100884. block.entries.push(entry);
  100885. }
  100886. };
  100887. /**
  100888. * Adds a submesh into the octree block if it intersects the block
  100889. */
  100890. Octree.CreationFuncForSubMeshes = function (entry, block) {
  100891. var boundingInfo = entry.getBoundingInfo();
  100892. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  100893. block.entries.push(entry);
  100894. }
  100895. };
  100896. return Octree;
  100897. }());
  100898. BABYLON.Octree = Octree;
  100899. })(BABYLON || (BABYLON = {}));
  100900. //# sourceMappingURL=babylon.octree.js.map
  100901. var BABYLON;
  100902. (function (BABYLON) {
  100903. /**
  100904. * Class used to store a cell in an octree
  100905. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  100906. */
  100907. var OctreeBlock = /** @class */ (function () {
  100908. /**
  100909. * Creates a new block
  100910. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  100911. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  100912. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  100913. * @param depth defines the current depth of this block in the octree
  100914. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  100915. * @param creationFunc defines a callback to call when an element is added to the block
  100916. */
  100917. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  100918. /**
  100919. * Gets the content of the current block
  100920. */
  100921. this.entries = new Array();
  100922. this._boundingVectors = new Array();
  100923. this._capacity = capacity;
  100924. this._depth = depth;
  100925. this._maxDepth = maxDepth;
  100926. this._creationFunc = creationFunc;
  100927. this._minPoint = minPoint;
  100928. this._maxPoint = maxPoint;
  100929. this._boundingVectors.push(minPoint.clone());
  100930. this._boundingVectors.push(maxPoint.clone());
  100931. this._boundingVectors.push(minPoint.clone());
  100932. this._boundingVectors[2].x = maxPoint.x;
  100933. this._boundingVectors.push(minPoint.clone());
  100934. this._boundingVectors[3].y = maxPoint.y;
  100935. this._boundingVectors.push(minPoint.clone());
  100936. this._boundingVectors[4].z = maxPoint.z;
  100937. this._boundingVectors.push(maxPoint.clone());
  100938. this._boundingVectors[5].z = minPoint.z;
  100939. this._boundingVectors.push(maxPoint.clone());
  100940. this._boundingVectors[6].x = minPoint.x;
  100941. this._boundingVectors.push(maxPoint.clone());
  100942. this._boundingVectors[7].y = minPoint.y;
  100943. }
  100944. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  100945. // Property
  100946. /**
  100947. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  100948. */
  100949. get: function () {
  100950. return this._capacity;
  100951. },
  100952. enumerable: true,
  100953. configurable: true
  100954. });
  100955. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  100956. /**
  100957. * Gets the minimum vector (in world space) of the block's bounding box
  100958. */
  100959. get: function () {
  100960. return this._minPoint;
  100961. },
  100962. enumerable: true,
  100963. configurable: true
  100964. });
  100965. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  100966. /**
  100967. * Gets the maximum vector (in world space) of the block's bounding box
  100968. */
  100969. get: function () {
  100970. return this._maxPoint;
  100971. },
  100972. enumerable: true,
  100973. configurable: true
  100974. });
  100975. // Methods
  100976. /**
  100977. * Add a new element to this block
  100978. * @param entry defines the element to add
  100979. */
  100980. OctreeBlock.prototype.addEntry = function (entry) {
  100981. if (this.blocks) {
  100982. for (var index = 0; index < this.blocks.length; index++) {
  100983. var block = this.blocks[index];
  100984. block.addEntry(entry);
  100985. }
  100986. return;
  100987. }
  100988. this._creationFunc(entry, this);
  100989. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  100990. this.createInnerBlocks();
  100991. }
  100992. };
  100993. /**
  100994. * Add an array of elements to this block
  100995. * @param entries defines the array of elements to add
  100996. */
  100997. OctreeBlock.prototype.addEntries = function (entries) {
  100998. for (var index = 0; index < entries.length; index++) {
  100999. var mesh = entries[index];
  101000. this.addEntry(mesh);
  101001. }
  101002. };
  101003. /**
  101004. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  101005. * @param frustumPlanes defines the frustum planes to test
  101006. * @param selection defines the array to store current content if selection is positive
  101007. * @param allowDuplicate defines if the selection array can contains duplicated entries
  101008. */
  101009. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  101010. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  101011. if (this.blocks) {
  101012. for (var index = 0; index < this.blocks.length; index++) {
  101013. var block = this.blocks[index];
  101014. block.select(frustumPlanes, selection, allowDuplicate);
  101015. }
  101016. return;
  101017. }
  101018. if (allowDuplicate) {
  101019. selection.concat(this.entries);
  101020. }
  101021. else {
  101022. selection.concatWithNoDuplicate(this.entries);
  101023. }
  101024. }
  101025. };
  101026. /**
  101027. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  101028. * @param sphereCenter defines the bounding sphere center
  101029. * @param sphereRadius defines the bounding sphere radius
  101030. * @param selection defines the array to store current content if selection is positive
  101031. * @param allowDuplicate defines if the selection array can contains duplicated entries
  101032. */
  101033. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  101034. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  101035. if (this.blocks) {
  101036. for (var index = 0; index < this.blocks.length; index++) {
  101037. var block = this.blocks[index];
  101038. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  101039. }
  101040. return;
  101041. }
  101042. if (allowDuplicate) {
  101043. selection.concat(this.entries);
  101044. }
  101045. else {
  101046. selection.concatWithNoDuplicate(this.entries);
  101047. }
  101048. }
  101049. };
  101050. /**
  101051. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  101052. * @param ray defines the ray to test with
  101053. * @param selection defines the array to store current content if selection is positive
  101054. */
  101055. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  101056. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  101057. if (this.blocks) {
  101058. for (var index = 0; index < this.blocks.length; index++) {
  101059. var block = this.blocks[index];
  101060. block.intersectsRay(ray, selection);
  101061. }
  101062. return;
  101063. }
  101064. selection.concatWithNoDuplicate(this.entries);
  101065. }
  101066. };
  101067. /**
  101068. * Subdivide the content into child blocks (this block will then be empty)
  101069. */
  101070. OctreeBlock.prototype.createInnerBlocks = function () {
  101071. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  101072. };
  101073. return OctreeBlock;
  101074. }());
  101075. BABYLON.OctreeBlock = OctreeBlock;
  101076. })(BABYLON || (BABYLON = {}));
  101077. //# sourceMappingURL=babylon.octreeBlock.js.map
  101078. var BABYLON;
  101079. (function (BABYLON) {
  101080. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  101081. if (maxCapacity === void 0) { maxCapacity = 64; }
  101082. if (maxDepth === void 0) { maxDepth = 2; }
  101083. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  101084. if (!component) {
  101085. component = new OctreeSceneComponent(this);
  101086. this._addComponent(component);
  101087. }
  101088. if (!this._selectionOctree) {
  101089. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  101090. }
  101091. var worldExtends = this.getWorldExtends();
  101092. // Update octree
  101093. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  101094. return this._selectionOctree;
  101095. };
  101096. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  101097. get: function () {
  101098. return this._selectionOctree;
  101099. },
  101100. enumerable: true,
  101101. configurable: true
  101102. });
  101103. /**
  101104. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  101105. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  101106. * @param maxCapacity defines the maximum size of each block (64 by default)
  101107. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  101108. * @returns the new octree
  101109. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  101110. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  101111. */
  101112. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  101113. if (maxCapacity === void 0) { maxCapacity = 64; }
  101114. if (maxDepth === void 0) { maxDepth = 2; }
  101115. var scene = this.getScene();
  101116. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  101117. if (!component) {
  101118. component = new OctreeSceneComponent(scene);
  101119. scene._addComponent(component);
  101120. }
  101121. if (!this._submeshesOctree) {
  101122. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  101123. }
  101124. this.computeWorldMatrix(true);
  101125. var boundingInfo = this.getBoundingInfo();
  101126. // Update octree
  101127. var bbox = boundingInfo.boundingBox;
  101128. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  101129. return this._submeshesOctree;
  101130. };
  101131. /**
  101132. * Defines the octree scene component responsible to manage any octrees
  101133. * in a given scene.
  101134. */
  101135. var OctreeSceneComponent = /** @class */ (function () {
  101136. /**
  101137. * Creates a new instance of the component for the given scene
  101138. * @param scene Defines the scene to register the component in
  101139. */
  101140. function OctreeSceneComponent(scene) {
  101141. /**
  101142. * The component name helpfull to identify the component in the list of scene components.
  101143. */
  101144. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  101145. /**
  101146. * Indicates if the meshes have been checked to make sure they are isEnabled()
  101147. */
  101148. this.checksIsEnabled = true;
  101149. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  101150. this.scene = scene;
  101151. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  101152. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  101153. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  101154. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  101155. }
  101156. /**
  101157. * Registers the component in a given scene
  101158. */
  101159. OctreeSceneComponent.prototype.register = function () {
  101160. var _this = this;
  101161. this.scene.onMeshRemovedObservable.add(function (mesh) {
  101162. var sceneOctree = _this.scene.selectionOctree;
  101163. if (sceneOctree !== undefined && sceneOctree !== null) {
  101164. var index = sceneOctree.dynamicContent.indexOf(mesh);
  101165. if (index !== -1) {
  101166. sceneOctree.dynamicContent.splice(index, 1);
  101167. }
  101168. }
  101169. });
  101170. this.scene.onMeshImportedObservable.add(function (mesh) {
  101171. var sceneOctree = _this.scene.selectionOctree;
  101172. if (sceneOctree !== undefined && sceneOctree !== null) {
  101173. sceneOctree.addMesh(mesh);
  101174. }
  101175. });
  101176. };
  101177. /**
  101178. * Return the list of active meshes
  101179. * @returns the list of active meshes
  101180. */
  101181. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  101182. if (this.scene._selectionOctree) {
  101183. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  101184. return selection;
  101185. }
  101186. return this.scene._getDefaultMeshCandidates();
  101187. };
  101188. /**
  101189. * Return the list of active sub meshes
  101190. * @param mesh The mesh to get the candidates sub meshes from
  101191. * @returns the list of active sub meshes
  101192. */
  101193. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  101194. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  101195. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  101196. return intersections;
  101197. }
  101198. return this.scene._getDefaultSubMeshCandidates(mesh);
  101199. };
  101200. /**
  101201. * Return the list of sub meshes intersecting with a given local ray
  101202. * @param mesh defines the mesh to find the submesh for
  101203. * @param localRay defines the ray in local space
  101204. * @returns the list of intersecting sub meshes
  101205. */
  101206. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  101207. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  101208. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  101209. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  101210. return intersections;
  101211. }
  101212. return this.scene._getDefaultSubMeshCandidates(mesh);
  101213. };
  101214. /**
  101215. * Return the list of sub meshes colliding with a collider
  101216. * @param mesh defines the mesh to find the submesh for
  101217. * @param collider defines the collider to evaluate the collision against
  101218. * @returns the list of colliding sub meshes
  101219. */
  101220. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  101221. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  101222. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  101223. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  101224. return intersections;
  101225. }
  101226. return this.scene._getDefaultSubMeshCandidates(mesh);
  101227. };
  101228. /**
  101229. * Rebuilds the elements related to this component in case of
  101230. * context lost for instance.
  101231. */
  101232. OctreeSceneComponent.prototype.rebuild = function () {
  101233. // Nothing to do here.
  101234. };
  101235. /**
  101236. * Disposes the component and the associated ressources.
  101237. */
  101238. OctreeSceneComponent.prototype.dispose = function () {
  101239. // Nothing to do here.
  101240. };
  101241. return OctreeSceneComponent;
  101242. }());
  101243. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  101244. })(BABYLON || (BABYLON = {}));
  101245. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  101246. var BABYLON;
  101247. (function (BABYLON) {
  101248. /**
  101249. * Postprocess used to generate anaglyphic rendering
  101250. */
  101251. var AnaglyphPostProcess = /** @class */ (function (_super) {
  101252. __extends(AnaglyphPostProcess, _super);
  101253. /**
  101254. * Creates a new AnaglyphPostProcess
  101255. * @param name defines postprocess name
  101256. * @param options defines creation options or target ratio scale
  101257. * @param rigCameras defines cameras using this postprocess
  101258. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  101259. * @param engine defines hosting engine
  101260. * @param reusable defines if the postprocess will be reused multiple times per frame
  101261. */
  101262. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  101263. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  101264. _this._passedProcess = rigCameras[0]._rigPostProcess;
  101265. _this.onApplyObservable.add(function (effect) {
  101266. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  101267. });
  101268. return _this;
  101269. }
  101270. return AnaglyphPostProcess;
  101271. }(BABYLON.PostProcess));
  101272. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  101273. })(BABYLON || (BABYLON = {}));
  101274. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  101275. var BABYLON;
  101276. (function (BABYLON) {
  101277. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  101278. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  101279. });
  101280. /**
  101281. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  101282. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  101283. */
  101284. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  101285. __extends(AnaglyphArcRotateCamera, _super);
  101286. /**
  101287. * Creates a new AnaglyphArcRotateCamera
  101288. * @param name defines camera name
  101289. * @param alpha defines alpha angle (in radians)
  101290. * @param beta defines beta angle (in radians)
  101291. * @param radius defines radius
  101292. * @param target defines camera target
  101293. * @param interaxialDistance defines distance between each color axis
  101294. * @param scene defines the hosting scene
  101295. */
  101296. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  101297. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  101298. _this.interaxialDistance = interaxialDistance;
  101299. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  101300. return _this;
  101301. }
  101302. /**
  101303. * Gets camera class name
  101304. * @returns AnaglyphArcRotateCamera
  101305. */
  101306. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  101307. return "AnaglyphArcRotateCamera";
  101308. };
  101309. return AnaglyphArcRotateCamera;
  101310. }(BABYLON.ArcRotateCamera));
  101311. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  101312. })(BABYLON || (BABYLON = {}));
  101313. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  101314. var BABYLON;
  101315. (function (BABYLON) {
  101316. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  101317. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  101318. });
  101319. /**
  101320. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  101321. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  101322. */
  101323. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  101324. __extends(AnaglyphFreeCamera, _super);
  101325. /**
  101326. * Creates a new AnaglyphFreeCamera
  101327. * @param name defines camera name
  101328. * @param position defines initial position
  101329. * @param interaxialDistance defines distance between each color axis
  101330. * @param scene defines the hosting scene
  101331. */
  101332. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  101333. var _this = _super.call(this, name, position, scene) || this;
  101334. _this.interaxialDistance = interaxialDistance;
  101335. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  101336. return _this;
  101337. }
  101338. /**
  101339. * Gets camera class name
  101340. * @returns AnaglyphFreeCamera
  101341. */
  101342. AnaglyphFreeCamera.prototype.getClassName = function () {
  101343. return "AnaglyphFreeCamera";
  101344. };
  101345. return AnaglyphFreeCamera;
  101346. }(BABYLON.FreeCamera));
  101347. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  101348. })(BABYLON || (BABYLON = {}));
  101349. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  101350. var BABYLON;
  101351. (function (BABYLON) {
  101352. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  101353. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  101354. });
  101355. /**
  101356. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  101357. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  101358. */
  101359. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  101360. __extends(AnaglyphGamepadCamera, _super);
  101361. /**
  101362. * Creates a new AnaglyphGamepadCamera
  101363. * @param name defines camera name
  101364. * @param position defines initial position
  101365. * @param interaxialDistance defines distance between each color axis
  101366. * @param scene defines the hosting scene
  101367. */
  101368. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  101369. var _this = _super.call(this, name, position, scene) || this;
  101370. _this.interaxialDistance = interaxialDistance;
  101371. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  101372. return _this;
  101373. }
  101374. /**
  101375. * Gets camera class name
  101376. * @returns AnaglyphGamepadCamera
  101377. */
  101378. AnaglyphGamepadCamera.prototype.getClassName = function () {
  101379. return "AnaglyphGamepadCamera";
  101380. };
  101381. return AnaglyphGamepadCamera;
  101382. }(BABYLON.GamepadCamera));
  101383. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  101384. })(BABYLON || (BABYLON = {}));
  101385. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  101386. var BABYLON;
  101387. (function (BABYLON) {
  101388. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  101389. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  101390. });
  101391. /**
  101392. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  101393. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  101394. */
  101395. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  101396. __extends(AnaglyphUniversalCamera, _super);
  101397. /**
  101398. * Creates a new AnaglyphUniversalCamera
  101399. * @param name defines camera name
  101400. * @param position defines initial position
  101401. * @param interaxialDistance defines distance between each color axis
  101402. * @param scene defines the hosting scene
  101403. */
  101404. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  101405. var _this = _super.call(this, name, position, scene) || this;
  101406. _this.interaxialDistance = interaxialDistance;
  101407. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  101408. return _this;
  101409. }
  101410. /**
  101411. * Gets camera class name
  101412. * @returns AnaglyphUniversalCamera
  101413. */
  101414. AnaglyphUniversalCamera.prototype.getClassName = function () {
  101415. return "AnaglyphUniversalCamera";
  101416. };
  101417. return AnaglyphUniversalCamera;
  101418. }(BABYLON.UniversalCamera));
  101419. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  101420. })(BABYLON || (BABYLON = {}));
  101421. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  101422. var BABYLON;
  101423. (function (BABYLON) {
  101424. /**
  101425. * StereoscopicInterlacePostProcess used to render stereo views from a rigged camera
  101426. */
  101427. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  101428. __extends(StereoscopicInterlacePostProcess, _super);
  101429. /**
  101430. * Initializes a StereoscopicInterlacePostProcess
  101431. * @param name The name of the effect.
  101432. * @param rigCameras The rig cameras to be appled to the post process
  101433. * @param isStereoscopicHoriz If the rendered results are horizontal or verticle
  101434. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  101435. * @param engine The engine which the post process will be applied. (default: current engine)
  101436. * @param reusable If the post process can be reused on the same frame. (default: false)
  101437. */
  101438. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  101439. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  101440. _this._passedProcess = rigCameras[0]._rigPostProcess;
  101441. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  101442. _this.onSizeChangedObservable.add(function () {
  101443. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  101444. });
  101445. _this.onApplyObservable.add(function (effect) {
  101446. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  101447. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  101448. });
  101449. return _this;
  101450. }
  101451. return StereoscopicInterlacePostProcess;
  101452. }(BABYLON.PostProcess));
  101453. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  101454. })(BABYLON || (BABYLON = {}));
  101455. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  101456. var BABYLON;
  101457. (function (BABYLON) {
  101458. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  101459. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  101460. });
  101461. /**
  101462. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  101463. * @see http://doc.babylonjs.com/features/cameras
  101464. */
  101465. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  101466. __extends(StereoscopicArcRotateCamera, _super);
  101467. /**
  101468. * Creates a new StereoscopicArcRotateCamera
  101469. * @param name defines camera name
  101470. * @param alpha defines alpha angle (in radians)
  101471. * @param beta defines beta angle (in radians)
  101472. * @param radius defines radius
  101473. * @param target defines camera target
  101474. * @param interaxialDistance defines distance between each color axis
  101475. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  101476. * @param scene defines the hosting scene
  101477. */
  101478. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  101479. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  101480. _this.interaxialDistance = interaxialDistance;
  101481. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  101482. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  101483. return _this;
  101484. }
  101485. /**
  101486. * Gets camera class name
  101487. * @returns StereoscopicArcRotateCamera
  101488. */
  101489. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  101490. return "StereoscopicArcRotateCamera";
  101491. };
  101492. return StereoscopicArcRotateCamera;
  101493. }(BABYLON.ArcRotateCamera));
  101494. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  101495. })(BABYLON || (BABYLON = {}));
  101496. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  101497. var BABYLON;
  101498. (function (BABYLON) {
  101499. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  101500. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  101501. });
  101502. /**
  101503. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  101504. * @see http://doc.babylonjs.com/features/cameras
  101505. */
  101506. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  101507. __extends(StereoscopicFreeCamera, _super);
  101508. /**
  101509. * Creates a new StereoscopicFreeCamera
  101510. * @param name defines camera name
  101511. * @param position defines initial position
  101512. * @param interaxialDistance defines distance between each color axis
  101513. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  101514. * @param scene defines the hosting scene
  101515. */
  101516. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  101517. var _this = _super.call(this, name, position, scene) || this;
  101518. _this.interaxialDistance = interaxialDistance;
  101519. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  101520. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  101521. return _this;
  101522. }
  101523. /**
  101524. * Gets camera class name
  101525. * @returns StereoscopicFreeCamera
  101526. */
  101527. StereoscopicFreeCamera.prototype.getClassName = function () {
  101528. return "StereoscopicFreeCamera";
  101529. };
  101530. return StereoscopicFreeCamera;
  101531. }(BABYLON.FreeCamera));
  101532. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  101533. })(BABYLON || (BABYLON = {}));
  101534. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  101535. var BABYLON;
  101536. (function (BABYLON) {
  101537. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  101538. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  101539. });
  101540. /**
  101541. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  101542. * @see http://doc.babylonjs.com/features/cameras
  101543. */
  101544. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  101545. __extends(StereoscopicGamepadCamera, _super);
  101546. /**
  101547. * Creates a new StereoscopicGamepadCamera
  101548. * @param name defines camera name
  101549. * @param position defines initial position
  101550. * @param interaxialDistance defines distance between each color axis
  101551. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  101552. * @param scene defines the hosting scene
  101553. */
  101554. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  101555. var _this = _super.call(this, name, position, scene) || this;
  101556. _this.interaxialDistance = interaxialDistance;
  101557. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  101558. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  101559. return _this;
  101560. }
  101561. /**
  101562. * Gets camera class name
  101563. * @returns StereoscopicGamepadCamera
  101564. */
  101565. StereoscopicGamepadCamera.prototype.getClassName = function () {
  101566. return "StereoscopicGamepadCamera";
  101567. };
  101568. return StereoscopicGamepadCamera;
  101569. }(BABYLON.GamepadCamera));
  101570. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  101571. })(BABYLON || (BABYLON = {}));
  101572. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  101573. var BABYLON;
  101574. (function (BABYLON) {
  101575. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  101576. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  101577. });
  101578. /**
  101579. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  101580. * @see http://doc.babylonjs.com/features/cameras
  101581. */
  101582. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  101583. __extends(StereoscopicUniversalCamera, _super);
  101584. /**
  101585. * Creates a new StereoscopicUniversalCamera
  101586. * @param name defines camera name
  101587. * @param position defines initial position
  101588. * @param interaxialDistance defines distance between each color axis
  101589. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  101590. * @param scene defines the hosting scene
  101591. */
  101592. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  101593. var _this = _super.call(this, name, position, scene) || this;
  101594. _this.interaxialDistance = interaxialDistance;
  101595. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  101596. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  101597. return _this;
  101598. }
  101599. /**
  101600. * Gets camera class name
  101601. * @returns StereoscopicUniversalCamera
  101602. */
  101603. StereoscopicUniversalCamera.prototype.getClassName = function () {
  101604. return "StereoscopicUniversalCamera";
  101605. };
  101606. return StereoscopicUniversalCamera;
  101607. }(BABYLON.UniversalCamera));
  101608. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  101609. })(BABYLON || (BABYLON = {}));
  101610. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  101611. var BABYLON;
  101612. (function (BABYLON) {
  101613. /**
  101614. * VRDistortionCorrectionPostProcess used for mobile VR
  101615. */
  101616. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  101617. __extends(VRDistortionCorrectionPostProcess, _super);
  101618. /**
  101619. * Initializes the VRDistortionCorrectionPostProcess
  101620. * @param name The name of the effect.
  101621. * @param camera The camera to apply the render pass to.
  101622. * @param isRightEye If this is for the right eye distortion
  101623. * @param vrMetrics All the required metrics for the VR camera
  101624. */
  101625. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  101626. var _this = _super.call(this, name, "vrDistortionCorrection", [
  101627. 'LensCenter',
  101628. 'Scale',
  101629. 'ScaleIn',
  101630. 'HmdWarpParam'
  101631. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  101632. _this._isRightEye = isRightEye;
  101633. _this._distortionFactors = vrMetrics.distortionK;
  101634. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  101635. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  101636. _this.adaptScaleToCurrentViewport = true;
  101637. _this.onSizeChangedObservable.add(function () {
  101638. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  101639. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  101640. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  101641. });
  101642. _this.onApplyObservable.add(function (effect) {
  101643. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  101644. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  101645. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  101646. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  101647. });
  101648. return _this;
  101649. }
  101650. return VRDistortionCorrectionPostProcess;
  101651. }(BABYLON.PostProcess));
  101652. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  101653. })(BABYLON || (BABYLON = {}));
  101654. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  101655. var BABYLON;
  101656. (function (BABYLON) {
  101657. /**
  101658. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  101659. * Screen rotation is taken into account.
  101660. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  101661. */
  101662. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  101663. /**
  101664. * Instantiates a new input
  101665. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  101666. */
  101667. function FreeCameraDeviceOrientationInput() {
  101668. var _this = this;
  101669. this._screenOrientationAngle = 0;
  101670. this._screenQuaternion = new BABYLON.Quaternion();
  101671. this._alpha = 0;
  101672. this._beta = 0;
  101673. this._gamma = 0;
  101674. this._orientationChanged = function () {
  101675. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  101676. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  101677. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  101678. };
  101679. this._deviceOrientation = function (evt) {
  101680. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  101681. _this._beta = evt.beta !== null ? evt.beta : 0;
  101682. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  101683. };
  101684. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  101685. this._orientationChanged();
  101686. }
  101687. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  101688. /**
  101689. * Define the camera controlled by the input.
  101690. */
  101691. get: function () {
  101692. return this._camera;
  101693. },
  101694. set: function (camera) {
  101695. this._camera = camera;
  101696. if (this._camera != null && !this._camera.rotationQuaternion) {
  101697. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  101698. }
  101699. },
  101700. enumerable: true,
  101701. configurable: true
  101702. });
  101703. /**
  101704. * Attach the input controls to a specific dom element to get the input from.
  101705. * @param element Defines the element the controls should be listened from
  101706. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  101707. */
  101708. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  101709. window.addEventListener("orientationchange", this._orientationChanged);
  101710. window.addEventListener("deviceorientation", this._deviceOrientation);
  101711. //In certain cases, the attach control is called AFTER orientation was changed,
  101712. //So this is needed.
  101713. this._orientationChanged();
  101714. };
  101715. /**
  101716. * Detach the current controls from the specified dom element.
  101717. * @param element Defines the element to stop listening the inputs from
  101718. */
  101719. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  101720. window.removeEventListener("orientationchange", this._orientationChanged);
  101721. window.removeEventListener("deviceorientation", this._deviceOrientation);
  101722. };
  101723. /**
  101724. * Update the current camera state depending on the inputs that have been used this frame.
  101725. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  101726. */
  101727. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  101728. //if no device orientation provided, don't update the rotation.
  101729. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  101730. if (!this._alpha)
  101731. return;
  101732. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  101733. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  101734. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  101735. //Mirror on XY Plane
  101736. this._camera.rotationQuaternion.z *= -1;
  101737. this._camera.rotationQuaternion.w *= -1;
  101738. };
  101739. /**
  101740. * Gets the class name of the current intput.
  101741. * @returns the class name
  101742. */
  101743. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  101744. return "FreeCameraDeviceOrientationInput";
  101745. };
  101746. /**
  101747. * Get the friendly name associated with the input class.
  101748. * @returns the input friendly name
  101749. */
  101750. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  101751. return "deviceOrientation";
  101752. };
  101753. return FreeCameraDeviceOrientationInput;
  101754. }());
  101755. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  101756. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  101757. })(BABYLON || (BABYLON = {}));
  101758. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  101759. var BABYLON;
  101760. (function (BABYLON) {
  101761. /**
  101762. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  101763. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  101764. */
  101765. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  101766. /**
  101767. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  101768. */
  101769. function ArcRotateCameraVRDeviceOrientationInput() {
  101770. /**
  101771. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  101772. */
  101773. this.alphaCorrection = 1;
  101774. /**
  101775. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  101776. */
  101777. this.betaCorrection = 1;
  101778. /**
  101779. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  101780. */
  101781. this.gammaCorrection = 1;
  101782. this._alpha = 0;
  101783. this._gamma = 0;
  101784. this._dirty = false;
  101785. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  101786. }
  101787. /**
  101788. * Attach the input controls to a specific dom element to get the input from.
  101789. * @param element Defines the element the controls should be listened from
  101790. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  101791. */
  101792. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  101793. this.camera.attachControl(element, noPreventDefault);
  101794. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  101795. };
  101796. /** @hidden */
  101797. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  101798. if (evt.alpha !== null) {
  101799. this._alpha = +evt.alpha | 0;
  101800. }
  101801. if (evt.gamma !== null) {
  101802. this._gamma = +evt.gamma | 0;
  101803. }
  101804. this._dirty = true;
  101805. };
  101806. /**
  101807. * Update the current camera state depending on the inputs that have been used this frame.
  101808. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  101809. */
  101810. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  101811. if (this._dirty) {
  101812. this._dirty = false;
  101813. if (this._gamma < 0) {
  101814. this._gamma = 180 + this._gamma;
  101815. }
  101816. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  101817. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  101818. }
  101819. };
  101820. /**
  101821. * Detach the current controls from the specified dom element.
  101822. * @param element Defines the element to stop listening the inputs from
  101823. */
  101824. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  101825. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  101826. };
  101827. /**
  101828. * Gets the class name of the current intput.
  101829. * @returns the class name
  101830. */
  101831. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  101832. return "ArcRotateCameraVRDeviceOrientationInput";
  101833. };
  101834. /**
  101835. * Get the friendly name associated with the input class.
  101836. * @returns the input friendly name
  101837. */
  101838. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  101839. return "VRDeviceOrientation";
  101840. };
  101841. return ArcRotateCameraVRDeviceOrientationInput;
  101842. }());
  101843. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  101844. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  101845. })(BABYLON || (BABYLON = {}));
  101846. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  101847. var BABYLON;
  101848. (function (BABYLON) {
  101849. /**
  101850. * This represents all the required metrics to create a VR camera.
  101851. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  101852. */
  101853. var VRCameraMetrics = /** @class */ (function () {
  101854. function VRCameraMetrics() {
  101855. /**
  101856. * Define if the current vr camera should compensate the distortion of the lense or not.
  101857. */
  101858. this.compensateDistortion = true;
  101859. }
  101860. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  101861. /**
  101862. * Gets the rendering aspect ratio based on the provided resolutions.
  101863. */
  101864. get: function () {
  101865. return this.hResolution / (2 * this.vResolution);
  101866. },
  101867. enumerable: true,
  101868. configurable: true
  101869. });
  101870. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  101871. /**
  101872. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  101873. */
  101874. get: function () {
  101875. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  101876. },
  101877. enumerable: true,
  101878. configurable: true
  101879. });
  101880. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  101881. /**
  101882. * @hidden
  101883. */
  101884. get: function () {
  101885. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  101886. var h = (4 * meters) / this.hScreenSize;
  101887. return BABYLON.Matrix.Translation(h, 0, 0);
  101888. },
  101889. enumerable: true,
  101890. configurable: true
  101891. });
  101892. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  101893. /**
  101894. * @hidden
  101895. */
  101896. get: function () {
  101897. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  101898. var h = (4 * meters) / this.hScreenSize;
  101899. return BABYLON.Matrix.Translation(-h, 0, 0);
  101900. },
  101901. enumerable: true,
  101902. configurable: true
  101903. });
  101904. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  101905. /**
  101906. * @hidden
  101907. */
  101908. get: function () {
  101909. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  101910. },
  101911. enumerable: true,
  101912. configurable: true
  101913. });
  101914. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  101915. /**
  101916. * @hidden
  101917. */
  101918. get: function () {
  101919. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  101920. },
  101921. enumerable: true,
  101922. configurable: true
  101923. });
  101924. /**
  101925. * Get the default VRMetrics based on the most generic setup.
  101926. * @returns the default vr metrics
  101927. */
  101928. VRCameraMetrics.GetDefault = function () {
  101929. var result = new VRCameraMetrics();
  101930. result.hResolution = 1280;
  101931. result.vResolution = 800;
  101932. result.hScreenSize = 0.149759993;
  101933. result.vScreenSize = 0.0935999975;
  101934. result.vScreenCenter = 0.0467999987;
  101935. result.eyeToScreenDistance = 0.0410000011;
  101936. result.lensSeparationDistance = 0.0635000020;
  101937. result.interpupillaryDistance = 0.0640000030;
  101938. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  101939. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  101940. result.postProcessScaleFactor = 1.714605507808412;
  101941. result.lensCenterOffset = 0.151976421;
  101942. return result;
  101943. };
  101944. return VRCameraMetrics;
  101945. }());
  101946. BABYLON.VRCameraMetrics = VRCameraMetrics;
  101947. })(BABYLON || (BABYLON = {}));
  101948. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  101949. var BABYLON;
  101950. (function (BABYLON) {
  101951. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  101952. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  101953. });
  101954. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  101955. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  101956. });
  101957. /**
  101958. * This represents a WebVR camera.
  101959. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  101960. * @example http://doc.babylonjs.com/how_to/webvr_camera
  101961. */
  101962. var WebVRFreeCamera = /** @class */ (function (_super) {
  101963. __extends(WebVRFreeCamera, _super);
  101964. /**
  101965. * Instantiates a WebVRFreeCamera.
  101966. * @param name The name of the WebVRFreeCamera
  101967. * @param position The starting anchor position for the camera
  101968. * @param scene The scene the camera belongs to
  101969. * @param webVROptions a set of customizable options for the webVRCamera
  101970. */
  101971. function WebVRFreeCamera(name, position, scene, webVROptions) {
  101972. if (webVROptions === void 0) { webVROptions = {}; }
  101973. var _this = _super.call(this, name, position, scene) || this;
  101974. _this.webVROptions = webVROptions;
  101975. /**
  101976. * @hidden
  101977. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  101978. */
  101979. _this._vrDevice = null;
  101980. /**
  101981. * The rawPose of the vrDevice.
  101982. */
  101983. _this.rawPose = null;
  101984. _this._specsVersion = "1.1";
  101985. _this._attached = false;
  101986. _this._descendants = [];
  101987. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  101988. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  101989. /** @hidden */
  101990. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  101991. _this._standingMatrix = null;
  101992. /**
  101993. * Represents device position in babylon space.
  101994. */
  101995. _this.devicePosition = BABYLON.Vector3.Zero();
  101996. /**
  101997. * Represents device rotation in babylon space.
  101998. */
  101999. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  102000. /**
  102001. * The scale of the device to be used when translating from device space to babylon space.
  102002. */
  102003. _this.deviceScaleFactor = 1;
  102004. _this._deviceToWorld = BABYLON.Matrix.Identity();
  102005. _this._worldToDevice = BABYLON.Matrix.Identity();
  102006. /**
  102007. * References to the webVR controllers for the vrDevice.
  102008. */
  102009. _this.controllers = [];
  102010. /**
  102011. * Emits an event when a controller is attached.
  102012. */
  102013. _this.onControllersAttachedObservable = new BABYLON.Observable();
  102014. /**
  102015. * Emits an event when a controller's mesh has been loaded;
  102016. */
  102017. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  102018. /**
  102019. * Emits an event when the HMD's pose has been updated.
  102020. */
  102021. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  102022. _this._poseSet = false;
  102023. /**
  102024. * If the rig cameras be used as parent instead of this camera.
  102025. */
  102026. _this.rigParenting = true;
  102027. _this._defaultHeight = undefined;
  102028. _this._htmlElementAttached = null;
  102029. _this._detachIfAttached = function () {
  102030. var vrDisplay = _this.getEngine().getVRDevice();
  102031. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  102032. _this.detachControl(_this._htmlElementAttached);
  102033. }
  102034. };
  102035. _this._workingVector = BABYLON.Vector3.Zero();
  102036. _this._oneVector = BABYLON.Vector3.One();
  102037. _this._workingMatrix = BABYLON.Matrix.Identity();
  102038. _this._tmpMatrix = new BABYLON.Matrix();
  102039. _this._cache.position = BABYLON.Vector3.Zero();
  102040. if (webVROptions.defaultHeight) {
  102041. _this._defaultHeight = webVROptions.defaultHeight;
  102042. _this.position.y = _this._defaultHeight;
  102043. }
  102044. _this.minZ = 0.1;
  102045. //legacy support - the compensation boolean was removed.
  102046. if (arguments.length === 5) {
  102047. _this.webVROptions = arguments[4];
  102048. }
  102049. // default webVR options
  102050. if (_this.webVROptions.trackPosition == undefined) {
  102051. _this.webVROptions.trackPosition = true;
  102052. }
  102053. if (_this.webVROptions.controllerMeshes == undefined) {
  102054. _this.webVROptions.controllerMeshes = true;
  102055. }
  102056. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  102057. _this.webVROptions.defaultLightingOnControllers = true;
  102058. }
  102059. _this.rotationQuaternion = new BABYLON.Quaternion();
  102060. if (_this.webVROptions && _this.webVROptions.positionScale) {
  102061. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  102062. }
  102063. //enable VR
  102064. var engine = _this.getEngine();
  102065. _this._onVREnabled = function (success) { if (success) {
  102066. _this.initControllers();
  102067. } };
  102068. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  102069. engine.initWebVR().add(function (event) {
  102070. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  102071. return;
  102072. }
  102073. _this._vrDevice = event.vrDisplay;
  102074. //reset the rig parameters.
  102075. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  102076. if (_this._attached) {
  102077. _this.getEngine().enableVR();
  102078. }
  102079. });
  102080. if (typeof (VRFrameData) !== "undefined")
  102081. _this._frameData = new VRFrameData();
  102082. /**
  102083. * The idea behind the following lines:
  102084. * objects that have the camera as parent should actually have the rig cameras as a parent.
  102085. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  102086. * the second will not show it correctly.
  102087. *
  102088. * To solve this - each object that has the camera as parent will be added to a protected array.
  102089. * When the rig camera renders, it will take this array and set all of those to be its children.
  102090. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  102091. * Amazing!
  102092. */
  102093. scene.onBeforeCameraRenderObservable.add(function (camera) {
  102094. if (camera.parent === _this && _this.rigParenting) {
  102095. _this._descendants = _this.getDescendants(true, function (n) {
  102096. // don't take the cameras or the controllers!
  102097. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  102098. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  102099. return !isController && !isRigCamera;
  102100. });
  102101. _this._descendants.forEach(function (node) {
  102102. node.parent = camera;
  102103. });
  102104. }
  102105. });
  102106. scene.onAfterCameraRenderObservable.add(function (camera) {
  102107. if (camera.parent === _this && _this.rigParenting) {
  102108. _this._descendants.forEach(function (node) {
  102109. node.parent = _this;
  102110. });
  102111. }
  102112. });
  102113. return _this;
  102114. }
  102115. /**
  102116. * Gets the device distance from the ground in meters.
  102117. * @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.
  102118. */
  102119. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  102120. if (this._standingMatrix) {
  102121. // Add standing matrix offset to get real offset from ground in room
  102122. this._standingMatrix.getTranslationToRef(this._workingVector);
  102123. return this._deviceRoomPosition.y + this._workingVector.y;
  102124. }
  102125. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  102126. return this._defaultHeight || 0;
  102127. };
  102128. /**
  102129. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  102130. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  102131. */
  102132. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  102133. var _this = this;
  102134. if (callback === void 0) { callback = function (bool) { }; }
  102135. // Use standing matrix if available
  102136. this.getEngine().initWebVRAsync().then(function (result) {
  102137. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  102138. callback(false);
  102139. }
  102140. else {
  102141. _this._standingMatrix = new BABYLON.Matrix();
  102142. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  102143. if (!_this.getScene().useRightHandedSystem) {
  102144. [2, 6, 8, 9, 14].forEach(function (num) {
  102145. if (_this._standingMatrix) {
  102146. _this._standingMatrix.m[num] *= -1;
  102147. }
  102148. });
  102149. }
  102150. callback(true);
  102151. }
  102152. });
  102153. };
  102154. /**
  102155. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  102156. * @returns A promise with a boolean set to if the standing matrix is supported.
  102157. */
  102158. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  102159. var _this = this;
  102160. return new Promise(function (res, rej) {
  102161. _this.useStandingMatrix(function (supported) {
  102162. res(supported);
  102163. });
  102164. });
  102165. };
  102166. /**
  102167. * Disposes the camera
  102168. */
  102169. WebVRFreeCamera.prototype.dispose = function () {
  102170. this._detachIfAttached();
  102171. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  102172. if (this._updateCacheWhenTrackingDisabledObserver) {
  102173. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  102174. }
  102175. _super.prototype.dispose.call(this);
  102176. };
  102177. /**
  102178. * Gets a vrController by name.
  102179. * @param name The name of the controller to retreive
  102180. * @returns the controller matching the name specified or null if not found
  102181. */
  102182. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  102183. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  102184. var gp = _a[_i];
  102185. if (gp.hand === name) {
  102186. return gp;
  102187. }
  102188. }
  102189. return null;
  102190. };
  102191. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  102192. /**
  102193. * The controller corrisponding to the users left hand.
  102194. */
  102195. get: function () {
  102196. if (!this._leftController) {
  102197. this._leftController = this.getControllerByName("left");
  102198. }
  102199. return this._leftController;
  102200. },
  102201. enumerable: true,
  102202. configurable: true
  102203. });
  102204. ;
  102205. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  102206. /**
  102207. * The controller corrisponding to the users right hand.
  102208. */
  102209. get: function () {
  102210. if (!this._rightController) {
  102211. this._rightController = this.getControllerByName("right");
  102212. }
  102213. return this._rightController;
  102214. },
  102215. enumerable: true,
  102216. configurable: true
  102217. });
  102218. ;
  102219. /**
  102220. * Casts a ray forward from the vrCamera's gaze.
  102221. * @param length Length of the ray (default: 100)
  102222. * @returns the ray corrisponding to the gaze
  102223. */
  102224. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  102225. if (length === void 0) { length = 100; }
  102226. if (this.leftCamera) {
  102227. // Use left eye to avoid computation to compute center on every call
  102228. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  102229. }
  102230. else {
  102231. return _super.prototype.getForwardRay.call(this, length);
  102232. }
  102233. };
  102234. /**
  102235. * @hidden
  102236. * Updates the camera based on device's frame data
  102237. */
  102238. WebVRFreeCamera.prototype._checkInputs = function () {
  102239. if (this._vrDevice && this._vrDevice.isPresenting) {
  102240. this._vrDevice.getFrameData(this._frameData);
  102241. this.updateFromDevice(this._frameData.pose);
  102242. }
  102243. _super.prototype._checkInputs.call(this);
  102244. };
  102245. /**
  102246. * Updates the poseControlled values based on the input device pose.
  102247. * @param poseData Pose coming from the device
  102248. */
  102249. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  102250. if (poseData && poseData.orientation) {
  102251. this.rawPose = poseData;
  102252. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  102253. if (this.getScene().useRightHandedSystem) {
  102254. this._deviceRoomRotationQuaternion.z *= -1;
  102255. this._deviceRoomRotationQuaternion.w *= -1;
  102256. }
  102257. if (this.webVROptions.trackPosition && this.rawPose.position) {
  102258. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  102259. if (this.getScene().useRightHandedSystem) {
  102260. this._deviceRoomPosition.z *= -1;
  102261. }
  102262. }
  102263. this._poseSet = true;
  102264. }
  102265. };
  102266. /**
  102267. * WebVR's attach control will start broadcasting frames to the device.
  102268. * Note that in certain browsers (chrome for example) this function must be called
  102269. * within a user-interaction callback. Example:
  102270. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  102271. *
  102272. * @param element html element to attach the vrDevice to
  102273. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  102274. */
  102275. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  102276. _super.prototype.attachControl.call(this, element, noPreventDefault);
  102277. this._attached = true;
  102278. this._htmlElementAttached = element;
  102279. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  102280. if (this._vrDevice) {
  102281. this.getEngine().enableVR();
  102282. }
  102283. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  102284. };
  102285. /**
  102286. * Detaches the camera from the html element and disables VR
  102287. *
  102288. * @param element html element to detach from
  102289. */
  102290. WebVRFreeCamera.prototype.detachControl = function (element) {
  102291. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  102292. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  102293. _super.prototype.detachControl.call(this, element);
  102294. this._attached = false;
  102295. this.getEngine().disableVR();
  102296. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  102297. };
  102298. /**
  102299. * @returns the name of this class
  102300. */
  102301. WebVRFreeCamera.prototype.getClassName = function () {
  102302. return "WebVRFreeCamera";
  102303. };
  102304. /**
  102305. * Calls resetPose on the vrDisplay
  102306. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  102307. */
  102308. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  102309. //uses the vrDisplay's "resetPose()".
  102310. //pitch and roll won't be affected.
  102311. this._vrDevice.resetPose();
  102312. };
  102313. /**
  102314. * @hidden
  102315. * Updates the rig cameras (left and right eye)
  102316. */
  102317. WebVRFreeCamera.prototype._updateRigCameras = function () {
  102318. var camLeft = this._rigCameras[0];
  102319. var camRight = this._rigCameras[1];
  102320. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  102321. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  102322. camLeft.position.copyFrom(this._deviceRoomPosition);
  102323. camRight.position.copyFrom(this._deviceRoomPosition);
  102324. };
  102325. // Remove translation from 6dof headset if trackposition is set to false
  102326. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  102327. if (isViewMatrix === void 0) { isViewMatrix = false; }
  102328. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  102329. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  102330. if (!isViewMatrix) {
  102331. this._tmpMatrix.invert();
  102332. }
  102333. this._tmpMatrix.multiplyToRef(matrix, matrix);
  102334. }
  102335. };
  102336. /**
  102337. * @hidden
  102338. * Updates the cached values of the camera
  102339. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  102340. */
  102341. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  102342. var _this = this;
  102343. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  102344. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  102345. if (!this.updateCacheCalled) {
  102346. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  102347. this.updateCacheCalled = true;
  102348. this.update();
  102349. }
  102350. // Set working vector to the device position in room space rotated by the new rotation
  102351. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  102352. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  102353. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  102354. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  102355. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  102356. // Add translation from anchor position
  102357. this._deviceToWorld.getTranslationToRef(this._workingVector);
  102358. this._workingVector.addInPlace(this.position);
  102359. this._workingVector.subtractInPlace(this._cache.position);
  102360. this._deviceToWorld.setTranslation(this._workingVector);
  102361. // Set an inverted matrix to be used when updating the camera
  102362. this._deviceToWorld.invertToRef(this._worldToDevice);
  102363. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  102364. this.controllers.forEach(function (controller) {
  102365. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  102366. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  102367. controller.update();
  102368. });
  102369. }
  102370. if (!ignoreParentClass) {
  102371. _super.prototype._updateCache.call(this);
  102372. }
  102373. this.updateCacheCalled = false;
  102374. };
  102375. /**
  102376. * @hidden
  102377. * Get current device position in babylon world
  102378. */
  102379. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  102380. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  102381. };
  102382. /**
  102383. * Updates the current device position and rotation in the babylon world
  102384. */
  102385. WebVRFreeCamera.prototype.update = function () {
  102386. this._computeDevicePosition();
  102387. // Get current device rotation in babylon world
  102388. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  102389. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  102390. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  102391. if (this._poseSet) {
  102392. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  102393. }
  102394. _super.prototype.update.call(this);
  102395. };
  102396. /**
  102397. * @hidden
  102398. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  102399. * @returns an identity matrix
  102400. */
  102401. WebVRFreeCamera.prototype._getViewMatrix = function () {
  102402. return BABYLON.Matrix.Identity();
  102403. };
  102404. /**
  102405. * This function is called by the two RIG cameras.
  102406. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  102407. */
  102408. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  102409. var _this = this;
  102410. // Update the parent camera prior to using a child camera to avoid desynchronization
  102411. var parentCamera = this._cameraRigParams["parentCamera"];
  102412. parentCamera._updateCache();
  102413. //WebVR 1.1
  102414. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  102415. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  102416. if (!this.getScene().useRightHandedSystem) {
  102417. [2, 6, 8, 9, 14].forEach(function (num) {
  102418. _this._webvrViewMatrix.m[num] *= -1;
  102419. });
  102420. }
  102421. // update the camera rotation matrix
  102422. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  102423. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  102424. // Computing target and final matrix
  102425. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  102426. // should the view matrix be updated with scale and position offset?
  102427. if (parentCamera.deviceScaleFactor !== 1) {
  102428. this._webvrViewMatrix.invert();
  102429. // scale the position, if set
  102430. if (parentCamera.deviceScaleFactor) {
  102431. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  102432. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  102433. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  102434. }
  102435. this._webvrViewMatrix.invert();
  102436. }
  102437. // Remove translation from 6dof headset if trackposition is set to false
  102438. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  102439. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  102440. // Compute global position
  102441. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  102442. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  102443. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  102444. this._workingMatrix.getTranslationToRef(this._globalPosition);
  102445. this._markSyncedWithParent();
  102446. return this._webvrViewMatrix;
  102447. };
  102448. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  102449. var _this = this;
  102450. var parentCamera = this.parent;
  102451. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  102452. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  102453. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  102454. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  102455. //babylon compatible matrix
  102456. if (!this.getScene().useRightHandedSystem) {
  102457. [8, 9, 10, 11].forEach(function (num) {
  102458. _this._projectionMatrix.m[num] *= -1;
  102459. });
  102460. }
  102461. return this._projectionMatrix;
  102462. };
  102463. /**
  102464. * Initializes the controllers and their meshes
  102465. */
  102466. WebVRFreeCamera.prototype.initControllers = function () {
  102467. var _this = this;
  102468. this.controllers = [];
  102469. var manager = this.getScene().gamepadManager;
  102470. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  102471. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  102472. var webVrController = gamepad;
  102473. if (webVrController.defaultModel) {
  102474. webVrController.defaultModel.setEnabled(false);
  102475. }
  102476. if (webVrController.hand === "right") {
  102477. _this._rightController = null;
  102478. }
  102479. if (webVrController.hand === "left") {
  102480. _this._leftController = null;
  102481. }
  102482. var controllerIndex = _this.controllers.indexOf(webVrController);
  102483. if (controllerIndex !== -1) {
  102484. _this.controllers.splice(controllerIndex, 1);
  102485. }
  102486. }
  102487. });
  102488. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  102489. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  102490. var webVrController_1 = gamepad;
  102491. if (!_this.webVROptions.trackPosition) {
  102492. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  102493. // Cache must be updated before rendering controllers to avoid them being one frame behind
  102494. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  102495. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  102496. _this._updateCache();
  102497. });
  102498. }
  102499. }
  102500. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  102501. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  102502. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  102503. if (_this.webVROptions.controllerMeshes) {
  102504. if (webVrController_1.defaultModel) {
  102505. webVrController_1.defaultModel.setEnabled(true);
  102506. }
  102507. else {
  102508. // Load the meshes
  102509. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  102510. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  102511. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  102512. if (_this.webVROptions.defaultLightingOnControllers) {
  102513. if (!_this._lightOnControllers) {
  102514. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  102515. }
  102516. var activateLightOnSubMeshes_1 = function (mesh, light) {
  102517. var children = mesh.getChildren();
  102518. if (children && children.length !== 0) {
  102519. children.forEach(function (mesh) {
  102520. light.includedOnlyMeshes.push(mesh);
  102521. activateLightOnSubMeshes_1(mesh, light);
  102522. });
  102523. }
  102524. };
  102525. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  102526. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  102527. }
  102528. });
  102529. }
  102530. }
  102531. webVrController_1.attachToPoseControlledCamera(_this);
  102532. // since this is async - sanity check. Is the controller already stored?
  102533. if (_this.controllers.indexOf(webVrController_1) === -1) {
  102534. //add to the controllers array
  102535. _this.controllers.push(webVrController_1);
  102536. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  102537. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  102538. // So we're overriding setting left & right manually to be sure
  102539. var firstViveWandDetected = false;
  102540. for (var i = 0; i < _this.controllers.length; i++) {
  102541. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  102542. if (!firstViveWandDetected) {
  102543. firstViveWandDetected = true;
  102544. _this.controllers[i].hand = "left";
  102545. }
  102546. else {
  102547. _this.controllers[i].hand = "right";
  102548. }
  102549. }
  102550. }
  102551. //did we find enough controllers? Great! let the developer know.
  102552. if (_this.controllers.length >= 2) {
  102553. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  102554. }
  102555. }
  102556. }
  102557. });
  102558. };
  102559. return WebVRFreeCamera;
  102560. }(BABYLON.FreeCamera));
  102561. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  102562. })(BABYLON || (BABYLON = {}));
  102563. //# sourceMappingURL=babylon.webVRCamera.js.map
  102564. var BABYLON;
  102565. (function (BABYLON) {
  102566. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  102567. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  102568. });
  102569. // We're mainly based on the logic defined into the FreeCamera code
  102570. /**
  102571. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  102572. * being tilted forward or back and left or right.
  102573. */
  102574. var DeviceOrientationCamera = /** @class */ (function (_super) {
  102575. __extends(DeviceOrientationCamera, _super);
  102576. /**
  102577. * Creates a new device orientation camera
  102578. * @param name The name of the camera
  102579. * @param position The start position camera
  102580. * @param scene The scene the camera belongs to
  102581. */
  102582. function DeviceOrientationCamera(name, position, scene) {
  102583. var _this = _super.call(this, name, position, scene) || this;
  102584. _this._quaternionCache = new BABYLON.Quaternion();
  102585. _this.inputs.addDeviceOrientation();
  102586. return _this;
  102587. }
  102588. /**
  102589. * Gets the current instance class name ("DeviceOrientationCamera").
  102590. * This helps avoiding instanceof at run time.
  102591. * @returns the class name
  102592. */
  102593. DeviceOrientationCamera.prototype.getClassName = function () {
  102594. return "DeviceOrientationCamera";
  102595. };
  102596. /**
  102597. * @hidden
  102598. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  102599. */
  102600. DeviceOrientationCamera.prototype._checkInputs = function () {
  102601. _super.prototype._checkInputs.call(this);
  102602. this._quaternionCache.copyFrom(this.rotationQuaternion);
  102603. if (this._initialQuaternion) {
  102604. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  102605. }
  102606. };
  102607. /**
  102608. * Reset the camera to its default orientation on the specified axis only.
  102609. * @param axis The axis to reset
  102610. */
  102611. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  102612. var _this = this;
  102613. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  102614. //can only work if this camera has a rotation quaternion already.
  102615. if (!this.rotationQuaternion)
  102616. return;
  102617. if (!this._initialQuaternion) {
  102618. this._initialQuaternion = new BABYLON.Quaternion();
  102619. }
  102620. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  102621. ['x', 'y', 'z'].forEach(function (axisName) {
  102622. if (!axis[axisName]) {
  102623. _this._initialQuaternion[axisName] = 0;
  102624. }
  102625. else {
  102626. _this._initialQuaternion[axisName] *= -1;
  102627. }
  102628. });
  102629. this._initialQuaternion.normalize();
  102630. //force rotation update
  102631. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  102632. };
  102633. return DeviceOrientationCamera;
  102634. }(BABYLON.FreeCamera));
  102635. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  102636. })(BABYLON || (BABYLON = {}));
  102637. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  102638. var BABYLON;
  102639. (function (BABYLON) {
  102640. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  102641. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  102642. });
  102643. /**
  102644. * Camera used to simulate VR rendering (based on FreeCamera)
  102645. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  102646. */
  102647. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  102648. __extends(VRDeviceOrientationFreeCamera, _super);
  102649. /**
  102650. * Creates a new VRDeviceOrientationFreeCamera
  102651. * @param name defines camera name
  102652. * @param position defines the start position of the camera
  102653. * @param scene defines the scene the camera belongs to
  102654. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  102655. * @param vrCameraMetrics defines the vr metrics associated to the camera
  102656. */
  102657. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  102658. if (compensateDistortion === void 0) { compensateDistortion = true; }
  102659. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  102660. var _this = _super.call(this, name, position, scene) || this;
  102661. vrCameraMetrics.compensateDistortion = compensateDistortion;
  102662. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  102663. return _this;
  102664. }
  102665. /**
  102666. * Gets camera class name
  102667. * @returns VRDeviceOrientationFreeCamera
  102668. */
  102669. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  102670. return "VRDeviceOrientationFreeCamera";
  102671. };
  102672. return VRDeviceOrientationFreeCamera;
  102673. }(BABYLON.DeviceOrientationCamera));
  102674. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  102675. })(BABYLON || (BABYLON = {}));
  102676. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  102677. var BABYLON;
  102678. (function (BABYLON) {
  102679. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  102680. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  102681. });
  102682. /**
  102683. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  102684. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  102685. */
  102686. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  102687. __extends(VRDeviceOrientationArcRotateCamera, _super);
  102688. /**
  102689. * Creates a new VRDeviceOrientationArcRotateCamera
  102690. * @param name defines camera name
  102691. * @param alpha defines the camera rotation along the logitudinal axis
  102692. * @param beta defines the camera rotation along the latitudinal axis
  102693. * @param radius defines the camera distance from its target
  102694. * @param target defines the camera target
  102695. * @param scene defines the scene the camera belongs to
  102696. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  102697. * @param vrCameraMetrics defines the vr metrics associated to the camera
  102698. */
  102699. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  102700. if (compensateDistortion === void 0) { compensateDistortion = true; }
  102701. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  102702. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  102703. vrCameraMetrics.compensateDistortion = compensateDistortion;
  102704. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  102705. _this.inputs.addVRDeviceOrientation();
  102706. return _this;
  102707. }
  102708. /**
  102709. * Gets camera class name
  102710. * @returns VRDeviceOrientationArcRotateCamera
  102711. */
  102712. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  102713. return "VRDeviceOrientationArcRotateCamera";
  102714. };
  102715. return VRDeviceOrientationArcRotateCamera;
  102716. }(BABYLON.ArcRotateCamera));
  102717. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  102718. })(BABYLON || (BABYLON = {}));
  102719. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  102720. var BABYLON;
  102721. (function (BABYLON) {
  102722. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  102723. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  102724. });
  102725. /**
  102726. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  102727. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  102728. */
  102729. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  102730. __extends(VRDeviceOrientationGamepadCamera, _super);
  102731. /**
  102732. * Creates a new VRDeviceOrientationGamepadCamera
  102733. * @param name defines camera name
  102734. * @param position defines the start position of the camera
  102735. * @param scene defines the scene the camera belongs to
  102736. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  102737. * @param vrCameraMetrics defines the vr metrics associated to the camera
  102738. */
  102739. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  102740. if (compensateDistortion === void 0) { compensateDistortion = true; }
  102741. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  102742. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  102743. _this.inputs.addGamepad();
  102744. return _this;
  102745. }
  102746. /**
  102747. * Gets camera class name
  102748. * @returns VRDeviceOrientationGamepadCamera
  102749. */
  102750. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  102751. return "VRDeviceOrientationGamepadCamera";
  102752. };
  102753. return VRDeviceOrientationGamepadCamera;
  102754. }(BABYLON.VRDeviceOrientationFreeCamera));
  102755. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  102756. })(BABYLON || (BABYLON = {}));
  102757. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  102758. var BABYLON;
  102759. (function (BABYLON) {
  102760. var VRExperienceHelperGazer = /** @class */ (function () {
  102761. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  102762. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  102763. this.scene = scene;
  102764. /** @hidden */
  102765. this._pointerDownOnMeshAsked = false;
  102766. /** @hidden */
  102767. this._isActionableMesh = false;
  102768. /** @hidden */
  102769. this._teleportationRequestInitiated = false;
  102770. /** @hidden */
  102771. this._teleportationBackRequestInitiated = false;
  102772. /** @hidden */
  102773. this._rotationRightAsked = false;
  102774. /** @hidden */
  102775. this._rotationLeftAsked = false;
  102776. /** @hidden */
  102777. this._dpadPressed = true;
  102778. /** @hidden */
  102779. this._activePointer = false;
  102780. this._id = VRExperienceHelperGazer._idCounter++;
  102781. // Gaze tracker
  102782. if (!gazeTrackerToClone) {
  102783. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  102784. this._gazeTracker.bakeCurrentTransformIntoVertices();
  102785. this._gazeTracker.isPickable = false;
  102786. this._gazeTracker.isVisible = false;
  102787. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  102788. targetMat.specularColor = BABYLON.Color3.Black();
  102789. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  102790. targetMat.backFaceCulling = false;
  102791. this._gazeTracker.material = targetMat;
  102792. }
  102793. else {
  102794. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  102795. }
  102796. }
  102797. /** @hidden */
  102798. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  102799. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  102800. };
  102801. /** @hidden */
  102802. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  102803. this._pointerDownOnMeshAsked = true;
  102804. if (this._currentHit) {
  102805. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  102806. }
  102807. };
  102808. /** @hidden */
  102809. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  102810. if (this._currentHit) {
  102811. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  102812. }
  102813. this._pointerDownOnMeshAsked = false;
  102814. };
  102815. /** @hidden */
  102816. VRExperienceHelperGazer.prototype._activatePointer = function () {
  102817. this._activePointer = true;
  102818. };
  102819. /** @hidden */
  102820. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  102821. this._activePointer = false;
  102822. };
  102823. /** @hidden */
  102824. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  102825. if (distance === void 0) { distance = 100; }
  102826. };
  102827. VRExperienceHelperGazer.prototype.dispose = function () {
  102828. this._interactionsEnabled = false;
  102829. this._teleportationEnabled = false;
  102830. if (this._gazeTracker) {
  102831. this._gazeTracker.dispose();
  102832. }
  102833. };
  102834. VRExperienceHelperGazer._idCounter = 0;
  102835. return VRExperienceHelperGazer;
  102836. }());
  102837. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  102838. __extends(VRExperienceHelperControllerGazer, _super);
  102839. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  102840. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  102841. _this.webVRController = webVRController;
  102842. // Laser pointer
  102843. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  102844. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  102845. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  102846. laserPointerMaterial.alpha = 0.6;
  102847. _this._laserPointer.material = laserPointerMaterial;
  102848. _this._laserPointer.rotation.x = Math.PI / 2;
  102849. _this._laserPointer.position.z = -0.5;
  102850. _this._laserPointer.isVisible = false;
  102851. _this._laserPointer.isPickable = false;
  102852. if (!webVRController.mesh) {
  102853. // Create an empty mesh that is used prior to loading the high quality model
  102854. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  102855. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  102856. preloadPointerPose.rotation.x = -0.7;
  102857. preloadMesh.addChild(preloadPointerPose);
  102858. webVRController.attachToMesh(preloadMesh);
  102859. }
  102860. _this._setLaserPointerParent(webVRController.mesh);
  102861. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  102862. _this._setLaserPointerParent(mesh);
  102863. });
  102864. return _this;
  102865. }
  102866. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  102867. return this.webVRController.getForwardRay(length);
  102868. };
  102869. /** @hidden */
  102870. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  102871. _super.prototype._activatePointer.call(this);
  102872. this._laserPointer.isVisible = true;
  102873. };
  102874. /** @hidden */
  102875. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  102876. _super.prototype._deactivatePointer.call(this);
  102877. this._laserPointer.isVisible = false;
  102878. };
  102879. /** @hidden */
  102880. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  102881. this._laserPointer.material.emissiveColor = color;
  102882. };
  102883. /** @hidden */
  102884. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  102885. var makeNotPick = function (root) {
  102886. root.isPickable = false;
  102887. root.getChildMeshes().forEach(function (c) {
  102888. makeNotPick(c);
  102889. });
  102890. };
  102891. makeNotPick(mesh);
  102892. var childMeshes = mesh.getChildMeshes();
  102893. this.webVRController._pointingPoseNode = null;
  102894. for (var i = 0; i < childMeshes.length; i++) {
  102895. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  102896. mesh = childMeshes[i];
  102897. this.webVRController._pointingPoseNode = mesh;
  102898. break;
  102899. }
  102900. }
  102901. this._laserPointer.parent = mesh;
  102902. };
  102903. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  102904. if (distance === void 0) { distance = 100; }
  102905. this._laserPointer.scaling.y = distance;
  102906. this._laserPointer.position.z = -distance / 2;
  102907. };
  102908. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  102909. _super.prototype.dispose.call(this);
  102910. this._laserPointer.dispose();
  102911. if (this._meshAttachedObserver) {
  102912. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  102913. }
  102914. };
  102915. return VRExperienceHelperControllerGazer;
  102916. }(VRExperienceHelperGazer));
  102917. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  102918. __extends(VRExperienceHelperCameraGazer, _super);
  102919. function VRExperienceHelperCameraGazer(getCamera, scene) {
  102920. var _this = _super.call(this, scene) || this;
  102921. _this.getCamera = getCamera;
  102922. return _this;
  102923. }
  102924. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  102925. var camera = this.getCamera();
  102926. if (camera) {
  102927. return camera.getForwardRay(length);
  102928. }
  102929. else {
  102930. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  102931. }
  102932. };
  102933. return VRExperienceHelperCameraGazer;
  102934. }(VRExperienceHelperGazer));
  102935. /**
  102936. * Helps to quickly add VR support to an existing scene.
  102937. * See http://doc.babylonjs.com/how_to/webvr_helper
  102938. */
  102939. var VRExperienceHelper = /** @class */ (function () {
  102940. /**
  102941. * Instantiates a VRExperienceHelper.
  102942. * Helps to quickly add VR support to an existing scene.
  102943. * @param scene The scene the VRExperienceHelper belongs to.
  102944. * @param webVROptions Options to modify the vr experience helper's behavior.
  102945. */
  102946. function VRExperienceHelper(scene,
  102947. /** Options to modify the vr experience helper's behavior. */
  102948. webVROptions) {
  102949. if (webVROptions === void 0) { webVROptions = {}; }
  102950. var _this = this;
  102951. this.webVROptions = webVROptions;
  102952. // Can the system support WebVR, even if a headset isn't plugged in?
  102953. this._webVRsupported = false;
  102954. // If WebVR is supported, is a headset plugged in and are we ready to present?
  102955. this._webVRready = false;
  102956. // Are we waiting for the requestPresent callback to complete?
  102957. this._webVRrequesting = false;
  102958. // Are we presenting to the headset right now? (this is the vrDevice state)
  102959. this._webVRpresenting = false;
  102960. // Are we presenting in the fullscreen fallback?
  102961. this._fullscreenVRpresenting = false;
  102962. /**
  102963. * Observable raised when entering VR.
  102964. */
  102965. this.onEnteringVRObservable = new BABYLON.Observable();
  102966. /**
  102967. * Observable raised when exiting VR.
  102968. */
  102969. this.onExitingVRObservable = new BABYLON.Observable();
  102970. /**
  102971. * Observable raised when controller mesh is loaded.
  102972. */
  102973. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  102974. this._useCustomVRButton = false;
  102975. this._teleportationRequested = false;
  102976. this._teleportActive = false;
  102977. this._floorMeshesCollection = [];
  102978. this._rotationAllowed = true;
  102979. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  102980. this._isDefaultTeleportationTarget = true;
  102981. this._teleportationFillColor = "#444444";
  102982. this._teleportationBorderColor = "#FFFFFF";
  102983. this._rotationAngle = 0;
  102984. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  102985. this._padSensibilityUp = 0.65;
  102986. this._padSensibilityDown = 0.35;
  102987. this._leftController = null;
  102988. this._rightController = null;
  102989. /**
  102990. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  102991. */
  102992. this.onNewMeshSelected = new BABYLON.Observable();
  102993. /**
  102994. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  102995. */
  102996. this.onNewMeshPicked = new BABYLON.Observable();
  102997. /**
  102998. * Observable raised before camera teleportation
  102999. */
  103000. this.onBeforeCameraTeleport = new BABYLON.Observable();
  103001. /**
  103002. * Observable raised after camera teleportation
  103003. */
  103004. this.onAfterCameraTeleport = new BABYLON.Observable();
  103005. /**
  103006. * Observable raised when current selected mesh gets unselected
  103007. */
  103008. this.onSelectedMeshUnselected = new BABYLON.Observable();
  103009. /**
  103010. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  103011. */
  103012. this.teleportationEnabled = true;
  103013. this._teleportationInitialized = false;
  103014. this._interactionsEnabled = false;
  103015. this._interactionsRequested = false;
  103016. this._displayGaze = true;
  103017. this._displayLaserPointer = true;
  103018. /**
  103019. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  103020. */
  103021. this.updateGazeTrackerScale = true;
  103022. this._onResize = function () {
  103023. _this.moveButtonToBottomRight();
  103024. if (_this._fullscreenVRpresenting && _this._webVRready) {
  103025. _this.exitVR();
  103026. }
  103027. };
  103028. this._onFullscreenChange = function () {
  103029. if (document.fullscreen !== undefined) {
  103030. _this._fullscreenVRpresenting = document.fullscreen;
  103031. }
  103032. else if (document.mozFullScreen !== undefined) {
  103033. _this._fullscreenVRpresenting = document.mozFullScreen;
  103034. }
  103035. else if (document.webkitIsFullScreen !== undefined) {
  103036. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  103037. }
  103038. else if (document.msIsFullScreen !== undefined) {
  103039. _this._fullscreenVRpresenting = document.msIsFullScreen;
  103040. }
  103041. else if (document.msFullscreenElement !== undefined) {
  103042. _this._fullscreenVRpresenting = document.msFullscreenElement;
  103043. }
  103044. if (!_this._fullscreenVRpresenting && _this._canvas) {
  103045. _this.exitVR();
  103046. if (!_this._useCustomVRButton) {
  103047. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  103048. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  103049. }
  103050. }
  103051. };
  103052. this.beforeRender = function () {
  103053. if (_this._leftController && _this._leftController._activePointer) {
  103054. _this._castRayAndSelectObject(_this._leftController);
  103055. }
  103056. if (_this._rightController && _this._rightController._activePointer) {
  103057. _this._castRayAndSelectObject(_this._rightController);
  103058. }
  103059. if (_this._noControllerIsActive) {
  103060. _this._castRayAndSelectObject(_this._cameraGazer);
  103061. }
  103062. else {
  103063. _this._cameraGazer._gazeTracker.isVisible = false;
  103064. }
  103065. };
  103066. this._onNewGamepadConnected = function (gamepad) {
  103067. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  103068. if (gamepad.leftStick) {
  103069. gamepad.onleftstickchanged(function (stickValues) {
  103070. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  103071. // Listening to classic/xbox gamepad only if no VR controller is active
  103072. if ((!_this._leftController && !_this._rightController) ||
  103073. ((_this._leftController && !_this._leftController._activePointer) &&
  103074. (_this._rightController && !_this._rightController._activePointer))) {
  103075. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  103076. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  103077. }
  103078. }
  103079. });
  103080. }
  103081. if (gamepad.rightStick) {
  103082. gamepad.onrightstickchanged(function (stickValues) {
  103083. if (_this._teleportationInitialized) {
  103084. _this._checkRotate(stickValues, _this._cameraGazer);
  103085. }
  103086. });
  103087. }
  103088. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  103089. gamepad.onbuttondown(function (buttonPressed) {
  103090. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  103091. _this._cameraGazer._selectionPointerDown();
  103092. }
  103093. });
  103094. gamepad.onbuttonup(function (buttonPressed) {
  103095. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  103096. _this._cameraGazer._selectionPointerUp();
  103097. }
  103098. });
  103099. }
  103100. }
  103101. else {
  103102. var webVRController = gamepad;
  103103. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  103104. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  103105. _this._rightController = controller;
  103106. }
  103107. else {
  103108. _this._leftController = controller;
  103109. }
  103110. _this._tryEnableInteractionOnController(controller);
  103111. }
  103112. };
  103113. // 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
  103114. this._tryEnableInteractionOnController = function (controller) {
  103115. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  103116. _this._enableInteractionOnController(controller);
  103117. }
  103118. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  103119. _this._enableTeleportationOnController(controller);
  103120. }
  103121. };
  103122. this._onNewGamepadDisconnected = function (gamepad) {
  103123. if (gamepad instanceof BABYLON.WebVRController) {
  103124. if (gamepad.hand === "left" && _this._leftController != null) {
  103125. _this._leftController.dispose();
  103126. _this._leftController = null;
  103127. }
  103128. if (gamepad.hand === "right" && _this._rightController != null) {
  103129. _this._rightController.dispose();
  103130. _this._rightController = null;
  103131. }
  103132. }
  103133. };
  103134. this._workingVector = BABYLON.Vector3.Zero();
  103135. this._workingQuaternion = BABYLON.Quaternion.Identity();
  103136. this._workingMatrix = BABYLON.Matrix.Identity();
  103137. this._scene = scene;
  103138. this._canvas = scene.getEngine().getRenderingCanvas();
  103139. // Parse options
  103140. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  103141. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  103142. }
  103143. if (webVROptions.createDeviceOrientationCamera === undefined) {
  103144. webVROptions.createDeviceOrientationCamera = true;
  103145. }
  103146. if (webVROptions.laserToggle === undefined) {
  103147. webVROptions.laserToggle = true;
  103148. }
  103149. if (webVROptions.defaultHeight === undefined) {
  103150. webVROptions.defaultHeight = 1.7;
  103151. }
  103152. if (webVROptions.useCustomVRButton) {
  103153. this._useCustomVRButton = true;
  103154. if (webVROptions.customVRButton) {
  103155. this._btnVR = webVROptions.customVRButton;
  103156. }
  103157. }
  103158. if (webVROptions.rayLength) {
  103159. this._rayLength = webVROptions.rayLength;
  103160. }
  103161. this._defaultHeight = webVROptions.defaultHeight;
  103162. if (webVROptions.positionScale) {
  103163. this._rayLength *= webVROptions.positionScale;
  103164. this._defaultHeight *= webVROptions.positionScale;
  103165. }
  103166. this._hasEnteredVR = false;
  103167. // Set position
  103168. if (this._scene.activeCamera) {
  103169. this._position = this._scene.activeCamera.position.clone();
  103170. }
  103171. else {
  103172. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  103173. }
  103174. // Set non-vr camera
  103175. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  103176. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  103177. // Copy data from existing camera
  103178. if (this._scene.activeCamera) {
  103179. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  103180. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  103181. // Set rotation from previous camera
  103182. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  103183. var targetCamera = this._scene.activeCamera;
  103184. if (targetCamera.rotationQuaternion) {
  103185. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  103186. }
  103187. else {
  103188. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  103189. }
  103190. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  103191. }
  103192. }
  103193. this._scene.activeCamera = this._deviceOrientationCamera;
  103194. if (this._canvas) {
  103195. this._scene.activeCamera.attachControl(this._canvas);
  103196. }
  103197. }
  103198. else {
  103199. this._existingCamera = this._scene.activeCamera;
  103200. }
  103201. // Create VR cameras
  103202. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  103203. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  103204. }
  103205. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  103206. this._webVRCamera.useStandingMatrix();
  103207. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  103208. // Create default button
  103209. if (!this._useCustomVRButton) {
  103210. this._btnVR = document.createElement("BUTTON");
  103211. this._btnVR.className = "babylonVRicon";
  103212. this._btnVR.id = "babylonVRiconbtn";
  103213. this._btnVR.title = "Click to switch to VR";
  103214. 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) }";
  103215. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  103216. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  103217. // css += ".babylonVRicon.vrdisplaysupported { }";
  103218. // css += ".babylonVRicon.vrdisplayready { }";
  103219. // css += ".babylonVRicon.vrdisplayrequesting { }";
  103220. var style = document.createElement('style');
  103221. style.appendChild(document.createTextNode(css));
  103222. document.getElementsByTagName('head')[0].appendChild(style);
  103223. this.moveButtonToBottomRight();
  103224. }
  103225. // VR button click event
  103226. if (this._btnVR) {
  103227. this._btnVR.addEventListener("click", function () {
  103228. if (!_this.isInVRMode) {
  103229. _this.enterVR();
  103230. }
  103231. else {
  103232. _this.exitVR();
  103233. }
  103234. });
  103235. }
  103236. // Window events
  103237. window.addEventListener("resize", this._onResize);
  103238. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  103239. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  103240. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  103241. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  103242. document.onmsfullscreenchange = this._onFullscreenChange;
  103243. // Display vr button when headset is connected
  103244. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  103245. this.displayVRButton();
  103246. }
  103247. else {
  103248. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  103249. if (e.vrDisplay) {
  103250. _this.displayVRButton();
  103251. }
  103252. });
  103253. }
  103254. // Exiting VR mode using 'ESC' key on desktop
  103255. this._onKeyDown = function (event) {
  103256. if (event.keyCode === 27 && _this.isInVRMode) {
  103257. _this.exitVR();
  103258. }
  103259. };
  103260. document.addEventListener("keydown", this._onKeyDown);
  103261. // Exiting VR mode double tapping the touch screen
  103262. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  103263. if (_this.isInVRMode) {
  103264. _this.exitVR();
  103265. if (_this._fullscreenVRpresenting) {
  103266. _this._scene.getEngine().switchFullscreen(true);
  103267. }
  103268. }
  103269. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  103270. // Listen for WebVR display changes
  103271. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  103272. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  103273. this._onVRRequestPresentStart = function () {
  103274. _this._webVRrequesting = true;
  103275. _this.updateButtonVisibility();
  103276. };
  103277. this._onVRRequestPresentComplete = function (success) {
  103278. _this._webVRrequesting = false;
  103279. _this.updateButtonVisibility();
  103280. };
  103281. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  103282. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  103283. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  103284. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  103285. scene.onDisposeObservable.add(function () {
  103286. _this.dispose();
  103287. });
  103288. // Gamepad connection events
  103289. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  103290. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  103291. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  103292. this.updateButtonVisibility();
  103293. //create easing functions
  103294. this._circleEase = new BABYLON.CircleEase();
  103295. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  103296. if (this.webVROptions.floorMeshes) {
  103297. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  103298. }
  103299. }
  103300. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  103301. /** Return this.onEnteringVRObservable
  103302. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  103303. */
  103304. get: function () {
  103305. return this.onEnteringVRObservable;
  103306. },
  103307. enumerable: true,
  103308. configurable: true
  103309. });
  103310. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  103311. /** Return this.onExitingVRObservable
  103312. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  103313. */
  103314. get: function () {
  103315. return this.onExitingVRObservable;
  103316. },
  103317. enumerable: true,
  103318. configurable: true
  103319. });
  103320. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  103321. /** Return this.onControllerMeshLoadedObservable
  103322. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  103323. */
  103324. get: function () {
  103325. return this.onControllerMeshLoadedObservable;
  103326. },
  103327. enumerable: true,
  103328. configurable: true
  103329. });
  103330. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  103331. /**
  103332. * The mesh used to display where the user is going to teleport.
  103333. */
  103334. get: function () {
  103335. return this._teleportationTarget;
  103336. },
  103337. /**
  103338. * Sets the mesh to be used to display where the user is going to teleport.
  103339. */
  103340. set: function (value) {
  103341. if (value) {
  103342. value.name = "teleportationTarget";
  103343. this._isDefaultTeleportationTarget = false;
  103344. this._teleportationTarget = value;
  103345. }
  103346. },
  103347. enumerable: true,
  103348. configurable: true
  103349. });
  103350. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  103351. /**
  103352. * 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
  103353. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  103354. * See http://doc.babylonjs.com/resources/baking_transformations
  103355. */
  103356. get: function () {
  103357. return this._cameraGazer._gazeTracker;
  103358. },
  103359. set: function (value) {
  103360. if (value) {
  103361. // Dispose of existing meshes
  103362. if (this._cameraGazer._gazeTracker) {
  103363. this._cameraGazer._gazeTracker.dispose();
  103364. }
  103365. if (this._leftController && this._leftController._gazeTracker) {
  103366. this._leftController._gazeTracker.dispose();
  103367. }
  103368. if (this._rightController && this._rightController._gazeTracker) {
  103369. this._rightController._gazeTracker.dispose();
  103370. }
  103371. // Set and create gaze trackers on head and controllers
  103372. this._cameraGazer._gazeTracker = value;
  103373. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  103374. this._cameraGazer._gazeTracker.isPickable = false;
  103375. this._cameraGazer._gazeTracker.isVisible = false;
  103376. this._cameraGazer._gazeTracker.name = "gazeTracker";
  103377. if (this._leftController) {
  103378. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  103379. }
  103380. if (this._rightController) {
  103381. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  103382. }
  103383. }
  103384. },
  103385. enumerable: true,
  103386. configurable: true
  103387. });
  103388. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  103389. /**
  103390. * The gaze tracking mesh corresponding to the left controller
  103391. */
  103392. get: function () {
  103393. if (this._leftController) {
  103394. return this._leftController._gazeTracker;
  103395. }
  103396. return null;
  103397. },
  103398. enumerable: true,
  103399. configurable: true
  103400. });
  103401. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  103402. /**
  103403. * The gaze tracking mesh corresponding to the right controller
  103404. */
  103405. get: function () {
  103406. if (this._rightController) {
  103407. return this._rightController._gazeTracker;
  103408. }
  103409. return null;
  103410. },
  103411. enumerable: true,
  103412. configurable: true
  103413. });
  103414. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  103415. /**
  103416. * If the ray of the gaze should be displayed.
  103417. */
  103418. get: function () {
  103419. return this._displayGaze;
  103420. },
  103421. /**
  103422. * Sets if the ray of the gaze should be displayed.
  103423. */
  103424. set: function (value) {
  103425. this._displayGaze = value;
  103426. if (!value) {
  103427. this._cameraGazer._gazeTracker.isVisible = false;
  103428. if (this._leftController) {
  103429. this._leftController._gazeTracker.isVisible = false;
  103430. }
  103431. if (this._rightController) {
  103432. this._rightController._gazeTracker.isVisible = false;
  103433. }
  103434. }
  103435. },
  103436. enumerable: true,
  103437. configurable: true
  103438. });
  103439. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  103440. /**
  103441. * If the ray of the LaserPointer should be displayed.
  103442. */
  103443. get: function () {
  103444. return this._displayLaserPointer;
  103445. },
  103446. /**
  103447. * Sets if the ray of the LaserPointer should be displayed.
  103448. */
  103449. set: function (value) {
  103450. this._displayLaserPointer = value;
  103451. if (!value) {
  103452. if (this._rightController) {
  103453. this._rightController._deactivatePointer();
  103454. this._rightController._gazeTracker.isVisible = false;
  103455. }
  103456. if (this._leftController) {
  103457. this._leftController._deactivatePointer();
  103458. this._leftController._gazeTracker.isVisible = false;
  103459. }
  103460. }
  103461. else {
  103462. if (this._rightController) {
  103463. this._rightController._activatePointer();
  103464. }
  103465. if (this._leftController) {
  103466. this._leftController._activatePointer();
  103467. }
  103468. }
  103469. },
  103470. enumerable: true,
  103471. configurable: true
  103472. });
  103473. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  103474. /**
  103475. * The deviceOrientationCamera used as the camera when not in VR.
  103476. */
  103477. get: function () {
  103478. return this._deviceOrientationCamera;
  103479. },
  103480. enumerable: true,
  103481. configurable: true
  103482. });
  103483. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  103484. /**
  103485. * Based on the current WebVR support, returns the current VR camera used.
  103486. */
  103487. get: function () {
  103488. if (this._webVRready) {
  103489. return this._webVRCamera;
  103490. }
  103491. else {
  103492. return this._scene.activeCamera;
  103493. }
  103494. },
  103495. enumerable: true,
  103496. configurable: true
  103497. });
  103498. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  103499. /**
  103500. * The webVRCamera which is used when in VR.
  103501. */
  103502. get: function () {
  103503. return this._webVRCamera;
  103504. },
  103505. enumerable: true,
  103506. configurable: true
  103507. });
  103508. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  103509. /**
  103510. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  103511. */
  103512. get: function () {
  103513. return this._vrDeviceOrientationCamera;
  103514. },
  103515. enumerable: true,
  103516. configurable: true
  103517. });
  103518. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  103519. get: function () {
  103520. var result = this._cameraGazer._teleportationRequestInitiated
  103521. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  103522. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  103523. return result;
  103524. },
  103525. enumerable: true,
  103526. configurable: true
  103527. });
  103528. // Raised when one of the controller has loaded successfully its associated default mesh
  103529. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  103530. if (this._leftController && this._leftController.webVRController == webVRController) {
  103531. if (webVRController.mesh) {
  103532. this._leftController._setLaserPointerParent(webVRController.mesh);
  103533. }
  103534. }
  103535. if (this._rightController && this._rightController.webVRController == webVRController) {
  103536. if (webVRController.mesh) {
  103537. this._rightController._setLaserPointerParent(webVRController.mesh);
  103538. }
  103539. }
  103540. try {
  103541. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  103542. }
  103543. catch (err) {
  103544. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  103545. }
  103546. };
  103547. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  103548. /**
  103549. * Gets a value indicating if we are currently in VR mode.
  103550. */
  103551. get: function () {
  103552. return this._webVRpresenting || this._fullscreenVRpresenting;
  103553. },
  103554. enumerable: true,
  103555. configurable: true
  103556. });
  103557. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  103558. var vrDisplay = this._scene.getEngine().getVRDevice();
  103559. if (vrDisplay) {
  103560. var wasPresenting = this._webVRpresenting;
  103561. this._webVRpresenting = vrDisplay.isPresenting;
  103562. if (wasPresenting && !this._webVRpresenting)
  103563. this.exitVR();
  103564. }
  103565. else {
  103566. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  103567. }
  103568. this.updateButtonVisibility();
  103569. };
  103570. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  103571. this._webVRsupported = eventArgs.vrSupported;
  103572. this._webVRready = !!eventArgs.vrDisplay;
  103573. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  103574. this.updateButtonVisibility();
  103575. };
  103576. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  103577. if (this._canvas && !this._useCustomVRButton) {
  103578. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  103579. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  103580. }
  103581. };
  103582. VRExperienceHelper.prototype.displayVRButton = function () {
  103583. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  103584. document.body.appendChild(this._btnVR);
  103585. this._btnVRDisplayed = true;
  103586. }
  103587. };
  103588. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  103589. if (!this._btnVR || this._useCustomVRButton) {
  103590. return;
  103591. }
  103592. this._btnVR.className = "babylonVRicon";
  103593. if (this.isInVRMode) {
  103594. this._btnVR.className += " vrdisplaypresenting";
  103595. }
  103596. else {
  103597. if (this._webVRready)
  103598. this._btnVR.className += " vrdisplayready";
  103599. if (this._webVRsupported)
  103600. this._btnVR.className += " vrdisplaysupported";
  103601. if (this._webVRrequesting)
  103602. this._btnVR.className += " vrdisplayrequesting";
  103603. }
  103604. };
  103605. /**
  103606. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  103607. * Otherwise, will use the fullscreen API.
  103608. */
  103609. VRExperienceHelper.prototype.enterVR = function () {
  103610. if (this.onEnteringVRObservable) {
  103611. try {
  103612. this.onEnteringVRObservable.notifyObservers(this);
  103613. }
  103614. catch (err) {
  103615. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  103616. }
  103617. }
  103618. if (this._scene.activeCamera) {
  103619. this._position = this._scene.activeCamera.position.clone();
  103620. // make sure that we return to the last active camera
  103621. this._existingCamera = this._scene.activeCamera;
  103622. }
  103623. if (this._webVRrequesting)
  103624. return;
  103625. // If WebVR is supported and a headset is connected
  103626. if (this._webVRready) {
  103627. if (!this._webVRpresenting) {
  103628. this._webVRCamera.position = this._position;
  103629. this._scene.activeCamera = this._webVRCamera;
  103630. }
  103631. }
  103632. else if (this._vrDeviceOrientationCamera) {
  103633. this._vrDeviceOrientationCamera.position = this._position;
  103634. if (this._scene.activeCamera) {
  103635. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  103636. }
  103637. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  103638. this._scene.getEngine().switchFullscreen(true);
  103639. this.updateButtonVisibility();
  103640. }
  103641. if (this._scene.activeCamera && this._canvas) {
  103642. this._scene.activeCamera.attachControl(this._canvas);
  103643. }
  103644. if (this._interactionsEnabled) {
  103645. this._scene.registerBeforeRender(this.beforeRender);
  103646. }
  103647. this._hasEnteredVR = true;
  103648. };
  103649. /**
  103650. * Attempt to exit VR, or fullscreen.
  103651. */
  103652. VRExperienceHelper.prototype.exitVR = function () {
  103653. if (this._hasEnteredVR) {
  103654. if (this.onExitingVRObservable) {
  103655. try {
  103656. this.onExitingVRObservable.notifyObservers(this);
  103657. }
  103658. catch (err) {
  103659. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  103660. }
  103661. }
  103662. if (this._webVRpresenting) {
  103663. this._scene.getEngine().disableVR();
  103664. }
  103665. if (this._scene.activeCamera) {
  103666. this._position = this._scene.activeCamera.position.clone();
  103667. }
  103668. if (this._deviceOrientationCamera) {
  103669. this._deviceOrientationCamera.position = this._position;
  103670. this._scene.activeCamera = this._deviceOrientationCamera;
  103671. if (this._canvas) {
  103672. this._scene.activeCamera.attachControl(this._canvas);
  103673. }
  103674. }
  103675. else if (this._existingCamera) {
  103676. this._existingCamera.position = this._position;
  103677. this._scene.activeCamera = this._existingCamera;
  103678. }
  103679. this.updateButtonVisibility();
  103680. if (this._interactionsEnabled) {
  103681. this._scene.unregisterBeforeRender(this.beforeRender);
  103682. this._cameraGazer._gazeTracker.isVisible = false;
  103683. if (this._leftController) {
  103684. this._leftController._gazeTracker.isVisible = false;
  103685. }
  103686. if (this._rightController) {
  103687. this._rightController._gazeTracker.isVisible = false;
  103688. }
  103689. }
  103690. // resize to update width and height when exiting vr exits fullscreen
  103691. this._scene.getEngine().resize();
  103692. this._hasEnteredVR = false;
  103693. }
  103694. };
  103695. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  103696. /**
  103697. * The position of the vr experience helper.
  103698. */
  103699. get: function () {
  103700. return this._position;
  103701. },
  103702. /**
  103703. * Sets the position of the vr experience helper.
  103704. */
  103705. set: function (value) {
  103706. this._position = value;
  103707. if (this._scene.activeCamera) {
  103708. this._scene.activeCamera.position = value;
  103709. }
  103710. },
  103711. enumerable: true,
  103712. configurable: true
  103713. });
  103714. /**
  103715. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  103716. */
  103717. VRExperienceHelper.prototype.enableInteractions = function () {
  103718. var _this = this;
  103719. if (!this._interactionsEnabled) {
  103720. this._interactionsRequested = true;
  103721. if (this._leftController) {
  103722. this._enableInteractionOnController(this._leftController);
  103723. }
  103724. if (this._rightController) {
  103725. this._enableInteractionOnController(this._rightController);
  103726. }
  103727. this.raySelectionPredicate = function (mesh) {
  103728. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  103729. };
  103730. this.meshSelectionPredicate = function (mesh) {
  103731. return true;
  103732. };
  103733. this._raySelectionPredicate = function (mesh) {
  103734. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  103735. && mesh.name.indexOf("teleportationTarget") === -1
  103736. && mesh.name.indexOf("torusTeleportation") === -1)) {
  103737. return _this.raySelectionPredicate(mesh);
  103738. }
  103739. return false;
  103740. };
  103741. this._interactionsEnabled = true;
  103742. }
  103743. };
  103744. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  103745. get: function () {
  103746. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  103747. },
  103748. enumerable: true,
  103749. configurable: true
  103750. });
  103751. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  103752. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  103753. if (this._floorMeshesCollection[i].id === mesh.id) {
  103754. return true;
  103755. }
  103756. }
  103757. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  103758. return true;
  103759. }
  103760. return false;
  103761. };
  103762. /**
  103763. * Adds a floor mesh to be used for teleportation.
  103764. * @param floorMesh the mesh to be used for teleportation.
  103765. */
  103766. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  103767. if (!this._floorMeshesCollection) {
  103768. return;
  103769. }
  103770. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  103771. return;
  103772. }
  103773. this._floorMeshesCollection.push(floorMesh);
  103774. };
  103775. /**
  103776. * Removes a floor mesh from being used for teleportation.
  103777. * @param floorMesh the mesh to be removed.
  103778. */
  103779. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  103780. if (!this._floorMeshesCollection) {
  103781. return;
  103782. }
  103783. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  103784. if (meshIndex !== -1) {
  103785. this._floorMeshesCollection.splice(meshIndex, 1);
  103786. }
  103787. };
  103788. /**
  103789. * Enables interactions and teleportation using the VR controllers and gaze.
  103790. * @param vrTeleportationOptions options to modify teleportation behavior.
  103791. */
  103792. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  103793. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  103794. if (!this._teleportationInitialized) {
  103795. this._teleportationRequested = true;
  103796. this.enableInteractions();
  103797. if (vrTeleportationOptions.floorMeshName) {
  103798. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  103799. }
  103800. if (vrTeleportationOptions.floorMeshes) {
  103801. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  103802. }
  103803. if (this._leftController != null) {
  103804. this._enableTeleportationOnController(this._leftController);
  103805. }
  103806. if (this._rightController != null) {
  103807. this._enableTeleportationOnController(this._rightController);
  103808. }
  103809. // Creates an image processing post process for the vignette not relying
  103810. // on the main scene configuration for image processing to reduce setup and spaces
  103811. // (gamma/linear) conflicts.
  103812. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  103813. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  103814. imageProcessingConfiguration.vignetteEnabled = true;
  103815. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  103816. this._webVRCamera.detachPostProcess(this._postProcessMove);
  103817. this._teleportationInitialized = true;
  103818. if (this._isDefaultTeleportationTarget) {
  103819. this._createTeleportationCircles();
  103820. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  103821. }
  103822. }
  103823. };
  103824. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  103825. var _this = this;
  103826. var controllerMesh = controller.webVRController.mesh;
  103827. if (controllerMesh) {
  103828. controller._interactionsEnabled = true;
  103829. controller._activatePointer();
  103830. if (this.webVROptions.laserToggle) {
  103831. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  103832. // Enabling / disabling laserPointer
  103833. if (_this._displayLaserPointer && stateObject.value === 1) {
  103834. if (controller._activePointer) {
  103835. controller._deactivatePointer();
  103836. }
  103837. else {
  103838. controller._activatePointer();
  103839. }
  103840. if (_this.displayGaze) {
  103841. controller._gazeTracker.isVisible = controller._activePointer;
  103842. }
  103843. }
  103844. });
  103845. }
  103846. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  103847. var gazer = controller;
  103848. if (_this._noControllerIsActive) {
  103849. gazer = _this._cameraGazer;
  103850. }
  103851. if (!gazer._pointerDownOnMeshAsked) {
  103852. if (stateObject.value > _this._padSensibilityUp) {
  103853. gazer._selectionPointerDown();
  103854. }
  103855. }
  103856. else if (stateObject.value < _this._padSensibilityDown) {
  103857. gazer._selectionPointerUp();
  103858. }
  103859. });
  103860. }
  103861. };
  103862. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  103863. // Dont teleport if another gaze already requested teleportation
  103864. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  103865. return;
  103866. }
  103867. if (!gazer._teleportationRequestInitiated) {
  103868. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  103869. gazer._activatePointer();
  103870. gazer._teleportationRequestInitiated = true;
  103871. }
  103872. }
  103873. else {
  103874. // Listening to the proper controller values changes to confirm teleportation
  103875. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  103876. if (this._teleportActive) {
  103877. this.teleportCamera(this._haloCenter);
  103878. }
  103879. gazer._teleportationRequestInitiated = false;
  103880. }
  103881. }
  103882. };
  103883. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  103884. // Only rotate when user is not currently selecting a teleportation location
  103885. if (gazer._teleportationRequestInitiated) {
  103886. return;
  103887. }
  103888. if (!gazer._rotationLeftAsked) {
  103889. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  103890. gazer._rotationLeftAsked = true;
  103891. if (this._rotationAllowed) {
  103892. this._rotateCamera(false);
  103893. }
  103894. }
  103895. }
  103896. else {
  103897. if (stateObject.x > -this._padSensibilityDown) {
  103898. gazer._rotationLeftAsked = false;
  103899. }
  103900. }
  103901. if (!gazer._rotationRightAsked) {
  103902. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  103903. gazer._rotationRightAsked = true;
  103904. if (this._rotationAllowed) {
  103905. this._rotateCamera(true);
  103906. }
  103907. }
  103908. }
  103909. else {
  103910. if (stateObject.x < this._padSensibilityDown) {
  103911. gazer._rotationRightAsked = false;
  103912. }
  103913. }
  103914. };
  103915. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  103916. // Only teleport backwards when user is not currently selecting a teleportation location
  103917. if (gazer._teleportationRequestInitiated) {
  103918. return;
  103919. }
  103920. // Teleport backwards
  103921. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  103922. if (!gazer._teleportationBackRequestInitiated) {
  103923. if (!this.currentVRCamera) {
  103924. return;
  103925. }
  103926. // Get rotation and position of the current camera
  103927. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  103928. var position = this.currentVRCamera.position;
  103929. // If the camera has device position, use that instead
  103930. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  103931. rotation = this.currentVRCamera.deviceRotationQuaternion;
  103932. position = this.currentVRCamera.devicePosition;
  103933. }
  103934. // Get matrix with only the y rotation of the device rotation
  103935. rotation.toEulerAnglesToRef(this._workingVector);
  103936. this._workingVector.z = 0;
  103937. this._workingVector.x = 0;
  103938. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  103939. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  103940. // Rotate backwards ray by device rotation to cast at the ground behind the user
  103941. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  103942. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  103943. var ray = new BABYLON.Ray(position, this._workingVector);
  103944. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  103945. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  103946. this.teleportCamera(hit.pickedPoint);
  103947. }
  103948. gazer._teleportationBackRequestInitiated = true;
  103949. }
  103950. }
  103951. else {
  103952. gazer._teleportationBackRequestInitiated = false;
  103953. }
  103954. };
  103955. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  103956. var _this = this;
  103957. var controllerMesh = controller.webVRController.mesh;
  103958. if (controllerMesh) {
  103959. if (!controller._interactionsEnabled) {
  103960. this._enableInteractionOnController(controller);
  103961. }
  103962. controller._interactionsEnabled = true;
  103963. controller._teleportationEnabled = true;
  103964. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  103965. controller._dpadPressed = false;
  103966. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  103967. controller._dpadPressed = stateObject.pressed;
  103968. if (!controller._dpadPressed) {
  103969. controller._rotationLeftAsked = false;
  103970. controller._rotationRightAsked = false;
  103971. controller._teleportationBackRequestInitiated = false;
  103972. }
  103973. });
  103974. }
  103975. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  103976. if (_this.teleportationEnabled) {
  103977. _this._checkTeleportBackwards(stateObject, controller);
  103978. _this._checkTeleportWithRay(stateObject, controller);
  103979. }
  103980. _this._checkRotate(stateObject, controller);
  103981. });
  103982. }
  103983. };
  103984. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  103985. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  103986. this._teleportationTarget.isPickable = false;
  103987. var length = 512;
  103988. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  103989. dynamicTexture.hasAlpha = true;
  103990. var context = dynamicTexture.getContext();
  103991. var centerX = length / 2;
  103992. var centerY = length / 2;
  103993. var radius = 200;
  103994. context.beginPath();
  103995. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  103996. context.fillStyle = this._teleportationFillColor;
  103997. context.fill();
  103998. context.lineWidth = 10;
  103999. context.strokeStyle = this._teleportationBorderColor;
  104000. context.stroke();
  104001. context.closePath();
  104002. dynamicTexture.update();
  104003. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  104004. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  104005. this._teleportationTarget.material = teleportationCircleMaterial;
  104006. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  104007. torus.isPickable = false;
  104008. torus.parent = this._teleportationTarget;
  104009. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  104010. var keys = [];
  104011. keys.push({
  104012. frame: 0,
  104013. value: 0
  104014. });
  104015. keys.push({
  104016. frame: 30,
  104017. value: 0.4
  104018. });
  104019. keys.push({
  104020. frame: 60,
  104021. value: 0
  104022. });
  104023. animationInnerCircle.setKeys(keys);
  104024. var easingFunction = new BABYLON.SineEase();
  104025. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  104026. animationInnerCircle.setEasingFunction(easingFunction);
  104027. torus.animations = [];
  104028. torus.animations.push(animationInnerCircle);
  104029. this._scene.beginAnimation(torus, 0, 60, true);
  104030. this._hideTeleportationTarget();
  104031. };
  104032. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  104033. this._teleportActive = true;
  104034. if (this._teleportationInitialized) {
  104035. this._teleportationTarget.isVisible = true;
  104036. if (this._isDefaultTeleportationTarget) {
  104037. this._teleportationTarget.getChildren()[0].isVisible = true;
  104038. }
  104039. }
  104040. };
  104041. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  104042. this._teleportActive = false;
  104043. if (this._teleportationInitialized) {
  104044. this._teleportationTarget.isVisible = false;
  104045. if (this._isDefaultTeleportationTarget) {
  104046. this._teleportationTarget.getChildren()[0].isVisible = false;
  104047. }
  104048. }
  104049. };
  104050. VRExperienceHelper.prototype._rotateCamera = function (right) {
  104051. var _this = this;
  104052. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  104053. return;
  104054. }
  104055. if (right) {
  104056. this._rotationAngle++;
  104057. }
  104058. else {
  104059. this._rotationAngle--;
  104060. }
  104061. this.currentVRCamera.animations = [];
  104062. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  104063. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104064. var animationRotationKeys = [];
  104065. animationRotationKeys.push({
  104066. frame: 0,
  104067. value: this.currentVRCamera.rotationQuaternion
  104068. });
  104069. animationRotationKeys.push({
  104070. frame: 6,
  104071. value: target
  104072. });
  104073. animationRotation.setKeys(animationRotationKeys);
  104074. animationRotation.setEasingFunction(this._circleEase);
  104075. this.currentVRCamera.animations.push(animationRotation);
  104076. this._postProcessMove.animations = [];
  104077. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104078. var vignetteWeightKeys = [];
  104079. vignetteWeightKeys.push({
  104080. frame: 0,
  104081. value: 0
  104082. });
  104083. vignetteWeightKeys.push({
  104084. frame: 3,
  104085. value: 4
  104086. });
  104087. vignetteWeightKeys.push({
  104088. frame: 6,
  104089. value: 0
  104090. });
  104091. animationPP.setKeys(vignetteWeightKeys);
  104092. animationPP.setEasingFunction(this._circleEase);
  104093. this._postProcessMove.animations.push(animationPP);
  104094. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104095. var vignetteStretchKeys = [];
  104096. vignetteStretchKeys.push({
  104097. frame: 0,
  104098. value: 0
  104099. });
  104100. vignetteStretchKeys.push({
  104101. frame: 3,
  104102. value: 10
  104103. });
  104104. vignetteStretchKeys.push({
  104105. frame: 6,
  104106. value: 0
  104107. });
  104108. animationPP2.setKeys(vignetteStretchKeys);
  104109. animationPP2.setEasingFunction(this._circleEase);
  104110. this._postProcessMove.animations.push(animationPP2);
  104111. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  104112. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  104113. this._postProcessMove.samples = 4;
  104114. this._webVRCamera.attachPostProcess(this._postProcessMove);
  104115. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  104116. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  104117. });
  104118. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  104119. };
  104120. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  104121. if (hit.pickedPoint) {
  104122. if (gazer._teleportationRequestInitiated) {
  104123. this._displayTeleportationTarget();
  104124. this._haloCenter.copyFrom(hit.pickedPoint);
  104125. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  104126. }
  104127. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  104128. if (pickNormal) {
  104129. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  104130. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  104131. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  104132. }
  104133. this._teleportationTarget.position.y += 0.1;
  104134. }
  104135. };
  104136. /**
  104137. * Teleports the users feet to the desired location
  104138. * @param location The location where the user's feet should be placed
  104139. */
  104140. VRExperienceHelper.prototype.teleportCamera = function (location) {
  104141. var _this = this;
  104142. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  104143. return;
  104144. }
  104145. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  104146. // offset of the headset from the anchor.
  104147. if (this.webVRCamera.leftCamera) {
  104148. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  104149. this._workingVector.subtractInPlace(this.webVRCamera.position);
  104150. location.subtractToRef(this._workingVector, this._workingVector);
  104151. }
  104152. else {
  104153. this._workingVector.copyFrom(location);
  104154. }
  104155. // Add height to account for user's height offset
  104156. if (this.isInVRMode) {
  104157. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  104158. }
  104159. else {
  104160. this._workingVector.y += this._defaultHeight;
  104161. }
  104162. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  104163. // Create animation from the camera's position to the new location
  104164. this.currentVRCamera.animations = [];
  104165. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104166. var animationCameraTeleportationKeys = [{
  104167. frame: 0,
  104168. value: this.currentVRCamera.position
  104169. },
  104170. {
  104171. frame: 11,
  104172. value: this._workingVector
  104173. }
  104174. ];
  104175. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  104176. animationCameraTeleportation.setEasingFunction(this._circleEase);
  104177. this.currentVRCamera.animations.push(animationCameraTeleportation);
  104178. this._postProcessMove.animations = [];
  104179. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104180. var vignetteWeightKeys = [];
  104181. vignetteWeightKeys.push({
  104182. frame: 0,
  104183. value: 0
  104184. });
  104185. vignetteWeightKeys.push({
  104186. frame: 5,
  104187. value: 8
  104188. });
  104189. vignetteWeightKeys.push({
  104190. frame: 11,
  104191. value: 0
  104192. });
  104193. animationPP.setKeys(vignetteWeightKeys);
  104194. this._postProcessMove.animations.push(animationPP);
  104195. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  104196. var vignetteStretchKeys = [];
  104197. vignetteStretchKeys.push({
  104198. frame: 0,
  104199. value: 0
  104200. });
  104201. vignetteStretchKeys.push({
  104202. frame: 5,
  104203. value: 10
  104204. });
  104205. vignetteStretchKeys.push({
  104206. frame: 11,
  104207. value: 0
  104208. });
  104209. animationPP2.setKeys(vignetteStretchKeys);
  104210. this._postProcessMove.animations.push(animationPP2);
  104211. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  104212. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  104213. this._webVRCamera.attachPostProcess(this._postProcessMove);
  104214. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  104215. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  104216. });
  104217. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  104218. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  104219. });
  104220. this._hideTeleportationTarget();
  104221. };
  104222. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  104223. if (normal) {
  104224. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  104225. if (angle < Math.PI / 2) {
  104226. normal.scaleInPlace(-1);
  104227. }
  104228. }
  104229. return normal;
  104230. };
  104231. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  104232. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  104233. return;
  104234. }
  104235. var ray = gazer._getForwardRay(this._rayLength);
  104236. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  104237. if (hit) {
  104238. // Populate the contrllers mesh that can be used for drag/drop
  104239. if (gazer._laserPointer) {
  104240. hit.originMesh = gazer._laserPointer.parent;
  104241. }
  104242. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  104243. }
  104244. gazer._currentHit = hit;
  104245. // Moving the gazeTracker on the mesh face targetted
  104246. if (hit && hit.pickedPoint) {
  104247. if (this._displayGaze) {
  104248. var multiplier = 1;
  104249. gazer._gazeTracker.isVisible = true;
  104250. if (gazer._isActionableMesh) {
  104251. multiplier = 3;
  104252. }
  104253. if (this.updateGazeTrackerScale) {
  104254. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  104255. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  104256. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  104257. }
  104258. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  104259. // To avoid z-fighting
  104260. var deltaFighting = 0.002;
  104261. if (pickNormal) {
  104262. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  104263. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  104264. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  104265. }
  104266. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  104267. if (gazer._gazeTracker.position.x < 0) {
  104268. gazer._gazeTracker.position.x += deltaFighting;
  104269. }
  104270. else {
  104271. gazer._gazeTracker.position.x -= deltaFighting;
  104272. }
  104273. if (gazer._gazeTracker.position.y < 0) {
  104274. gazer._gazeTracker.position.y += deltaFighting;
  104275. }
  104276. else {
  104277. gazer._gazeTracker.position.y -= deltaFighting;
  104278. }
  104279. if (gazer._gazeTracker.position.z < 0) {
  104280. gazer._gazeTracker.position.z += deltaFighting;
  104281. }
  104282. else {
  104283. gazer._gazeTracker.position.z -= deltaFighting;
  104284. }
  104285. }
  104286. // Changing the size of the laser pointer based on the distance from the targetted point
  104287. gazer._updatePointerDistance(hit.distance);
  104288. }
  104289. else {
  104290. gazer._updatePointerDistance();
  104291. gazer._gazeTracker.isVisible = false;
  104292. }
  104293. if (hit && hit.pickedMesh) {
  104294. // The object selected is the floor, we're in a teleportation scenario
  104295. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  104296. // Moving the teleportation area to this targetted point
  104297. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  104298. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  104299. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  104300. }
  104301. gazer._currentMeshSelected = null;
  104302. if (gazer._teleportationRequestInitiated) {
  104303. this._moveTeleportationSelectorTo(hit, gazer, ray);
  104304. }
  104305. return;
  104306. }
  104307. // If not, we're in a selection scenario
  104308. //this._teleportationAllowed = false;
  104309. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  104310. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  104311. this.onNewMeshPicked.notifyObservers(hit);
  104312. gazer._currentMeshSelected = hit.pickedMesh;
  104313. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  104314. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  104315. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  104316. gazer._isActionableMesh = true;
  104317. }
  104318. else {
  104319. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104320. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104321. gazer._isActionableMesh = false;
  104322. }
  104323. try {
  104324. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  104325. }
  104326. catch (err) {
  104327. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  104328. }
  104329. }
  104330. else {
  104331. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  104332. gazer._currentMeshSelected = null;
  104333. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104334. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104335. }
  104336. }
  104337. }
  104338. else {
  104339. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  104340. gazer._currentMeshSelected = null;
  104341. //this._teleportationAllowed = false;
  104342. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104343. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  104344. }
  104345. };
  104346. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  104347. if (mesh) {
  104348. this.onSelectedMeshUnselected.notifyObservers(mesh);
  104349. }
  104350. };
  104351. /**
  104352. * Sets the color of the laser ray from the vr controllers.
  104353. * @param color new color for the ray.
  104354. */
  104355. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  104356. if (this._leftController) {
  104357. this._leftController._setLaserPointerColor(color);
  104358. }
  104359. if (this._rightController) {
  104360. this._rightController._setLaserPointerColor(color);
  104361. }
  104362. };
  104363. /**
  104364. * Sets the color of the ray from the vr headsets gaze.
  104365. * @param color new color for the ray.
  104366. */
  104367. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  104368. if (!this._cameraGazer._gazeTracker.material) {
  104369. return;
  104370. }
  104371. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  104372. if (this._leftController) {
  104373. this._leftController._gazeTracker.material.emissiveColor = color;
  104374. }
  104375. if (this._rightController) {
  104376. this._rightController._gazeTracker.material.emissiveColor = color;
  104377. }
  104378. };
  104379. /**
  104380. * Exits VR and disposes of the vr experience helper
  104381. */
  104382. VRExperienceHelper.prototype.dispose = function () {
  104383. if (this.isInVRMode) {
  104384. this.exitVR();
  104385. }
  104386. if (this._postProcessMove) {
  104387. this._postProcessMove.dispose();
  104388. }
  104389. if (this._webVRCamera) {
  104390. this._webVRCamera.dispose();
  104391. }
  104392. if (this._vrDeviceOrientationCamera) {
  104393. this._vrDeviceOrientationCamera.dispose();
  104394. }
  104395. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  104396. document.body.removeChild(this._btnVR);
  104397. }
  104398. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  104399. this._deviceOrientationCamera.dispose();
  104400. }
  104401. if (this._cameraGazer) {
  104402. this._cameraGazer.dispose();
  104403. }
  104404. if (this._leftController) {
  104405. this._leftController.dispose();
  104406. }
  104407. if (this._rightController) {
  104408. this._rightController.dispose();
  104409. }
  104410. if (this._teleportationTarget) {
  104411. this._teleportationTarget.dispose();
  104412. }
  104413. this._floorMeshesCollection = [];
  104414. document.removeEventListener("keydown", this._onKeyDown);
  104415. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  104416. window.removeEventListener("resize", this._onResize);
  104417. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  104418. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  104419. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  104420. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  104421. document.onmsfullscreenchange = null;
  104422. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  104423. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  104424. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  104425. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  104426. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  104427. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  104428. this._scene.unregisterBeforeRender(this.beforeRender);
  104429. };
  104430. /**
  104431. * Gets the name of the VRExperienceHelper class
  104432. * @returns "VRExperienceHelper"
  104433. */
  104434. VRExperienceHelper.prototype.getClassName = function () {
  104435. return "VRExperienceHelper";
  104436. };
  104437. return VRExperienceHelper;
  104438. }());
  104439. BABYLON.VRExperienceHelper = VRExperienceHelper;
  104440. })(BABYLON || (BABYLON = {}));
  104441. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  104442. // Mainly based on these 2 articles :
  104443. // 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
  104444. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  104445. var BABYLON;
  104446. (function (BABYLON) {
  104447. /**
  104448. * Defines the potential axis of a Joystick
  104449. */
  104450. var JoystickAxis;
  104451. (function (JoystickAxis) {
  104452. /** X axis */
  104453. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  104454. /** Y axis */
  104455. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  104456. /** Z axis */
  104457. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  104458. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  104459. /**
  104460. * Class used to define virtual joystick (used in touch mode)
  104461. */
  104462. var VirtualJoystick = /** @class */ (function () {
  104463. /**
  104464. * Creates a new virtual joystick
  104465. * @param leftJoystick defines that the joystick is for left hand (false by default)
  104466. */
  104467. function VirtualJoystick(leftJoystick) {
  104468. var _this = this;
  104469. if (leftJoystick) {
  104470. this._leftJoystick = true;
  104471. }
  104472. else {
  104473. this._leftJoystick = false;
  104474. }
  104475. VirtualJoystick._globalJoystickIndex++;
  104476. // By default left & right arrow keys are moving the X
  104477. // and up & down keys are moving the Y
  104478. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  104479. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  104480. this.reverseLeftRight = false;
  104481. this.reverseUpDown = false;
  104482. // collections of pointers
  104483. this._touches = new BABYLON.StringDictionary();
  104484. this.deltaPosition = BABYLON.Vector3.Zero();
  104485. this._joystickSensibility = 25;
  104486. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  104487. this._onResize = function (evt) {
  104488. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  104489. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  104490. if (VirtualJoystick.vjCanvas) {
  104491. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  104492. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  104493. }
  104494. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  104495. };
  104496. // injecting a canvas element on top of the canvas 3D game
  104497. if (!VirtualJoystick.vjCanvas) {
  104498. window.addEventListener("resize", this._onResize, false);
  104499. VirtualJoystick.vjCanvas = document.createElement("canvas");
  104500. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  104501. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  104502. VirtualJoystick.vjCanvas.width = window.innerWidth;
  104503. VirtualJoystick.vjCanvas.height = window.innerHeight;
  104504. VirtualJoystick.vjCanvas.style.width = "100%";
  104505. VirtualJoystick.vjCanvas.style.height = "100%";
  104506. VirtualJoystick.vjCanvas.style.position = "absolute";
  104507. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  104508. VirtualJoystick.vjCanvas.style.top = "0px";
  104509. VirtualJoystick.vjCanvas.style.left = "0px";
  104510. VirtualJoystick.vjCanvas.style.zIndex = "5";
  104511. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  104512. // Support for jQuery PEP polyfill
  104513. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  104514. var context = VirtualJoystick.vjCanvas.getContext('2d');
  104515. if (!context) {
  104516. throw new Error("Unable to create canvas for virtual joystick");
  104517. }
  104518. VirtualJoystick.vjCanvasContext = context;
  104519. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  104520. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  104521. document.body.appendChild(VirtualJoystick.vjCanvas);
  104522. }
  104523. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  104524. this.pressed = false;
  104525. // default joystick color
  104526. this._joystickColor = "cyan";
  104527. this._joystickPointerID = -1;
  104528. // current joystick position
  104529. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  104530. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  104531. // origin joystick position
  104532. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  104533. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  104534. this._onPointerDownHandlerRef = function (evt) {
  104535. _this._onPointerDown(evt);
  104536. };
  104537. this._onPointerMoveHandlerRef = function (evt) {
  104538. _this._onPointerMove(evt);
  104539. };
  104540. this._onPointerUpHandlerRef = function (evt) {
  104541. _this._onPointerUp(evt);
  104542. };
  104543. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  104544. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  104545. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  104546. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  104547. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  104548. evt.preventDefault(); // Disables system menu
  104549. }, false);
  104550. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  104551. }
  104552. /**
  104553. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  104554. * @param newJoystickSensibility defines the new sensibility
  104555. */
  104556. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  104557. this._joystickSensibility = newJoystickSensibility;
  104558. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  104559. };
  104560. VirtualJoystick.prototype._onPointerDown = function (e) {
  104561. var positionOnScreenCondition;
  104562. e.preventDefault();
  104563. if (this._leftJoystick === true) {
  104564. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  104565. }
  104566. else {
  104567. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  104568. }
  104569. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  104570. // First contact will be dedicated to the virtual joystick
  104571. this._joystickPointerID = e.pointerId;
  104572. this._joystickPointerStartPos.x = e.clientX;
  104573. this._joystickPointerStartPos.y = e.clientY;
  104574. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  104575. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  104576. this._deltaJoystickVector.x = 0;
  104577. this._deltaJoystickVector.y = 0;
  104578. this.pressed = true;
  104579. this._touches.add(e.pointerId.toString(), e);
  104580. }
  104581. else {
  104582. // You can only trigger the action buttons with a joystick declared
  104583. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  104584. this._action();
  104585. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  104586. }
  104587. }
  104588. };
  104589. VirtualJoystick.prototype._onPointerMove = function (e) {
  104590. // If the current pointer is the one associated to the joystick (first touch contact)
  104591. if (this._joystickPointerID == e.pointerId) {
  104592. this._joystickPointerPos.x = e.clientX;
  104593. this._joystickPointerPos.y = e.clientY;
  104594. this._deltaJoystickVector = this._joystickPointerPos.clone();
  104595. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  104596. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  104597. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  104598. switch (this._axisTargetedByLeftAndRight) {
  104599. case JoystickAxis.X:
  104600. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  104601. break;
  104602. case JoystickAxis.Y:
  104603. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  104604. break;
  104605. case JoystickAxis.Z:
  104606. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  104607. break;
  104608. }
  104609. var directionUpDown = this.reverseUpDown ? 1 : -1;
  104610. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  104611. switch (this._axisTargetedByUpAndDown) {
  104612. case JoystickAxis.X:
  104613. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  104614. break;
  104615. case JoystickAxis.Y:
  104616. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  104617. break;
  104618. case JoystickAxis.Z:
  104619. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  104620. break;
  104621. }
  104622. }
  104623. else {
  104624. var data = this._touches.get(e.pointerId.toString());
  104625. if (data) {
  104626. data.x = e.clientX;
  104627. data.y = e.clientY;
  104628. }
  104629. }
  104630. };
  104631. VirtualJoystick.prototype._onPointerUp = function (e) {
  104632. if (this._joystickPointerID == e.pointerId) {
  104633. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  104634. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  104635. this._joystickPointerID = -1;
  104636. this.pressed = false;
  104637. }
  104638. else {
  104639. var touch = this._touches.get(e.pointerId.toString());
  104640. if (touch) {
  104641. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  104642. }
  104643. }
  104644. this._deltaJoystickVector.x = 0;
  104645. this._deltaJoystickVector.y = 0;
  104646. this._touches.remove(e.pointerId.toString());
  104647. };
  104648. /**
  104649. * Change the color of the virtual joystick
  104650. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  104651. */
  104652. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  104653. this._joystickColor = newColor;
  104654. };
  104655. /**
  104656. * Defines a callback to call when the joystick is touched
  104657. * @param action defines the callback
  104658. */
  104659. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  104660. this._action = action;
  104661. };
  104662. /**
  104663. * Defines which axis you'd like to control for left & right
  104664. * @param axis defines the axis to use
  104665. */
  104666. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  104667. switch (axis) {
  104668. case JoystickAxis.X:
  104669. case JoystickAxis.Y:
  104670. case JoystickAxis.Z:
  104671. this._axisTargetedByLeftAndRight = axis;
  104672. break;
  104673. default:
  104674. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  104675. break;
  104676. }
  104677. };
  104678. /**
  104679. * Defines which axis you'd like to control for up & down
  104680. * @param axis defines the axis to use
  104681. */
  104682. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  104683. switch (axis) {
  104684. case JoystickAxis.X:
  104685. case JoystickAxis.Y:
  104686. case JoystickAxis.Z:
  104687. this._axisTargetedByUpAndDown = axis;
  104688. break;
  104689. default:
  104690. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  104691. break;
  104692. }
  104693. };
  104694. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  104695. var _this = this;
  104696. if (this.pressed) {
  104697. this._touches.forEach(function (key, touch) {
  104698. if (touch.pointerId === _this._joystickPointerID) {
  104699. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  104700. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  104701. VirtualJoystick.vjCanvasContext.beginPath();
  104702. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  104703. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  104704. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  104705. VirtualJoystick.vjCanvasContext.stroke();
  104706. VirtualJoystick.vjCanvasContext.closePath();
  104707. VirtualJoystick.vjCanvasContext.beginPath();
  104708. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  104709. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  104710. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  104711. VirtualJoystick.vjCanvasContext.stroke();
  104712. VirtualJoystick.vjCanvasContext.closePath();
  104713. VirtualJoystick.vjCanvasContext.beginPath();
  104714. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  104715. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  104716. VirtualJoystick.vjCanvasContext.stroke();
  104717. VirtualJoystick.vjCanvasContext.closePath();
  104718. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  104719. }
  104720. else {
  104721. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  104722. VirtualJoystick.vjCanvasContext.beginPath();
  104723. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  104724. VirtualJoystick.vjCanvasContext.beginPath();
  104725. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  104726. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  104727. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  104728. VirtualJoystick.vjCanvasContext.stroke();
  104729. VirtualJoystick.vjCanvasContext.closePath();
  104730. touch.prevX = touch.x;
  104731. touch.prevY = touch.y;
  104732. }
  104733. ;
  104734. });
  104735. }
  104736. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  104737. };
  104738. /**
  104739. * Release internal HTML canvas
  104740. */
  104741. VirtualJoystick.prototype.releaseCanvas = function () {
  104742. if (VirtualJoystick.vjCanvas) {
  104743. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  104744. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  104745. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  104746. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  104747. window.removeEventListener("resize", this._onResize);
  104748. document.body.removeChild(VirtualJoystick.vjCanvas);
  104749. VirtualJoystick.vjCanvas = null;
  104750. }
  104751. };
  104752. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  104753. VirtualJoystick._globalJoystickIndex = 0;
  104754. return VirtualJoystick;
  104755. }());
  104756. BABYLON.VirtualJoystick = VirtualJoystick;
  104757. })(BABYLON || (BABYLON = {}));
  104758. //# sourceMappingURL=babylon.virtualJoystick.js.map
  104759. var BABYLON;
  104760. (function (BABYLON) {
  104761. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  104762. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  104763. });
  104764. /**
  104765. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  104766. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  104767. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  104768. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  104769. */
  104770. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  104771. __extends(VirtualJoysticksCamera, _super);
  104772. /**
  104773. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  104774. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  104775. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  104776. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  104777. * @param name Define the name of the camera in the scene
  104778. * @param position Define the start position of the camera in the scene
  104779. * @param scene Define the scene the camera belongs to
  104780. */
  104781. function VirtualJoysticksCamera(name, position, scene) {
  104782. var _this = _super.call(this, name, position, scene) || this;
  104783. _this.inputs.addVirtualJoystick();
  104784. return _this;
  104785. }
  104786. /**
  104787. * Gets the current object class name.
  104788. * @return the class name
  104789. */
  104790. VirtualJoysticksCamera.prototype.getClassName = function () {
  104791. return "VirtualJoysticksCamera";
  104792. };
  104793. return VirtualJoysticksCamera;
  104794. }(BABYLON.FreeCamera));
  104795. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  104796. })(BABYLON || (BABYLON = {}));
  104797. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  104798. var BABYLON;
  104799. (function (BABYLON) {
  104800. /**
  104801. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  104802. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  104803. */
  104804. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  104805. function FreeCameraVirtualJoystickInput() {
  104806. }
  104807. /**
  104808. * Gets the left stick of the virtual joystick.
  104809. * @returns The virtual Joystick
  104810. */
  104811. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  104812. return this._leftjoystick;
  104813. };
  104814. /**
  104815. * Gets the right stick of the virtual joystick.
  104816. * @returns The virtual Joystick
  104817. */
  104818. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  104819. return this._rightjoystick;
  104820. };
  104821. /**
  104822. * Update the current camera state depending on the inputs that have been used this frame.
  104823. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  104824. */
  104825. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  104826. if (this._leftjoystick) {
  104827. var camera = this.camera;
  104828. var speed = camera._computeLocalCameraSpeed() * 50;
  104829. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  104830. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  104831. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  104832. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  104833. if (!this._leftjoystick.pressed) {
  104834. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  104835. }
  104836. if (!this._rightjoystick.pressed) {
  104837. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  104838. }
  104839. }
  104840. };
  104841. /**
  104842. * Attach the input controls to a specific dom element to get the input from.
  104843. * @param element Defines the element the controls should be listened from
  104844. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  104845. */
  104846. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  104847. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  104848. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  104849. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  104850. this._leftjoystick.setJoystickSensibility(0.15);
  104851. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  104852. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  104853. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  104854. this._rightjoystick.reverseUpDown = true;
  104855. this._rightjoystick.setJoystickSensibility(0.05);
  104856. this._rightjoystick.setJoystickColor("yellow");
  104857. };
  104858. /**
  104859. * Detach the current controls from the specified dom element.
  104860. * @param element Defines the element to stop listening the inputs from
  104861. */
  104862. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  104863. this._leftjoystick.releaseCanvas();
  104864. this._rightjoystick.releaseCanvas();
  104865. };
  104866. /**
  104867. * Gets the class name of the current intput.
  104868. * @returns the class name
  104869. */
  104870. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  104871. return "FreeCameraVirtualJoystickInput";
  104872. };
  104873. /**
  104874. * Get the friendly name associated with the input class.
  104875. * @returns the input friendly name
  104876. */
  104877. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  104878. return "virtualJoystick";
  104879. };
  104880. return FreeCameraVirtualJoystickInput;
  104881. }());
  104882. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  104883. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  104884. })(BABYLON || (BABYLON = {}));
  104885. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  104886. var BABYLON;
  104887. (function (BABYLON) {
  104888. /**
  104889. * Class used to specify simplification options
  104890. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  104891. */
  104892. var SimplificationSettings = /** @class */ (function () {
  104893. /**
  104894. * Creates a SimplificationSettings
  104895. * @param quality expected quality
  104896. * @param distance distance when this optimized version should be used
  104897. * @param optimizeMesh already optimized mesh
  104898. */
  104899. function SimplificationSettings(
  104900. /** expected quality */
  104901. quality,
  104902. /** distance when this optimized version should be used */
  104903. distance,
  104904. /** already optimized mesh */
  104905. optimizeMesh) {
  104906. this.quality = quality;
  104907. this.distance = distance;
  104908. this.optimizeMesh = optimizeMesh;
  104909. }
  104910. return SimplificationSettings;
  104911. }());
  104912. BABYLON.SimplificationSettings = SimplificationSettings;
  104913. /**
  104914. * Queue used to order the simplification tasks
  104915. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  104916. */
  104917. var SimplificationQueue = /** @class */ (function () {
  104918. /**
  104919. * Creates a new queue
  104920. */
  104921. function SimplificationQueue() {
  104922. this.running = false;
  104923. this._simplificationArray = [];
  104924. }
  104925. /**
  104926. * Adds a new simplification task
  104927. * @param task defines a task to add
  104928. */
  104929. SimplificationQueue.prototype.addTask = function (task) {
  104930. this._simplificationArray.push(task);
  104931. };
  104932. /**
  104933. * Execute next task
  104934. */
  104935. SimplificationQueue.prototype.executeNext = function () {
  104936. var task = this._simplificationArray.pop();
  104937. if (task) {
  104938. this.running = true;
  104939. this.runSimplification(task);
  104940. }
  104941. else {
  104942. this.running = false;
  104943. }
  104944. };
  104945. /**
  104946. * Execute a simplification task
  104947. * @param task defines the task to run
  104948. */
  104949. SimplificationQueue.prototype.runSimplification = function (task) {
  104950. var _this = this;
  104951. if (task.parallelProcessing) {
  104952. //parallel simplifier
  104953. task.settings.forEach(function (setting) {
  104954. var simplifier = _this.getSimplifier(task);
  104955. simplifier.simplify(setting, function (newMesh) {
  104956. task.mesh.addLODLevel(setting.distance, newMesh);
  104957. newMesh.isVisible = true;
  104958. //check if it is the last
  104959. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  104960. //all done, run the success callback.
  104961. task.successCallback();
  104962. }
  104963. _this.executeNext();
  104964. });
  104965. });
  104966. }
  104967. else {
  104968. //single simplifier.
  104969. var simplifier = this.getSimplifier(task);
  104970. var runDecimation = function (setting, callback) {
  104971. simplifier.simplify(setting, function (newMesh) {
  104972. task.mesh.addLODLevel(setting.distance, newMesh);
  104973. newMesh.isVisible = true;
  104974. //run the next quality level
  104975. callback();
  104976. });
  104977. };
  104978. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  104979. runDecimation(task.settings[loop.index], function () {
  104980. loop.executeNext();
  104981. });
  104982. }, function () {
  104983. //execution ended, run the success callback.
  104984. if (task.successCallback) {
  104985. task.successCallback();
  104986. }
  104987. _this.executeNext();
  104988. });
  104989. }
  104990. };
  104991. SimplificationQueue.prototype.getSimplifier = function (task) {
  104992. switch (task.simplificationType) {
  104993. case SimplificationType.QUADRATIC:
  104994. default:
  104995. return new QuadraticErrorSimplification(task.mesh);
  104996. }
  104997. };
  104998. return SimplificationQueue;
  104999. }());
  105000. BABYLON.SimplificationQueue = SimplificationQueue;
  105001. /**
  105002. * The implemented types of simplification
  105003. * At the moment only Quadratic Error Decimation is implemented
  105004. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  105005. */
  105006. var SimplificationType;
  105007. (function (SimplificationType) {
  105008. /** Quadratic error decimation */
  105009. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  105010. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  105011. var DecimationTriangle = /** @class */ (function () {
  105012. function DecimationTriangle(vertices) {
  105013. this.vertices = vertices;
  105014. this.error = new Array(4);
  105015. this.deleted = false;
  105016. this.isDirty = false;
  105017. this.deletePending = false;
  105018. this.borderFactor = 0;
  105019. }
  105020. return DecimationTriangle;
  105021. }());
  105022. var DecimationVertex = /** @class */ (function () {
  105023. function DecimationVertex(position, id) {
  105024. this.position = position;
  105025. this.id = id;
  105026. this.isBorder = true;
  105027. this.q = new QuadraticMatrix();
  105028. this.triangleCount = 0;
  105029. this.triangleStart = 0;
  105030. this.originalOffsets = [];
  105031. }
  105032. DecimationVertex.prototype.updatePosition = function (newPosition) {
  105033. this.position.copyFrom(newPosition);
  105034. };
  105035. return DecimationVertex;
  105036. }());
  105037. var QuadraticMatrix = /** @class */ (function () {
  105038. function QuadraticMatrix(data) {
  105039. this.data = new Array(10);
  105040. for (var i = 0; i < 10; ++i) {
  105041. if (data && data[i]) {
  105042. this.data[i] = data[i];
  105043. }
  105044. else {
  105045. this.data[i] = 0;
  105046. }
  105047. }
  105048. }
  105049. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  105050. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  105051. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  105052. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  105053. return det;
  105054. };
  105055. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  105056. for (var i = 0; i < 10; ++i) {
  105057. this.data[i] += matrix.data[i];
  105058. }
  105059. };
  105060. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  105061. for (var i = 0; i < 10; ++i) {
  105062. this.data[i] += data[i];
  105063. }
  105064. };
  105065. QuadraticMatrix.prototype.add = function (matrix) {
  105066. var m = new QuadraticMatrix();
  105067. for (var i = 0; i < 10; ++i) {
  105068. m.data[i] = this.data[i] + matrix.data[i];
  105069. }
  105070. return m;
  105071. };
  105072. QuadraticMatrix.FromData = function (a, b, c, d) {
  105073. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  105074. };
  105075. //returning an array to avoid garbage collection
  105076. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  105077. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  105078. };
  105079. return QuadraticMatrix;
  105080. }());
  105081. var Reference = /** @class */ (function () {
  105082. function Reference(vertexId, triangleId) {
  105083. this.vertexId = vertexId;
  105084. this.triangleId = triangleId;
  105085. }
  105086. return Reference;
  105087. }());
  105088. /**
  105089. * An implementation of the Quadratic Error simplification algorithm.
  105090. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  105091. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  105092. * @author RaananW
  105093. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  105094. */
  105095. var QuadraticErrorSimplification = /** @class */ (function () {
  105096. function QuadraticErrorSimplification(_mesh) {
  105097. this._mesh = _mesh;
  105098. this.syncIterations = 5000;
  105099. this.aggressiveness = 7;
  105100. this.decimationIterations = 100;
  105101. this.boundingBoxEpsilon = BABYLON.Epsilon;
  105102. }
  105103. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  105104. var _this = this;
  105105. this.initDecimatedMesh();
  105106. //iterating through the submeshes array, one after the other.
  105107. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  105108. _this.initWithMesh(loop.index, function () {
  105109. _this.runDecimation(settings, loop.index, function () {
  105110. loop.executeNext();
  105111. });
  105112. }, settings.optimizeMesh);
  105113. }, function () {
  105114. setTimeout(function () {
  105115. successCallback(_this._reconstructedMesh);
  105116. }, 0);
  105117. });
  105118. };
  105119. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  105120. var _this = this;
  105121. var targetCount = ~~(this.triangles.length * settings.quality);
  105122. var deletedTriangles = 0;
  105123. var triangleCount = this.triangles.length;
  105124. var iterationFunction = function (iteration, callback) {
  105125. setTimeout(function () {
  105126. if (iteration % 5 === 0) {
  105127. _this.updateMesh(iteration === 0);
  105128. }
  105129. for (var i = 0; i < _this.triangles.length; ++i) {
  105130. _this.triangles[i].isDirty = false;
  105131. }
  105132. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  105133. var trianglesIterator = function (i) {
  105134. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  105135. var t = _this.triangles[tIdx];
  105136. if (!t)
  105137. return;
  105138. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  105139. return;
  105140. }
  105141. for (var j = 0; j < 3; ++j) {
  105142. if (t.error[j] < threshold) {
  105143. var deleted0 = [];
  105144. var deleted1 = [];
  105145. var v0 = t.vertices[j];
  105146. var v1 = t.vertices[(j + 1) % 3];
  105147. if (v0.isBorder || v1.isBorder)
  105148. continue;
  105149. var p = BABYLON.Vector3.Zero();
  105150. var n = BABYLON.Vector3.Zero();
  105151. var uv = BABYLON.Vector2.Zero();
  105152. var color = new BABYLON.Color4(0, 0, 0, 1);
  105153. _this.calculateError(v0, v1, p, n, uv, color);
  105154. var delTr = new Array();
  105155. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  105156. continue;
  105157. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  105158. continue;
  105159. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  105160. continue;
  105161. var uniqueArray = new Array();
  105162. delTr.forEach(function (deletedT) {
  105163. if (uniqueArray.indexOf(deletedT) === -1) {
  105164. deletedT.deletePending = true;
  105165. uniqueArray.push(deletedT);
  105166. }
  105167. });
  105168. if (uniqueArray.length % 2 !== 0) {
  105169. continue;
  105170. }
  105171. v0.q = v1.q.add(v0.q);
  105172. v0.updatePosition(p);
  105173. var tStart = _this.references.length;
  105174. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  105175. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  105176. var tCount = _this.references.length - tStart;
  105177. if (tCount <= v0.triangleCount) {
  105178. if (tCount) {
  105179. for (var c = 0; c < tCount; c++) {
  105180. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  105181. }
  105182. }
  105183. }
  105184. else {
  105185. v0.triangleStart = tStart;
  105186. }
  105187. v0.triangleCount = tCount;
  105188. break;
  105189. }
  105190. }
  105191. };
  105192. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  105193. }, 0);
  105194. };
  105195. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  105196. if (triangleCount - deletedTriangles <= targetCount)
  105197. loop.breakLoop();
  105198. else {
  105199. iterationFunction(loop.index, function () {
  105200. loop.executeNext();
  105201. });
  105202. }
  105203. }, function () {
  105204. setTimeout(function () {
  105205. //reconstruct this part of the mesh
  105206. _this.reconstructMesh(submeshIndex);
  105207. successCallback();
  105208. }, 0);
  105209. });
  105210. };
  105211. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  105212. var _this = this;
  105213. this.vertices = [];
  105214. this.triangles = [];
  105215. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  105216. var indices = this._mesh.getIndices();
  105217. var submesh = this._mesh.subMeshes[submeshIndex];
  105218. var findInVertices = function (positionToSearch) {
  105219. if (optimizeMesh) {
  105220. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  105221. if (_this.vertices[ii].position.equals(positionToSearch)) {
  105222. return _this.vertices[ii];
  105223. }
  105224. }
  105225. }
  105226. return null;
  105227. };
  105228. var vertexReferences = [];
  105229. var vertexInit = function (i) {
  105230. if (!positionData) {
  105231. return;
  105232. }
  105233. var offset = i + submesh.verticesStart;
  105234. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  105235. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  105236. vertex.originalOffsets.push(offset);
  105237. if (vertex.id === _this.vertices.length) {
  105238. _this.vertices.push(vertex);
  105239. }
  105240. vertexReferences.push(vertex.id);
  105241. };
  105242. //var totalVertices = mesh.getTotalVertices();
  105243. var totalVertices = submesh.verticesCount;
  105244. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  105245. var indicesInit = function (i) {
  105246. if (!indices) {
  105247. return;
  105248. }
  105249. var offset = (submesh.indexStart / 3) + i;
  105250. var pos = (offset * 3);
  105251. var i0 = indices[pos + 0];
  105252. var i1 = indices[pos + 1];
  105253. var i2 = indices[pos + 2];
  105254. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  105255. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  105256. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  105257. var triangle = new DecimationTriangle([v0, v1, v2]);
  105258. triangle.originalOffset = pos;
  105259. _this.triangles.push(triangle);
  105260. };
  105261. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  105262. _this.init(callback);
  105263. });
  105264. });
  105265. };
  105266. QuadraticErrorSimplification.prototype.init = function (callback) {
  105267. var _this = this;
  105268. var triangleInit1 = function (i) {
  105269. var t = _this.triangles[i];
  105270. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  105271. for (var j = 0; j < 3; j++) {
  105272. 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))));
  105273. }
  105274. };
  105275. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  105276. var triangleInit2 = function (i) {
  105277. var t = _this.triangles[i];
  105278. for (var j = 0; j < 3; ++j) {
  105279. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  105280. }
  105281. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  105282. };
  105283. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  105284. callback();
  105285. });
  105286. });
  105287. };
  105288. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  105289. var newTriangles = [];
  105290. var i;
  105291. for (i = 0; i < this.vertices.length; ++i) {
  105292. this.vertices[i].triangleCount = 0;
  105293. }
  105294. var t;
  105295. var j;
  105296. for (i = 0; i < this.triangles.length; ++i) {
  105297. if (!this.triangles[i].deleted) {
  105298. t = this.triangles[i];
  105299. for (j = 0; j < 3; ++j) {
  105300. t.vertices[j].triangleCount = 1;
  105301. }
  105302. newTriangles.push(t);
  105303. }
  105304. }
  105305. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  105306. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  105307. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  105308. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  105309. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  105310. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  105311. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  105312. var vertexCount = 0;
  105313. for (i = 0; i < this.vertices.length; ++i) {
  105314. var vertex = this.vertices[i];
  105315. vertex.id = vertexCount;
  105316. if (vertex.triangleCount) {
  105317. vertex.originalOffsets.forEach(function (originalOffset) {
  105318. if (!normalData) {
  105319. return;
  105320. }
  105321. newPositionData.push(vertex.position.x);
  105322. newPositionData.push(vertex.position.y);
  105323. newPositionData.push(vertex.position.z);
  105324. newNormalData.push(normalData[originalOffset * 3]);
  105325. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  105326. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  105327. if (uvs && uvs.length) {
  105328. newUVsData.push(uvs[(originalOffset * 2)]);
  105329. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  105330. }
  105331. else if (colorsData && colorsData.length) {
  105332. newColorsData.push(colorsData[(originalOffset * 4)]);
  105333. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  105334. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  105335. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  105336. }
  105337. ++vertexCount;
  105338. });
  105339. }
  105340. }
  105341. var startingIndex = this._reconstructedMesh.getTotalIndices();
  105342. var startingVertex = this._reconstructedMesh.getTotalVertices();
  105343. var submeshesArray = this._reconstructedMesh.subMeshes;
  105344. this._reconstructedMesh.subMeshes = [];
  105345. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  105346. var originalIndices = this._mesh.getIndices();
  105347. for (i = 0; i < newTriangles.length; ++i) {
  105348. t = newTriangles[i]; //now get the new referencing point for each vertex
  105349. [0, 1, 2].forEach(function (idx) {
  105350. var id = originalIndices[t.originalOffset + idx];
  105351. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  105352. if (offset < 0)
  105353. offset = 0;
  105354. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  105355. });
  105356. }
  105357. //overwriting the old vertex buffers and indices.
  105358. this._reconstructedMesh.setIndices(newIndicesArray);
  105359. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  105360. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  105361. if (newUVsData.length > 0)
  105362. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  105363. if (newColorsData.length > 0)
  105364. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  105365. //create submesh
  105366. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  105367. if (submeshIndex > 0) {
  105368. this._reconstructedMesh.subMeshes = [];
  105369. submeshesArray.forEach(function (submesh) {
  105370. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  105371. });
  105372. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  105373. }
  105374. };
  105375. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  105376. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  105377. this._reconstructedMesh.material = this._mesh.material;
  105378. this._reconstructedMesh.parent = this._mesh.parent;
  105379. this._reconstructedMesh.isVisible = false;
  105380. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  105381. };
  105382. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  105383. for (var i = 0; i < vertex1.triangleCount; ++i) {
  105384. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  105385. if (t.deleted)
  105386. continue;
  105387. var s = this.references[vertex1.triangleStart + i].vertexId;
  105388. var v1 = t.vertices[(s + 1) % 3];
  105389. var v2 = t.vertices[(s + 2) % 3];
  105390. if ((v1 === vertex2 || v2 === vertex2)) {
  105391. deletedArray[i] = true;
  105392. delTr.push(t);
  105393. continue;
  105394. }
  105395. var d1 = v1.position.subtract(point);
  105396. d1 = d1.normalize();
  105397. var d2 = v2.position.subtract(point);
  105398. d2 = d2.normalize();
  105399. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  105400. return true;
  105401. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  105402. deletedArray[i] = false;
  105403. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  105404. return true;
  105405. }
  105406. return false;
  105407. };
  105408. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  105409. var newDeleted = deletedTriangles;
  105410. for (var i = 0; i < vertex.triangleCount; ++i) {
  105411. var ref = this.references[vertex.triangleStart + i];
  105412. var t = this.triangles[ref.triangleId];
  105413. if (t.deleted)
  105414. continue;
  105415. if (deletedArray[i] && t.deletePending) {
  105416. t.deleted = true;
  105417. newDeleted++;
  105418. continue;
  105419. }
  105420. t.vertices[ref.vertexId] = origVertex;
  105421. t.isDirty = true;
  105422. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  105423. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  105424. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  105425. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  105426. this.references.push(ref);
  105427. }
  105428. return newDeleted;
  105429. };
  105430. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  105431. for (var i = 0; i < this.vertices.length; ++i) {
  105432. var vCount = [];
  105433. var vId = [];
  105434. var v = this.vertices[i];
  105435. var j;
  105436. for (j = 0; j < v.triangleCount; ++j) {
  105437. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  105438. for (var ii = 0; ii < 3; ii++) {
  105439. var ofs = 0;
  105440. var vv = triangle.vertices[ii];
  105441. while (ofs < vCount.length) {
  105442. if (vId[ofs] === vv.id)
  105443. break;
  105444. ++ofs;
  105445. }
  105446. if (ofs === vCount.length) {
  105447. vCount.push(1);
  105448. vId.push(vv.id);
  105449. }
  105450. else {
  105451. vCount[ofs]++;
  105452. }
  105453. }
  105454. }
  105455. for (j = 0; j < vCount.length; ++j) {
  105456. if (vCount[j] === 1) {
  105457. this.vertices[vId[j]].isBorder = true;
  105458. }
  105459. else {
  105460. this.vertices[vId[j]].isBorder = false;
  105461. }
  105462. }
  105463. }
  105464. };
  105465. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  105466. if (identifyBorders === void 0) { identifyBorders = false; }
  105467. var i;
  105468. if (!identifyBorders) {
  105469. var newTrianglesVector = [];
  105470. for (i = 0; i < this.triangles.length; ++i) {
  105471. if (!this.triangles[i].deleted) {
  105472. newTrianglesVector.push(this.triangles[i]);
  105473. }
  105474. }
  105475. this.triangles = newTrianglesVector;
  105476. }
  105477. for (i = 0; i < this.vertices.length; ++i) {
  105478. this.vertices[i].triangleCount = 0;
  105479. this.vertices[i].triangleStart = 0;
  105480. }
  105481. var t;
  105482. var j;
  105483. var v;
  105484. for (i = 0; i < this.triangles.length; ++i) {
  105485. t = this.triangles[i];
  105486. for (j = 0; j < 3; ++j) {
  105487. v = t.vertices[j];
  105488. v.triangleCount++;
  105489. }
  105490. }
  105491. var tStart = 0;
  105492. for (i = 0; i < this.vertices.length; ++i) {
  105493. this.vertices[i].triangleStart = tStart;
  105494. tStart += this.vertices[i].triangleCount;
  105495. this.vertices[i].triangleCount = 0;
  105496. }
  105497. var newReferences = new Array(this.triangles.length * 3);
  105498. for (i = 0; i < this.triangles.length; ++i) {
  105499. t = this.triangles[i];
  105500. for (j = 0; j < 3; ++j) {
  105501. v = t.vertices[j];
  105502. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  105503. v.triangleCount++;
  105504. }
  105505. }
  105506. this.references = newReferences;
  105507. if (identifyBorders) {
  105508. this.identifyBorder();
  105509. }
  105510. };
  105511. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  105512. var x = point.x;
  105513. var y = point.y;
  105514. var z = point.z;
  105515. 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
  105516. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  105517. };
  105518. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  105519. var q = vertex1.q.add(vertex2.q);
  105520. var border = vertex1.isBorder && vertex2.isBorder;
  105521. var error = 0;
  105522. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  105523. if (qDet !== 0 && !border) {
  105524. if (!pointResult) {
  105525. pointResult = BABYLON.Vector3.Zero();
  105526. }
  105527. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  105528. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  105529. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  105530. error = this.vertexError(q, pointResult);
  105531. }
  105532. else {
  105533. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  105534. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  105535. var error1 = this.vertexError(q, vertex1.position);
  105536. var error2 = this.vertexError(q, vertex2.position);
  105537. var error3 = this.vertexError(q, p3);
  105538. error = Math.min(error1, error2, error3);
  105539. if (error === error1) {
  105540. if (pointResult) {
  105541. pointResult.copyFrom(vertex1.position);
  105542. }
  105543. }
  105544. else if (error === error2) {
  105545. if (pointResult) {
  105546. pointResult.copyFrom(vertex2.position);
  105547. }
  105548. }
  105549. else {
  105550. if (pointResult) {
  105551. pointResult.copyFrom(p3);
  105552. }
  105553. }
  105554. }
  105555. return error;
  105556. };
  105557. return QuadraticErrorSimplification;
  105558. }());
  105559. })(BABYLON || (BABYLON = {}));
  105560. //# sourceMappingURL=babylon.meshSimplification.js.map
  105561. var BABYLON;
  105562. (function (BABYLON) {
  105563. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  105564. get: function () {
  105565. if (!this._simplificationQueue) {
  105566. this._simplificationQueue = new BABYLON.SimplificationQueue();
  105567. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  105568. if (!component) {
  105569. component = new SimplicationQueueSceneComponent(this);
  105570. this._addComponent(component);
  105571. }
  105572. }
  105573. return this._simplificationQueue;
  105574. },
  105575. set: function (value) {
  105576. this._simplificationQueue = value;
  105577. },
  105578. enumerable: true,
  105579. configurable: true
  105580. });
  105581. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  105582. if (parallelProcessing === void 0) { parallelProcessing = true; }
  105583. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  105584. this.getScene().simplificationQueue.addTask({
  105585. settings: settings,
  105586. parallelProcessing: parallelProcessing,
  105587. mesh: this,
  105588. simplificationType: simplificationType,
  105589. successCallback: successCallback
  105590. });
  105591. return this;
  105592. };
  105593. /**
  105594. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  105595. * created in a scene
  105596. */
  105597. var SimplicationQueueSceneComponent = /** @class */ (function () {
  105598. /**
  105599. * Creates a new instance of the component for the given scene
  105600. * @param scene Defines the scene to register the component in
  105601. */
  105602. function SimplicationQueueSceneComponent(scene) {
  105603. /**
  105604. * The component name helpfull to identify the component in the list of scene components.
  105605. */
  105606. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  105607. this.scene = scene;
  105608. }
  105609. /**
  105610. * Registers the component in a given scene
  105611. */
  105612. SimplicationQueueSceneComponent.prototype.register = function () {
  105613. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  105614. };
  105615. /**
  105616. * Rebuilds the elements related to this component in case of
  105617. * context lost for instance.
  105618. */
  105619. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  105620. // Nothing to do for this component
  105621. };
  105622. /**
  105623. * Disposes the component and the associated ressources
  105624. */
  105625. SimplicationQueueSceneComponent.prototype.dispose = function () {
  105626. // Nothing to do for this component
  105627. };
  105628. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  105629. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  105630. this.scene._simplificationQueue.executeNext();
  105631. }
  105632. };
  105633. return SimplicationQueueSceneComponent;
  105634. }());
  105635. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  105636. })(BABYLON || (BABYLON = {}));
  105637. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  105638. var BABYLON;
  105639. (function (BABYLON) {
  105640. /**
  105641. * Class used to represent a specific level of detail of a mesh
  105642. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  105643. */
  105644. var MeshLODLevel = /** @class */ (function () {
  105645. /**
  105646. * Creates a new LOD level
  105647. * @param distance defines the distance where this level should star being displayed
  105648. * @param mesh defines the mesh to use to render this level
  105649. */
  105650. function MeshLODLevel(
  105651. /** Defines the distance where this level should star being displayed */
  105652. distance,
  105653. /** Defines the mesh to use to render this level */
  105654. mesh) {
  105655. this.distance = distance;
  105656. this.mesh = mesh;
  105657. }
  105658. return MeshLODLevel;
  105659. }());
  105660. BABYLON.MeshLODLevel = MeshLODLevel;
  105661. })(BABYLON || (BABYLON = {}));
  105662. //# sourceMappingURL=babylon.meshLODLevel.js.map
  105663. var BABYLON;
  105664. (function (BABYLON) {
  105665. /**
  105666. * Defines the root class used to create scene optimization to use with SceneOptimizer
  105667. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105668. */
  105669. var SceneOptimization = /** @class */ (function () {
  105670. /**
  105671. * Creates the SceneOptimization object
  105672. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  105673. * @param desc defines the description associated with the optimization
  105674. */
  105675. function SceneOptimization(
  105676. /**
  105677. * Defines the priority of this optimization (0 by default which means first in the list)
  105678. */
  105679. priority) {
  105680. if (priority === void 0) { priority = 0; }
  105681. this.priority = priority;
  105682. }
  105683. /**
  105684. * Gets a string describing the action executed by the current optimization
  105685. * @returns description string
  105686. */
  105687. SceneOptimization.prototype.getDescription = function () {
  105688. return "";
  105689. };
  105690. /**
  105691. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105692. * @param scene defines the current scene where to apply this optimization
  105693. * @param optimizer defines the current optimizer
  105694. * @returns true if everything that can be done was applied
  105695. */
  105696. SceneOptimization.prototype.apply = function (scene, optimizer) {
  105697. return true;
  105698. };
  105699. ;
  105700. return SceneOptimization;
  105701. }());
  105702. BABYLON.SceneOptimization = SceneOptimization;
  105703. /**
  105704. * Defines an optimization used to reduce the size of render target textures
  105705. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105706. */
  105707. var TextureOptimization = /** @class */ (function (_super) {
  105708. __extends(TextureOptimization, _super);
  105709. /**
  105710. * Creates the TextureOptimization object
  105711. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  105712. * @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
  105713. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  105714. */
  105715. function TextureOptimization(
  105716. /**
  105717. * Defines the priority of this optimization (0 by default which means first in the list)
  105718. */
  105719. priority,
  105720. /**
  105721. * 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
  105722. */
  105723. maximumSize,
  105724. /**
  105725. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  105726. */
  105727. step) {
  105728. if (priority === void 0) { priority = 0; }
  105729. if (maximumSize === void 0) { maximumSize = 1024; }
  105730. if (step === void 0) { step = 0.5; }
  105731. var _this = _super.call(this, priority) || this;
  105732. _this.priority = priority;
  105733. _this.maximumSize = maximumSize;
  105734. _this.step = step;
  105735. return _this;
  105736. }
  105737. /**
  105738. * Gets a string describing the action executed by the current optimization
  105739. * @returns description string
  105740. */
  105741. TextureOptimization.prototype.getDescription = function () {
  105742. return "Reducing render target texture size to " + this.maximumSize;
  105743. };
  105744. /**
  105745. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105746. * @param scene defines the current scene where to apply this optimization
  105747. * @param optimizer defines the current optimizer
  105748. * @returns true if everything that can be done was applied
  105749. */
  105750. TextureOptimization.prototype.apply = function (scene, optimizer) {
  105751. var allDone = true;
  105752. for (var index = 0; index < scene.textures.length; index++) {
  105753. var texture = scene.textures[index];
  105754. if (!texture.canRescale || texture.getContext) {
  105755. continue;
  105756. }
  105757. var currentSize = texture.getSize();
  105758. var maxDimension = Math.max(currentSize.width, currentSize.height);
  105759. if (maxDimension > this.maximumSize) {
  105760. texture.scale(this.step);
  105761. allDone = false;
  105762. }
  105763. }
  105764. return allDone;
  105765. };
  105766. return TextureOptimization;
  105767. }(SceneOptimization));
  105768. BABYLON.TextureOptimization = TextureOptimization;
  105769. /**
  105770. * Defines an optimization used to increase or decrease the rendering resolution
  105771. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105772. */
  105773. var HardwareScalingOptimization = /** @class */ (function (_super) {
  105774. __extends(HardwareScalingOptimization, _super);
  105775. /**
  105776. * Creates the HardwareScalingOptimization object
  105777. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  105778. * @param maximumScale defines the maximum scale to use (2 by default)
  105779. * @param step defines the step to use between two passes (0.5 by default)
  105780. */
  105781. function HardwareScalingOptimization(
  105782. /**
  105783. * Defines the priority of this optimization (0 by default which means first in the list)
  105784. */
  105785. priority,
  105786. /**
  105787. * Defines the maximum scale to use (2 by default)
  105788. */
  105789. maximumScale,
  105790. /**
  105791. * Defines the step to use between two passes (0.5 by default)
  105792. */
  105793. step) {
  105794. if (priority === void 0) { priority = 0; }
  105795. if (maximumScale === void 0) { maximumScale = 2; }
  105796. if (step === void 0) { step = 0.25; }
  105797. var _this = _super.call(this, priority) || this;
  105798. _this.priority = priority;
  105799. _this.maximumScale = maximumScale;
  105800. _this.step = step;
  105801. _this._currentScale = -1;
  105802. _this._directionOffset = 1;
  105803. return _this;
  105804. }
  105805. /**
  105806. * Gets a string describing the action executed by the current optimization
  105807. * @return description string
  105808. */
  105809. HardwareScalingOptimization.prototype.getDescription = function () {
  105810. return "Setting hardware scaling level to " + this._currentScale;
  105811. };
  105812. /**
  105813. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105814. * @param scene defines the current scene where to apply this optimization
  105815. * @param optimizer defines the current optimizer
  105816. * @returns true if everything that can be done was applied
  105817. */
  105818. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  105819. if (this._currentScale === -1) {
  105820. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  105821. if (this._currentScale > this.maximumScale) {
  105822. this._directionOffset = -1;
  105823. }
  105824. }
  105825. this._currentScale += this._directionOffset * this.step;
  105826. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  105827. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  105828. };
  105829. ;
  105830. return HardwareScalingOptimization;
  105831. }(SceneOptimization));
  105832. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  105833. /**
  105834. * Defines an optimization used to remove shadows
  105835. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105836. */
  105837. var ShadowsOptimization = /** @class */ (function (_super) {
  105838. __extends(ShadowsOptimization, _super);
  105839. function ShadowsOptimization() {
  105840. return _super !== null && _super.apply(this, arguments) || this;
  105841. }
  105842. /**
  105843. * Gets a string describing the action executed by the current optimization
  105844. * @return description string
  105845. */
  105846. ShadowsOptimization.prototype.getDescription = function () {
  105847. return "Turning shadows on/off";
  105848. };
  105849. /**
  105850. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105851. * @param scene defines the current scene where to apply this optimization
  105852. * @param optimizer defines the current optimizer
  105853. * @returns true if everything that can be done was applied
  105854. */
  105855. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  105856. scene.shadowsEnabled = optimizer.isInImprovementMode;
  105857. return true;
  105858. };
  105859. ;
  105860. return ShadowsOptimization;
  105861. }(SceneOptimization));
  105862. BABYLON.ShadowsOptimization = ShadowsOptimization;
  105863. /**
  105864. * Defines an optimization used to turn post-processes off
  105865. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105866. */
  105867. var PostProcessesOptimization = /** @class */ (function (_super) {
  105868. __extends(PostProcessesOptimization, _super);
  105869. function PostProcessesOptimization() {
  105870. return _super !== null && _super.apply(this, arguments) || this;
  105871. }
  105872. /**
  105873. * Gets a string describing the action executed by the current optimization
  105874. * @return description string
  105875. */
  105876. PostProcessesOptimization.prototype.getDescription = function () {
  105877. return "Turning post-processes on/off";
  105878. };
  105879. /**
  105880. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105881. * @param scene defines the current scene where to apply this optimization
  105882. * @param optimizer defines the current optimizer
  105883. * @returns true if everything that can be done was applied
  105884. */
  105885. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  105886. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  105887. return true;
  105888. };
  105889. ;
  105890. return PostProcessesOptimization;
  105891. }(SceneOptimization));
  105892. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  105893. /**
  105894. * Defines an optimization used to turn lens flares off
  105895. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105896. */
  105897. var LensFlaresOptimization = /** @class */ (function (_super) {
  105898. __extends(LensFlaresOptimization, _super);
  105899. function LensFlaresOptimization() {
  105900. return _super !== null && _super.apply(this, arguments) || this;
  105901. }
  105902. /**
  105903. * Gets a string describing the action executed by the current optimization
  105904. * @return description string
  105905. */
  105906. LensFlaresOptimization.prototype.getDescription = function () {
  105907. return "Turning lens flares on/off";
  105908. };
  105909. /**
  105910. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105911. * @param scene defines the current scene where to apply this optimization
  105912. * @param optimizer defines the current optimizer
  105913. * @returns true if everything that can be done was applied
  105914. */
  105915. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  105916. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  105917. return true;
  105918. };
  105919. ;
  105920. return LensFlaresOptimization;
  105921. }(SceneOptimization));
  105922. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  105923. /**
  105924. * Defines an optimization based on user defined callback.
  105925. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105926. */
  105927. var CustomOptimization = /** @class */ (function (_super) {
  105928. __extends(CustomOptimization, _super);
  105929. function CustomOptimization() {
  105930. return _super !== null && _super.apply(this, arguments) || this;
  105931. }
  105932. /**
  105933. * Gets a string describing the action executed by the current optimization
  105934. * @returns description string
  105935. */
  105936. CustomOptimization.prototype.getDescription = function () {
  105937. if (this.onGetDescription) {
  105938. return this.onGetDescription();
  105939. }
  105940. return "Running user defined callback";
  105941. };
  105942. /**
  105943. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105944. * @param scene defines the current scene where to apply this optimization
  105945. * @param optimizer defines the current optimizer
  105946. * @returns true if everything that can be done was applied
  105947. */
  105948. CustomOptimization.prototype.apply = function (scene, optimizer) {
  105949. if (this.onApply) {
  105950. return this.onApply(scene, optimizer);
  105951. }
  105952. return true;
  105953. };
  105954. ;
  105955. return CustomOptimization;
  105956. }(SceneOptimization));
  105957. BABYLON.CustomOptimization = CustomOptimization;
  105958. /**
  105959. * Defines an optimization used to turn particles off
  105960. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105961. */
  105962. var ParticlesOptimization = /** @class */ (function (_super) {
  105963. __extends(ParticlesOptimization, _super);
  105964. function ParticlesOptimization() {
  105965. return _super !== null && _super.apply(this, arguments) || this;
  105966. }
  105967. /**
  105968. * Gets a string describing the action executed by the current optimization
  105969. * @return description string
  105970. */
  105971. ParticlesOptimization.prototype.getDescription = function () {
  105972. return "Turning particles on/off";
  105973. };
  105974. /**
  105975. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  105976. * @param scene defines the current scene where to apply this optimization
  105977. * @param optimizer defines the current optimizer
  105978. * @returns true if everything that can be done was applied
  105979. */
  105980. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  105981. scene.particlesEnabled = optimizer.isInImprovementMode;
  105982. return true;
  105983. };
  105984. ;
  105985. return ParticlesOptimization;
  105986. }(SceneOptimization));
  105987. BABYLON.ParticlesOptimization = ParticlesOptimization;
  105988. /**
  105989. * Defines an optimization used to turn render targets off
  105990. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  105991. */
  105992. var RenderTargetsOptimization = /** @class */ (function (_super) {
  105993. __extends(RenderTargetsOptimization, _super);
  105994. function RenderTargetsOptimization() {
  105995. return _super !== null && _super.apply(this, arguments) || this;
  105996. }
  105997. /**
  105998. * Gets a string describing the action executed by the current optimization
  105999. * @return description string
  106000. */
  106001. RenderTargetsOptimization.prototype.getDescription = function () {
  106002. return "Turning render targets off";
  106003. };
  106004. /**
  106005. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  106006. * @param scene defines the current scene where to apply this optimization
  106007. * @param optimizer defines the current optimizer
  106008. * @returns true if everything that can be done was applied
  106009. */
  106010. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  106011. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  106012. return true;
  106013. };
  106014. ;
  106015. return RenderTargetsOptimization;
  106016. }(SceneOptimization));
  106017. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  106018. /**
  106019. * Defines an optimization used to merge meshes with compatible materials
  106020. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  106021. */
  106022. var MergeMeshesOptimization = /** @class */ (function (_super) {
  106023. __extends(MergeMeshesOptimization, _super);
  106024. function MergeMeshesOptimization() {
  106025. var _this = _super !== null && _super.apply(this, arguments) || this;
  106026. _this._canBeMerged = function (abstractMesh) {
  106027. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  106028. return false;
  106029. }
  106030. var mesh = abstractMesh;
  106031. if (mesh.isDisposed()) {
  106032. return false;
  106033. }
  106034. if (!mesh.isVisible || !mesh.isEnabled()) {
  106035. return false;
  106036. }
  106037. if (mesh.instances.length > 0) {
  106038. return false;
  106039. }
  106040. if (mesh.skeleton || mesh.hasLODLevels) {
  106041. return false;
  106042. }
  106043. return true;
  106044. };
  106045. return _this;
  106046. }
  106047. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  106048. /**
  106049. * Gets or sets a boolean which defines if optimization octree has to be updated
  106050. */
  106051. get: function () {
  106052. return MergeMeshesOptimization._UpdateSelectionTree;
  106053. },
  106054. /**
  106055. * Gets or sets a boolean which defines if optimization octree has to be updated
  106056. */
  106057. set: function (value) {
  106058. MergeMeshesOptimization._UpdateSelectionTree = value;
  106059. },
  106060. enumerable: true,
  106061. configurable: true
  106062. });
  106063. /**
  106064. * Gets a string describing the action executed by the current optimization
  106065. * @return description string
  106066. */
  106067. MergeMeshesOptimization.prototype.getDescription = function () {
  106068. return "Merging similar meshes together";
  106069. };
  106070. /**
  106071. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  106072. * @param scene defines the current scene where to apply this optimization
  106073. * @param optimizer defines the current optimizer
  106074. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  106075. * @returns true if everything that can be done was applied
  106076. */
  106077. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  106078. var globalPool = scene.meshes.slice(0);
  106079. var globalLength = globalPool.length;
  106080. for (var index = 0; index < globalLength; index++) {
  106081. var currentPool = new Array();
  106082. var current = globalPool[index];
  106083. // Checks
  106084. if (!this._canBeMerged(current)) {
  106085. continue;
  106086. }
  106087. currentPool.push(current);
  106088. // Find compatible meshes
  106089. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  106090. var otherMesh = globalPool[subIndex];
  106091. if (!this._canBeMerged(otherMesh)) {
  106092. continue;
  106093. }
  106094. if (otherMesh.material !== current.material) {
  106095. continue;
  106096. }
  106097. if (otherMesh.checkCollisions !== current.checkCollisions) {
  106098. continue;
  106099. }
  106100. currentPool.push(otherMesh);
  106101. globalLength--;
  106102. globalPool.splice(subIndex, 1);
  106103. subIndex--;
  106104. }
  106105. if (currentPool.length < 2) {
  106106. continue;
  106107. }
  106108. // Merge meshes
  106109. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  106110. }
  106111. // Call the octree system optimization if it is defined.
  106112. var sceneAsAny = scene;
  106113. if (sceneAsAny.createOrUpdateSelectionOctree) {
  106114. if (updateSelectionTree != undefined) {
  106115. if (updateSelectionTree) {
  106116. sceneAsAny.createOrUpdateSelectionOctree();
  106117. }
  106118. }
  106119. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  106120. sceneAsAny.createOrUpdateSelectionOctree();
  106121. }
  106122. }
  106123. return true;
  106124. };
  106125. ;
  106126. MergeMeshesOptimization._UpdateSelectionTree = false;
  106127. return MergeMeshesOptimization;
  106128. }(SceneOptimization));
  106129. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  106130. /**
  106131. * Defines a list of options used by SceneOptimizer
  106132. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  106133. */
  106134. var SceneOptimizerOptions = /** @class */ (function () {
  106135. /**
  106136. * Creates a new list of options used by SceneOptimizer
  106137. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  106138. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  106139. */
  106140. function SceneOptimizerOptions(
  106141. /**
  106142. * Defines the target frame rate to reach (60 by default)
  106143. */
  106144. targetFrameRate,
  106145. /**
  106146. * Defines the interval between two checkes (2000ms by default)
  106147. */
  106148. trackerDuration) {
  106149. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  106150. if (trackerDuration === void 0) { trackerDuration = 2000; }
  106151. this.targetFrameRate = targetFrameRate;
  106152. this.trackerDuration = trackerDuration;
  106153. /**
  106154. * Gets the list of optimizations to apply
  106155. */
  106156. this.optimizations = new Array();
  106157. }
  106158. /**
  106159. * Add a new optimization
  106160. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  106161. * @returns the current SceneOptimizerOptions
  106162. */
  106163. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  106164. this.optimizations.push(optimization);
  106165. return this;
  106166. };
  106167. /**
  106168. * Add a new custom optimization
  106169. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  106170. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  106171. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  106172. * @returns the current SceneOptimizerOptions
  106173. */
  106174. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  106175. if (priority === void 0) { priority = 0; }
  106176. var optimization = new CustomOptimization(priority);
  106177. optimization.onApply = onApply;
  106178. optimization.onGetDescription = onGetDescription;
  106179. this.optimizations.push(optimization);
  106180. return this;
  106181. };
  106182. /**
  106183. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  106184. * @param targetFrameRate defines the target frame rate (60 by default)
  106185. * @returns a SceneOptimizerOptions object
  106186. */
  106187. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  106188. var result = new SceneOptimizerOptions(targetFrameRate);
  106189. var priority = 0;
  106190. result.addOptimization(new MergeMeshesOptimization(priority));
  106191. result.addOptimization(new ShadowsOptimization(priority));
  106192. result.addOptimization(new LensFlaresOptimization(priority));
  106193. // Next priority
  106194. priority++;
  106195. result.addOptimization(new PostProcessesOptimization(priority));
  106196. result.addOptimization(new ParticlesOptimization(priority));
  106197. // Next priority
  106198. priority++;
  106199. result.addOptimization(new TextureOptimization(priority, 1024));
  106200. return result;
  106201. };
  106202. /**
  106203. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  106204. * @param targetFrameRate defines the target frame rate (60 by default)
  106205. * @returns a SceneOptimizerOptions object
  106206. */
  106207. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  106208. var result = new SceneOptimizerOptions(targetFrameRate);
  106209. var priority = 0;
  106210. result.addOptimization(new MergeMeshesOptimization(priority));
  106211. result.addOptimization(new ShadowsOptimization(priority));
  106212. result.addOptimization(new LensFlaresOptimization(priority));
  106213. // Next priority
  106214. priority++;
  106215. result.addOptimization(new PostProcessesOptimization(priority));
  106216. result.addOptimization(new ParticlesOptimization(priority));
  106217. // Next priority
  106218. priority++;
  106219. result.addOptimization(new TextureOptimization(priority, 512));
  106220. // Next priority
  106221. priority++;
  106222. result.addOptimization(new RenderTargetsOptimization(priority));
  106223. // Next priority
  106224. priority++;
  106225. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  106226. return result;
  106227. };
  106228. /**
  106229. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  106230. * @param targetFrameRate defines the target frame rate (60 by default)
  106231. * @returns a SceneOptimizerOptions object
  106232. */
  106233. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  106234. var result = new SceneOptimizerOptions(targetFrameRate);
  106235. var priority = 0;
  106236. result.addOptimization(new MergeMeshesOptimization(priority));
  106237. result.addOptimization(new ShadowsOptimization(priority));
  106238. result.addOptimization(new LensFlaresOptimization(priority));
  106239. // Next priority
  106240. priority++;
  106241. result.addOptimization(new PostProcessesOptimization(priority));
  106242. result.addOptimization(new ParticlesOptimization(priority));
  106243. // Next priority
  106244. priority++;
  106245. result.addOptimization(new TextureOptimization(priority, 256));
  106246. // Next priority
  106247. priority++;
  106248. result.addOptimization(new RenderTargetsOptimization(priority));
  106249. // Next priority
  106250. priority++;
  106251. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  106252. return result;
  106253. };
  106254. return SceneOptimizerOptions;
  106255. }());
  106256. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  106257. /**
  106258. * Class used to run optimizations in order to reach a target frame rate
  106259. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  106260. */
  106261. var SceneOptimizer = /** @class */ (function () {
  106262. /**
  106263. * Creates a new SceneOptimizer
  106264. * @param scene defines the scene to work on
  106265. * @param options defines the options to use with the SceneOptimizer
  106266. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  106267. * @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)
  106268. */
  106269. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  106270. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  106271. if (improvementMode === void 0) { improvementMode = false; }
  106272. var _this = this;
  106273. this._isRunning = false;
  106274. this._currentPriorityLevel = 0;
  106275. this._targetFrameRate = 60;
  106276. this._trackerDuration = 2000;
  106277. this._currentFrameRate = 0;
  106278. this._improvementMode = false;
  106279. /**
  106280. * Defines an observable called when the optimizer reaches the target frame rate
  106281. */
  106282. this.onSuccessObservable = new BABYLON.Observable();
  106283. /**
  106284. * Defines an observable called when the optimizer enables an optimization
  106285. */
  106286. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  106287. /**
  106288. * Defines an observable called when the optimizer is not able to reach the target frame rate
  106289. */
  106290. this.onFailureObservable = new BABYLON.Observable();
  106291. if (!options) {
  106292. this._options = new SceneOptimizerOptions();
  106293. }
  106294. else {
  106295. this._options = options;
  106296. }
  106297. if (this._options.targetFrameRate) {
  106298. this._targetFrameRate = this._options.targetFrameRate;
  106299. }
  106300. if (this._options.trackerDuration) {
  106301. this._trackerDuration = this._options.trackerDuration;
  106302. }
  106303. if (autoGeneratePriorities) {
  106304. var priority = 0;
  106305. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  106306. var optim = _a[_i];
  106307. optim.priority = priority++;
  106308. }
  106309. }
  106310. this._improvementMode = improvementMode;
  106311. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  106312. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  106313. _this._sceneDisposeObserver = null;
  106314. _this.dispose();
  106315. });
  106316. }
  106317. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  106318. /**
  106319. * Gets a boolean indicating if the optimizer is in improvement mode
  106320. */
  106321. get: function () {
  106322. return this._improvementMode;
  106323. },
  106324. enumerable: true,
  106325. configurable: true
  106326. });
  106327. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  106328. /**
  106329. * Gets the current priority level (0 at start)
  106330. */
  106331. get: function () {
  106332. return this._currentPriorityLevel;
  106333. },
  106334. enumerable: true,
  106335. configurable: true
  106336. });
  106337. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  106338. /**
  106339. * Gets the current frame rate checked by the SceneOptimizer
  106340. */
  106341. get: function () {
  106342. return this._currentFrameRate;
  106343. },
  106344. enumerable: true,
  106345. configurable: true
  106346. });
  106347. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  106348. /**
  106349. * Gets or sets the current target frame rate (60 by default)
  106350. */
  106351. get: function () {
  106352. return this._targetFrameRate;
  106353. },
  106354. /**
  106355. * Gets or sets the current target frame rate (60 by default)
  106356. */
  106357. set: function (value) {
  106358. this._targetFrameRate = value;
  106359. },
  106360. enumerable: true,
  106361. configurable: true
  106362. });
  106363. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  106364. /**
  106365. * Gets or sets the current interval between two checks (every 2000ms by default)
  106366. */
  106367. get: function () {
  106368. return this._trackerDuration;
  106369. },
  106370. /**
  106371. * Gets or sets the current interval between two checks (every 2000ms by default)
  106372. */
  106373. set: function (value) {
  106374. this._trackerDuration = value;
  106375. },
  106376. enumerable: true,
  106377. configurable: true
  106378. });
  106379. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  106380. /**
  106381. * Gets the list of active optimizations
  106382. */
  106383. get: function () {
  106384. return this._options.optimizations;
  106385. },
  106386. enumerable: true,
  106387. configurable: true
  106388. });
  106389. /**
  106390. * Stops the current optimizer
  106391. */
  106392. SceneOptimizer.prototype.stop = function () {
  106393. this._isRunning = false;
  106394. };
  106395. /**
  106396. * Reset the optimizer to initial step (current priority level = 0)
  106397. */
  106398. SceneOptimizer.prototype.reset = function () {
  106399. this._currentPriorityLevel = 0;
  106400. };
  106401. /**
  106402. * Start the optimizer. By default it will try to reach a specific framerate
  106403. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  106404. */
  106405. SceneOptimizer.prototype.start = function () {
  106406. var _this = this;
  106407. if (this._isRunning) {
  106408. return;
  106409. }
  106410. this._isRunning = true;
  106411. // Let's wait for the scene to be ready before running our check
  106412. this._scene.executeWhenReady(function () {
  106413. setTimeout(function () {
  106414. _this._checkCurrentState();
  106415. }, _this._trackerDuration);
  106416. });
  106417. };
  106418. SceneOptimizer.prototype._checkCurrentState = function () {
  106419. var _this = this;
  106420. if (!this._isRunning) {
  106421. return;
  106422. }
  106423. var scene = this._scene;
  106424. var options = this._options;
  106425. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  106426. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  106427. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  106428. this._isRunning = false;
  106429. this.onSuccessObservable.notifyObservers(this);
  106430. return;
  106431. }
  106432. // Apply current level of optimizations
  106433. var allDone = true;
  106434. var noOptimizationApplied = true;
  106435. for (var index = 0; index < options.optimizations.length; index++) {
  106436. var optimization = options.optimizations[index];
  106437. if (optimization.priority === this._currentPriorityLevel) {
  106438. noOptimizationApplied = false;
  106439. allDone = allDone && optimization.apply(scene, this);
  106440. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  106441. }
  106442. }
  106443. // If no optimization was applied, this is a failure :(
  106444. if (noOptimizationApplied) {
  106445. this._isRunning = false;
  106446. this.onFailureObservable.notifyObservers(this);
  106447. return;
  106448. }
  106449. // If all optimizations were done, move to next level
  106450. if (allDone) {
  106451. this._currentPriorityLevel++;
  106452. }
  106453. // Let's the system running for a specific amount of time before checking FPS
  106454. scene.executeWhenReady(function () {
  106455. setTimeout(function () {
  106456. _this._checkCurrentState();
  106457. }, _this._trackerDuration);
  106458. });
  106459. };
  106460. /**
  106461. * Release all resources
  106462. */
  106463. SceneOptimizer.prototype.dispose = function () {
  106464. this.stop();
  106465. this.onSuccessObservable.clear();
  106466. this.onFailureObservable.clear();
  106467. this.onNewOptimizationAppliedObservable.clear();
  106468. if (this._sceneDisposeObserver) {
  106469. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  106470. }
  106471. };
  106472. /**
  106473. * Helper function to create a SceneOptimizer with one single line of code
  106474. * @param scene defines the scene to work on
  106475. * @param options defines the options to use with the SceneOptimizer
  106476. * @param onSuccess defines a callback to call on success
  106477. * @param onFailure defines a callback to call on failure
  106478. * @returns the new SceneOptimizer object
  106479. */
  106480. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  106481. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  106482. if (onSuccess) {
  106483. optimizer.onSuccessObservable.add(function () {
  106484. onSuccess();
  106485. });
  106486. }
  106487. if (onFailure) {
  106488. optimizer.onFailureObservable.add(function () {
  106489. onFailure();
  106490. });
  106491. }
  106492. optimizer.start();
  106493. return optimizer;
  106494. };
  106495. return SceneOptimizer;
  106496. }());
  106497. BABYLON.SceneOptimizer = SceneOptimizer;
  106498. })(BABYLON || (BABYLON = {}));
  106499. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  106500. var BABYLON;
  106501. (function (BABYLON) {
  106502. /**
  106503. * Gets the outline renderer associated with the scene
  106504. * @returns a OutlineRenderer
  106505. */
  106506. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  106507. if (!this._outlineRenderer) {
  106508. this._outlineRenderer = new OutlineRenderer(this);
  106509. }
  106510. return this._outlineRenderer;
  106511. };
  106512. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  106513. get: function () {
  106514. return this._renderOutline;
  106515. },
  106516. set: function (value) {
  106517. if (value) {
  106518. // Lazy Load the component.
  106519. this.getScene().getOutlineRenderer();
  106520. }
  106521. this._renderOutline = value;
  106522. },
  106523. enumerable: true,
  106524. configurable: true
  106525. });
  106526. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  106527. get: function () {
  106528. return this._renderOverlay;
  106529. },
  106530. set: function (value) {
  106531. if (value) {
  106532. // Lazy Load the component.
  106533. this.getScene().getOutlineRenderer();
  106534. }
  106535. this._renderOverlay = value;
  106536. },
  106537. enumerable: true,
  106538. configurable: true
  106539. });
  106540. /**
  106541. * This class is responsible to draw bothe outline/overlay of meshes.
  106542. * It should not be used directly but through the available method on mesh.
  106543. */
  106544. var OutlineRenderer = /** @class */ (function () {
  106545. /**
  106546. * Instantiates a new outline renderer. (There could be only one per scene).
  106547. * @param scene Defines the scene it belongs to
  106548. */
  106549. function OutlineRenderer(scene) {
  106550. /**
  106551. * The name of the component. Each component must have a unique name.
  106552. */
  106553. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  106554. /**
  106555. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  106556. */
  106557. this.zOffset = 1;
  106558. this.scene = scene;
  106559. this._engine = scene.getEngine();
  106560. this.scene._addComponent(this);
  106561. }
  106562. /**
  106563. * Register the component to one instance of a scene.
  106564. */
  106565. OutlineRenderer.prototype.register = function () {
  106566. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  106567. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  106568. };
  106569. /**
  106570. * Rebuilds the elements related to this component in case of
  106571. * context lost for instance.
  106572. */
  106573. OutlineRenderer.prototype.rebuild = function () {
  106574. // Nothing to do here.
  106575. };
  106576. /**
  106577. * Disposes the component and the associated ressources.
  106578. */
  106579. OutlineRenderer.prototype.dispose = function () {
  106580. // Nothing to do here.
  106581. };
  106582. /**
  106583. * Renders the outline in the canvas.
  106584. * @param subMesh Defines the sumesh to render
  106585. * @param batch Defines the batch of meshes in case of instances
  106586. * @param useOverlay Defines if the rendering is for the overlay or the outline
  106587. */
  106588. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  106589. var _this = this;
  106590. if (useOverlay === void 0) { useOverlay = false; }
  106591. var scene = this.scene;
  106592. var engine = scene.getEngine();
  106593. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  106594. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  106595. return;
  106596. }
  106597. var mesh = subMesh.getRenderingMesh();
  106598. var material = subMesh.getMaterial();
  106599. if (!material || !scene.activeCamera) {
  106600. return;
  106601. }
  106602. engine.enableEffect(this._effect);
  106603. // Logarithmic depth
  106604. if (material.useLogarithmicDepth) {
  106605. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  106606. }
  106607. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  106608. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  106609. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  106610. // Bones
  106611. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  106612. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  106613. }
  106614. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  106615. // Alpha test
  106616. if (material && material.needAlphaTesting()) {
  106617. var alphaTexture = material.getAlphaTestTexture();
  106618. if (alphaTexture) {
  106619. this._effect.setTexture("diffuseSampler", alphaTexture);
  106620. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  106621. }
  106622. }
  106623. engine.setZOffset(-this.zOffset);
  106624. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  106625. engine.setZOffset(0);
  106626. };
  106627. /**
  106628. * Returns whether or not the outline renderer is ready for a given submesh.
  106629. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  106630. * @param subMesh Defines the submesh to check readyness for
  106631. * @param useInstances Defines wheter wee are trying to render instances or not
  106632. * @returns true if ready otherwise false
  106633. */
  106634. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  106635. var defines = [];
  106636. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  106637. var mesh = subMesh.getMesh();
  106638. var material = subMesh.getMaterial();
  106639. if (material) {
  106640. // Alpha test
  106641. if (material.needAlphaTesting()) {
  106642. defines.push("#define ALPHATEST");
  106643. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  106644. attribs.push(BABYLON.VertexBuffer.UVKind);
  106645. defines.push("#define UV1");
  106646. }
  106647. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  106648. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  106649. defines.push("#define UV2");
  106650. }
  106651. }
  106652. //Logarithmic depth
  106653. if (material.useLogarithmicDepth) {
  106654. defines.push("#define LOGARITHMICDEPTH");
  106655. }
  106656. }
  106657. // Bones
  106658. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  106659. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  106660. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  106661. if (mesh.numBoneInfluencers > 4) {
  106662. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  106663. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  106664. }
  106665. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  106666. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  106667. }
  106668. else {
  106669. defines.push("#define NUM_BONE_INFLUENCERS 0");
  106670. }
  106671. // Instances
  106672. if (useInstances) {
  106673. defines.push("#define INSTANCES");
  106674. attribs.push("world0");
  106675. attribs.push("world1");
  106676. attribs.push("world2");
  106677. attribs.push("world3");
  106678. }
  106679. // Get correct effect
  106680. var join = defines.join("\n");
  106681. if (this._cachedDefines !== join) {
  106682. this._cachedDefines = join;
  106683. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  106684. }
  106685. return this._effect.isReady();
  106686. };
  106687. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  106688. // Outline - step 1
  106689. this._savedDepthWrite = this._engine.getDepthWrite();
  106690. if (mesh.renderOutline) {
  106691. this._engine.setDepthWrite(false);
  106692. this.render(subMesh, batch);
  106693. this._engine.setDepthWrite(this._savedDepthWrite);
  106694. }
  106695. };
  106696. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  106697. // Outline - step 2
  106698. if (mesh.renderOutline && this._savedDepthWrite) {
  106699. this._engine.setDepthWrite(true);
  106700. this._engine.setColorWrite(false);
  106701. this.render(subMesh, batch);
  106702. this._engine.setColorWrite(true);
  106703. }
  106704. // Overlay
  106705. if (mesh.renderOverlay) {
  106706. var currentMode = this._engine.getAlphaMode();
  106707. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  106708. this.render(subMesh, batch, true);
  106709. this._engine.setAlphaMode(currentMode);
  106710. }
  106711. };
  106712. return OutlineRenderer;
  106713. }());
  106714. BABYLON.OutlineRenderer = OutlineRenderer;
  106715. })(BABYLON || (BABYLON = {}));
  106716. //# sourceMappingURL=babylon.outlineRenderer.js.map
  106717. var BABYLON;
  106718. (function (BABYLON) {
  106719. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  106720. if (this._edgesRenderer) {
  106721. this._edgesRenderer.dispose();
  106722. this._edgesRenderer = null;
  106723. }
  106724. return this;
  106725. };
  106726. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  106727. if (epsilon === void 0) { epsilon = 0.95; }
  106728. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  106729. this.disableEdgesRendering();
  106730. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  106731. return this;
  106732. };
  106733. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  106734. get: function () {
  106735. return this._edgesRenderer;
  106736. },
  106737. enumerable: true,
  106738. configurable: true
  106739. });
  106740. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  106741. if (epsilon === void 0) { epsilon = 0.95; }
  106742. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  106743. this.disableEdgesRendering();
  106744. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  106745. return this;
  106746. };
  106747. /**
  106748. * FaceAdjacencies Helper class to generate edges
  106749. */
  106750. var FaceAdjacencies = /** @class */ (function () {
  106751. function FaceAdjacencies() {
  106752. this.edges = new Array();
  106753. this.edgesConnectedCount = 0;
  106754. }
  106755. return FaceAdjacencies;
  106756. }());
  106757. /**
  106758. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  106759. */
  106760. var EdgesRenderer = /** @class */ (function () {
  106761. /**
  106762. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  106763. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  106764. * @param source Mesh used to create edges
  106765. * @param epsilon sum of angles in adjacency to check for edge
  106766. * @param checkVerticesInsteadOfIndices
  106767. * @param generateEdgesLines - should generate Lines or only prepare resources.
  106768. */
  106769. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  106770. if (epsilon === void 0) { epsilon = 0.95; }
  106771. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  106772. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  106773. var _this = this;
  106774. /**
  106775. * Define the size of the edges with an orthographic camera
  106776. */
  106777. this.edgesWidthScalerForOrthographic = 1000.0;
  106778. /**
  106779. * Define the size of the edges with a perspective camera
  106780. */
  106781. this.edgesWidthScalerForPerspective = 50.0;
  106782. this._linesPositions = new Array();
  106783. this._linesNormals = new Array();
  106784. this._linesIndices = new Array();
  106785. this._buffers = {};
  106786. this._checkVerticesInsteadOfIndices = false;
  106787. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  106788. this.isEnabled = true;
  106789. this._source = source;
  106790. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  106791. this._epsilon = epsilon;
  106792. this._prepareRessources();
  106793. if (generateEdgesLines) {
  106794. this._generateEdgesLines();
  106795. }
  106796. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  106797. _this._rebuild();
  106798. });
  106799. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  106800. _this.dispose();
  106801. });
  106802. }
  106803. EdgesRenderer.prototype._prepareRessources = function () {
  106804. if (this._lineShader) {
  106805. return;
  106806. }
  106807. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  106808. attributes: ["position", "normal"],
  106809. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  106810. });
  106811. this._lineShader.disableDepthWrite = true;
  106812. this._lineShader.backFaceCulling = false;
  106813. };
  106814. /** @hidden */
  106815. EdgesRenderer.prototype._rebuild = function () {
  106816. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  106817. if (buffer) {
  106818. buffer._rebuild();
  106819. }
  106820. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  106821. if (buffer) {
  106822. buffer._rebuild();
  106823. }
  106824. var scene = this._source.getScene();
  106825. var engine = scene.getEngine();
  106826. this._ib = engine.createIndexBuffer(this._linesIndices);
  106827. };
  106828. /**
  106829. * Releases the required resources for the edges renderer
  106830. */
  106831. EdgesRenderer.prototype.dispose = function () {
  106832. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  106833. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  106834. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  106835. if (buffer) {
  106836. buffer.dispose();
  106837. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  106838. }
  106839. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  106840. if (buffer) {
  106841. buffer.dispose();
  106842. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  106843. }
  106844. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  106845. this._lineShader.dispose();
  106846. };
  106847. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  106848. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  106849. return 0;
  106850. }
  106851. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  106852. return 1;
  106853. }
  106854. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  106855. return 2;
  106856. }
  106857. return -1;
  106858. };
  106859. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  106860. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  106861. return 0;
  106862. }
  106863. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  106864. return 1;
  106865. }
  106866. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  106867. return 2;
  106868. }
  106869. return -1;
  106870. };
  106871. /**
  106872. * Checks if the pair of p0 and p1 is en edge
  106873. * @param faceIndex
  106874. * @param edge
  106875. * @param faceNormals
  106876. * @param p0
  106877. * @param p1
  106878. * @private
  106879. */
  106880. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  106881. var needToCreateLine;
  106882. if (edge === undefined) {
  106883. needToCreateLine = true;
  106884. }
  106885. else {
  106886. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  106887. needToCreateLine = dotProduct < this._epsilon;
  106888. }
  106889. if (needToCreateLine) {
  106890. var offset = this._linesPositions.length / 3;
  106891. var normal = p0.subtract(p1);
  106892. normal.normalize();
  106893. // Positions
  106894. this._linesPositions.push(p0.x);
  106895. this._linesPositions.push(p0.y);
  106896. this._linesPositions.push(p0.z);
  106897. this._linesPositions.push(p0.x);
  106898. this._linesPositions.push(p0.y);
  106899. this._linesPositions.push(p0.z);
  106900. this._linesPositions.push(p1.x);
  106901. this._linesPositions.push(p1.y);
  106902. this._linesPositions.push(p1.z);
  106903. this._linesPositions.push(p1.x);
  106904. this._linesPositions.push(p1.y);
  106905. this._linesPositions.push(p1.z);
  106906. // Normals
  106907. this._linesNormals.push(p1.x);
  106908. this._linesNormals.push(p1.y);
  106909. this._linesNormals.push(p1.z);
  106910. this._linesNormals.push(-1);
  106911. this._linesNormals.push(p1.x);
  106912. this._linesNormals.push(p1.y);
  106913. this._linesNormals.push(p1.z);
  106914. this._linesNormals.push(1);
  106915. this._linesNormals.push(p0.x);
  106916. this._linesNormals.push(p0.y);
  106917. this._linesNormals.push(p0.z);
  106918. this._linesNormals.push(-1);
  106919. this._linesNormals.push(p0.x);
  106920. this._linesNormals.push(p0.y);
  106921. this._linesNormals.push(p0.z);
  106922. this._linesNormals.push(1);
  106923. // Indices
  106924. this._linesIndices.push(offset);
  106925. this._linesIndices.push(offset + 1);
  106926. this._linesIndices.push(offset + 2);
  106927. this._linesIndices.push(offset);
  106928. this._linesIndices.push(offset + 2);
  106929. this._linesIndices.push(offset + 3);
  106930. }
  106931. };
  106932. /**
  106933. * Generates lines edges from adjacencjes
  106934. * @private
  106935. */
  106936. EdgesRenderer.prototype._generateEdgesLines = function () {
  106937. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  106938. var indices = this._source.getIndices();
  106939. if (!indices || !positions) {
  106940. return;
  106941. }
  106942. // First let's find adjacencies
  106943. var adjacencies = new Array();
  106944. var faceNormals = new Array();
  106945. var index;
  106946. var faceAdjacencies;
  106947. // Prepare faces
  106948. for (index = 0; index < indices.length; index += 3) {
  106949. faceAdjacencies = new FaceAdjacencies();
  106950. var p0Index = indices[index];
  106951. var p1Index = indices[index + 1];
  106952. var p2Index = indices[index + 2];
  106953. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  106954. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  106955. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  106956. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  106957. faceNormal.normalize();
  106958. faceNormals.push(faceNormal);
  106959. adjacencies.push(faceAdjacencies);
  106960. }
  106961. // Scan
  106962. for (index = 0; index < adjacencies.length; index++) {
  106963. faceAdjacencies = adjacencies[index];
  106964. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  106965. var otherFaceAdjacencies = adjacencies[otherIndex];
  106966. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  106967. break;
  106968. }
  106969. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  106970. continue;
  106971. }
  106972. var otherP0 = indices[otherIndex * 3];
  106973. var otherP1 = indices[otherIndex * 3 + 1];
  106974. var otherP2 = indices[otherIndex * 3 + 2];
  106975. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  106976. var otherEdgeIndex = 0;
  106977. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  106978. continue;
  106979. }
  106980. switch (edgeIndex) {
  106981. case 0:
  106982. if (this._checkVerticesInsteadOfIndices) {
  106983. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  106984. }
  106985. else {
  106986. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  106987. }
  106988. break;
  106989. case 1:
  106990. if (this._checkVerticesInsteadOfIndices) {
  106991. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  106992. }
  106993. else {
  106994. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  106995. }
  106996. break;
  106997. case 2:
  106998. if (this._checkVerticesInsteadOfIndices) {
  106999. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  107000. }
  107001. else {
  107002. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  107003. }
  107004. break;
  107005. }
  107006. if (otherEdgeIndex === -1) {
  107007. continue;
  107008. }
  107009. faceAdjacencies.edges[edgeIndex] = otherIndex;
  107010. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  107011. faceAdjacencies.edgesConnectedCount++;
  107012. otherFaceAdjacencies.edgesConnectedCount++;
  107013. if (faceAdjacencies.edgesConnectedCount === 3) {
  107014. break;
  107015. }
  107016. }
  107017. }
  107018. }
  107019. // Create lines
  107020. for (index = 0; index < adjacencies.length; index++) {
  107021. // 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
  107022. var current = adjacencies[index];
  107023. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  107024. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  107025. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  107026. }
  107027. // Merge into a single mesh
  107028. var engine = this._source.getScene().getEngine();
  107029. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  107030. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  107031. this._ib = engine.createIndexBuffer(this._linesIndices);
  107032. this._indicesCount = this._linesIndices.length;
  107033. };
  107034. /**
  107035. * Checks wether or not the edges renderer is ready to render.
  107036. * @return true if ready, otherwise false.
  107037. */
  107038. EdgesRenderer.prototype.isReady = function () {
  107039. return this._lineShader.isReady();
  107040. };
  107041. /**
  107042. * Renders the edges of the attached mesh,
  107043. */
  107044. EdgesRenderer.prototype.render = function () {
  107045. var scene = this._source.getScene();
  107046. if (!this.isReady() || !scene.activeCamera) {
  107047. return;
  107048. }
  107049. var engine = scene.getEngine();
  107050. this._lineShader._preBind();
  107051. if (this._source.edgesColor.a !== 1) {
  107052. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  107053. }
  107054. else {
  107055. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  107056. }
  107057. // VBOs
  107058. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  107059. scene.resetCachedMaterial();
  107060. this._lineShader.setColor4("color", this._source.edgesColor);
  107061. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  107062. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  107063. }
  107064. else {
  107065. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  107066. }
  107067. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  107068. this._lineShader.bind(this._source.getWorldMatrix());
  107069. // Draw order
  107070. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  107071. this._lineShader.unbind();
  107072. };
  107073. return EdgesRenderer;
  107074. }());
  107075. BABYLON.EdgesRenderer = EdgesRenderer;
  107076. })(BABYLON || (BABYLON = {}));
  107077. //# sourceMappingURL=babylon.edgesRenderer.js.map
  107078. var BABYLON;
  107079. (function (BABYLON) {
  107080. /**
  107081. * FaceAdjacencies Helper class to generate edges
  107082. */
  107083. var FaceAdjacencies = /** @class */ (function () {
  107084. function FaceAdjacencies() {
  107085. this.edges = new Array();
  107086. this.edgesConnectedCount = 0;
  107087. }
  107088. return FaceAdjacencies;
  107089. }());
  107090. /**
  107091. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  107092. */
  107093. var LineEdgesRenderer = /** @class */ (function (_super) {
  107094. __extends(LineEdgesRenderer, _super);
  107095. /**
  107096. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  107097. * @param source LineMesh used to generate edges
  107098. * @param epsilon not important (specified angle for edge detection)
  107099. * @param checkVerticesInsteadOfIndices not important for LineMesh
  107100. */
  107101. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  107102. if (epsilon === void 0) { epsilon = 0.95; }
  107103. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  107104. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  107105. _this._generateEdgesLines();
  107106. return _this;
  107107. }
  107108. /**
  107109. * Always create the edge since its a line so only important things are p0 and p1
  107110. * @param faceIndex not important for LineMesh
  107111. * @param edge not important for LineMesh
  107112. * @param faceNormals not important for LineMesh
  107113. * @param p0 beginnig of line
  107114. * @param p1 end of line
  107115. */
  107116. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  107117. var offset = this._linesPositions.length / 3;
  107118. var normal = p0.subtract(p1);
  107119. normal.normalize();
  107120. // Positions
  107121. this._linesPositions.push(p0.x);
  107122. this._linesPositions.push(p0.y);
  107123. this._linesPositions.push(p0.z);
  107124. this._linesPositions.push(p0.x);
  107125. this._linesPositions.push(p0.y);
  107126. this._linesPositions.push(p0.z);
  107127. this._linesPositions.push(p1.x);
  107128. this._linesPositions.push(p1.y);
  107129. this._linesPositions.push(p1.z);
  107130. this._linesPositions.push(p1.x);
  107131. this._linesPositions.push(p1.y);
  107132. this._linesPositions.push(p1.z);
  107133. // Normals
  107134. this._linesNormals.push(p1.x);
  107135. this._linesNormals.push(p1.y);
  107136. this._linesNormals.push(p1.z);
  107137. this._linesNormals.push(-1);
  107138. this._linesNormals.push(p1.x);
  107139. this._linesNormals.push(p1.y);
  107140. this._linesNormals.push(p1.z);
  107141. this._linesNormals.push(1);
  107142. this._linesNormals.push(p0.x);
  107143. this._linesNormals.push(p0.y);
  107144. this._linesNormals.push(p0.z);
  107145. this._linesNormals.push(-1);
  107146. this._linesNormals.push(p0.x);
  107147. this._linesNormals.push(p0.y);
  107148. this._linesNormals.push(p0.z);
  107149. this._linesNormals.push(1);
  107150. // Indices
  107151. this._linesIndices.push(offset);
  107152. this._linesIndices.push(offset + 1);
  107153. this._linesIndices.push(offset + 2);
  107154. this._linesIndices.push(offset);
  107155. this._linesIndices.push(offset + 2);
  107156. this._linesIndices.push(offset + 3);
  107157. };
  107158. /**
  107159. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  107160. */
  107161. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  107162. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  107163. var indices = this._source.getIndices();
  107164. if (!indices || !positions) {
  107165. return;
  107166. }
  107167. // First let's find adjacencies
  107168. var adjacencies = new Array();
  107169. var faceNormals = new Array();
  107170. var index;
  107171. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  107172. var currentAdjecancy = new FaceAdjacencies();
  107173. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  107174. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  107175. adjacencies.push(currentAdjecancy);
  107176. }
  107177. // Create lines
  107178. for (index = 0; index < adjacencies.length; index++) {
  107179. // 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
  107180. var current = adjacencies[index];
  107181. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  107182. }
  107183. // Merge into a single mesh
  107184. var engine = this._source.getScene().getEngine();
  107185. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  107186. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  107187. this._ib = engine.createIndexBuffer(this._linesIndices);
  107188. this._indicesCount = this._linesIndices.length;
  107189. };
  107190. return LineEdgesRenderer;
  107191. }(BABYLON.EdgesRenderer));
  107192. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  107193. })(BABYLON || (BABYLON = {}));
  107194. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  107195. var BABYLON;
  107196. (function (BABYLON) {
  107197. // Adds the parser to the scene parsers.
  107198. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  107199. if (parsedData.effectLayers) {
  107200. if (!container.effectLayers) {
  107201. container.effectLayers = new Array();
  107202. }
  107203. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  107204. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  107205. container.effectLayers.push(effectLayer);
  107206. }
  107207. }
  107208. });
  107209. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  107210. var index = this.effectLayers.indexOf(toRemove);
  107211. if (index !== -1) {
  107212. this.effectLayers.splice(index, 1);
  107213. }
  107214. return index;
  107215. };
  107216. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  107217. this.effectLayers.push(newEffectLayer);
  107218. };
  107219. /**
  107220. * Defines the layer scene component responsible to manage any effect layers
  107221. * in a given scene.
  107222. */
  107223. var EffectLayerSceneComponent = /** @class */ (function () {
  107224. /**
  107225. * Creates a new instance of the component for the given scene
  107226. * @param scene Defines the scene to register the component in
  107227. */
  107228. function EffectLayerSceneComponent(scene) {
  107229. /**
  107230. * The component name helpfull to identify the component in the list of scene components.
  107231. */
  107232. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  107233. this._renderEffects = false;
  107234. this._needStencil = false;
  107235. this._previousStencilState = false;
  107236. this.scene = scene;
  107237. this._engine = scene.getEngine();
  107238. scene.effectLayers = new Array();
  107239. }
  107240. /**
  107241. * Registers the component in a given scene
  107242. */
  107243. EffectLayerSceneComponent.prototype.register = function () {
  107244. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  107245. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  107246. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  107247. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  107248. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  107249. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  107250. };
  107251. /**
  107252. * Rebuilds the elements related to this component in case of
  107253. * context lost for instance.
  107254. */
  107255. EffectLayerSceneComponent.prototype.rebuild = function () {
  107256. var layers = this.scene.effectLayers;
  107257. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  107258. var effectLayer = layers_1[_i];
  107259. effectLayer._rebuild();
  107260. }
  107261. };
  107262. /**
  107263. * Serializes the component data to the specified json object
  107264. * @param serializationObject The object to serialize to
  107265. */
  107266. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  107267. // Effect layers
  107268. serializationObject.effectLayers = [];
  107269. var layers = this.scene.effectLayers;
  107270. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  107271. var effectLayer = layers_2[_i];
  107272. if (effectLayer.serialize) {
  107273. serializationObject.effectLayers.push(effectLayer.serialize());
  107274. }
  107275. }
  107276. };
  107277. /**
  107278. * Adds all the element from the container to the scene
  107279. * @param container the container holding the elements
  107280. */
  107281. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  107282. var _this = this;
  107283. if (!container.effectLayers) {
  107284. return;
  107285. }
  107286. container.effectLayers.forEach(function (o) {
  107287. _this.scene.addEffectLayer(o);
  107288. });
  107289. };
  107290. /**
  107291. * Removes all the elements in the container from the scene
  107292. * @param container contains the elements to remove
  107293. */
  107294. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  107295. var _this = this;
  107296. if (!container.effectLayers) {
  107297. return;
  107298. }
  107299. container.effectLayers.forEach(function (o) {
  107300. _this.scene.removeEffectLayer(o);
  107301. });
  107302. };
  107303. /**
  107304. * Disposes the component and the associated ressources.
  107305. */
  107306. EffectLayerSceneComponent.prototype.dispose = function () {
  107307. var layers = this.scene.effectLayers;
  107308. while (layers.length) {
  107309. layers[0].dispose();
  107310. }
  107311. };
  107312. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  107313. var layers = this.scene.effectLayers;
  107314. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  107315. var layer = layers_3[_i];
  107316. if (!layer.hasMesh(mesh)) {
  107317. continue;
  107318. }
  107319. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  107320. var subMesh = _b[_a];
  107321. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  107322. return false;
  107323. }
  107324. }
  107325. }
  107326. return true;
  107327. };
  107328. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  107329. this._renderEffects = false;
  107330. this._needStencil = false;
  107331. var layers = this.scene.effectLayers;
  107332. if (layers && layers.length > 0) {
  107333. this._previousStencilState = this._engine.getStencilBuffer();
  107334. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  107335. var effectLayer = layers_4[_i];
  107336. if (effectLayer.shouldRender() &&
  107337. (!effectLayer.camera ||
  107338. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  107339. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  107340. this._renderEffects = true;
  107341. this._needStencil = this._needStencil || effectLayer.needStencil();
  107342. var renderTarget = effectLayer._mainTexture;
  107343. if (renderTarget._shouldRender()) {
  107344. this.scene.incrementRenderId();
  107345. renderTarget.render(false, false);
  107346. }
  107347. }
  107348. }
  107349. this.scene.incrementRenderId();
  107350. }
  107351. };
  107352. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  107353. // Activate effect Layer stencil
  107354. if (this._needStencil) {
  107355. this._engine.setStencilBuffer(true);
  107356. }
  107357. };
  107358. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  107359. // Restore effect Layer stencil
  107360. if (this._needStencil) {
  107361. this._engine.setStencilBuffer(this._previousStencilState);
  107362. }
  107363. };
  107364. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  107365. if (this._renderEffects) {
  107366. this._engine.setDepthBuffer(false);
  107367. var layers = this.scene.effectLayers;
  107368. for (var i = 0; i < layers.length; i++) {
  107369. var effectLayer = layers[i];
  107370. if (effectLayer.renderingGroupId === renderingGroupId) {
  107371. if (effectLayer.shouldRender()) {
  107372. effectLayer.render();
  107373. }
  107374. }
  107375. }
  107376. this._engine.setDepthBuffer(true);
  107377. }
  107378. };
  107379. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  107380. if (this._renderEffects) {
  107381. this._draw(-1);
  107382. }
  107383. };
  107384. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  107385. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  107386. this._draw(index);
  107387. }
  107388. };
  107389. return EffectLayerSceneComponent;
  107390. }());
  107391. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  107392. })(BABYLON || (BABYLON = {}));
  107393. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  107394. var __assign = (this && this.__assign) || function () {
  107395. __assign = Object.assign || function(t) {
  107396. for (var s, i = 1, n = arguments.length; i < n; i++) {
  107397. s = arguments[i];
  107398. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  107399. t[p] = s[p];
  107400. }
  107401. return t;
  107402. };
  107403. return __assign.apply(this, arguments);
  107404. };
  107405. var BABYLON;
  107406. (function (BABYLON) {
  107407. /**
  107408. * The effect layer Helps adding post process effect blended with the main pass.
  107409. *
  107410. * This can be for instance use to generate glow or higlight effects on the scene.
  107411. *
  107412. * The effect layer class can not be used directly and is intented to inherited from to be
  107413. * customized per effects.
  107414. */
  107415. var EffectLayer = /** @class */ (function () {
  107416. /**
  107417. * Instantiates a new effect Layer and references it in the scene.
  107418. * @param name The name of the layer
  107419. * @param scene The scene to use the layer in
  107420. */
  107421. function EffectLayer(
  107422. /** The Friendly of the effect in the scene */
  107423. name, scene) {
  107424. this._vertexBuffers = {};
  107425. this._maxSize = 0;
  107426. this._mainTextureDesiredSize = { width: 0, height: 0 };
  107427. this._shouldRender = true;
  107428. this._postProcesses = [];
  107429. this._textures = [];
  107430. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  107431. /**
  107432. * The clear color of the texture used to generate the glow map.
  107433. */
  107434. this.neutralColor = new BABYLON.Color4();
  107435. /**
  107436. * Specifies wether the highlight layer is enabled or not.
  107437. */
  107438. this.isEnabled = true;
  107439. /**
  107440. * An event triggered when the effect layer has been disposed.
  107441. */
  107442. this.onDisposeObservable = new BABYLON.Observable();
  107443. /**
  107444. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  107445. */
  107446. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  107447. /**
  107448. * An event triggered when the generated texture is being merged in the scene.
  107449. */
  107450. this.onBeforeComposeObservable = new BABYLON.Observable();
  107451. /**
  107452. * An event triggered when the generated texture has been merged in the scene.
  107453. */
  107454. this.onAfterComposeObservable = new BABYLON.Observable();
  107455. /**
  107456. * An event triggered when the efffect layer changes its size.
  107457. */
  107458. this.onSizeChangedObservable = new BABYLON.Observable();
  107459. this.name = name;
  107460. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  107461. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  107462. if (!component) {
  107463. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  107464. this._scene._addComponent(component);
  107465. }
  107466. this._engine = this._scene.getEngine();
  107467. this._maxSize = this._engine.getCaps().maxTextureSize;
  107468. this._scene.effectLayers.push(this);
  107469. // Generate Buffers
  107470. this._generateIndexBuffer();
  107471. this._genrateVertexBuffer();
  107472. }
  107473. Object.defineProperty(EffectLayer.prototype, "camera", {
  107474. /**
  107475. * Gets the camera attached to the layer.
  107476. */
  107477. get: function () {
  107478. return this._effectLayerOptions.camera;
  107479. },
  107480. enumerable: true,
  107481. configurable: true
  107482. });
  107483. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  107484. /**
  107485. * Gets the rendering group id the layer should render in.
  107486. */
  107487. get: function () {
  107488. return this._effectLayerOptions.renderingGroupId;
  107489. },
  107490. enumerable: true,
  107491. configurable: true
  107492. });
  107493. /**
  107494. * Initializes the effect layer with the required options.
  107495. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  107496. */
  107497. EffectLayer.prototype._init = function (options) {
  107498. // Adapt options
  107499. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  107500. this._setMainTextureSize();
  107501. this._createMainTexture();
  107502. this._createTextureAndPostProcesses();
  107503. this._mergeEffect = this._createMergeEffect();
  107504. };
  107505. /**
  107506. * Generates the index buffer of the full screen quad blending to the main canvas.
  107507. */
  107508. EffectLayer.prototype._generateIndexBuffer = function () {
  107509. // Indices
  107510. var indices = [];
  107511. indices.push(0);
  107512. indices.push(1);
  107513. indices.push(2);
  107514. indices.push(0);
  107515. indices.push(2);
  107516. indices.push(3);
  107517. this._indexBuffer = this._engine.createIndexBuffer(indices);
  107518. };
  107519. /**
  107520. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  107521. */
  107522. EffectLayer.prototype._genrateVertexBuffer = function () {
  107523. // VBO
  107524. var vertices = [];
  107525. vertices.push(1, 1);
  107526. vertices.push(-1, 1);
  107527. vertices.push(-1, -1);
  107528. vertices.push(1, -1);
  107529. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  107530. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  107531. };
  107532. /**
  107533. * Sets the main texture desired size which is the closest power of two
  107534. * of the engine canvas size.
  107535. */
  107536. EffectLayer.prototype._setMainTextureSize = function () {
  107537. if (this._effectLayerOptions.mainTextureFixedSize) {
  107538. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  107539. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  107540. }
  107541. else {
  107542. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  107543. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  107544. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  107545. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  107546. }
  107547. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  107548. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  107549. };
  107550. /**
  107551. * Creates the main texture for the effect layer.
  107552. */
  107553. EffectLayer.prototype._createMainTexture = function () {
  107554. var _this = this;
  107555. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  107556. width: this._mainTextureDesiredSize.width,
  107557. height: this._mainTextureDesiredSize.height
  107558. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  107559. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  107560. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107561. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107562. this._mainTexture.anisotropicFilteringLevel = 1;
  107563. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  107564. this._mainTexture.renderParticles = false;
  107565. this._mainTexture.renderList = null;
  107566. this._mainTexture.ignoreCameraViewport = true;
  107567. // Custom render function
  107568. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  107569. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  107570. var index;
  107571. var engine = _this._scene.getEngine();
  107572. if (depthOnlySubMeshes.length) {
  107573. engine.setColorWrite(false);
  107574. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  107575. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  107576. }
  107577. engine.setColorWrite(true);
  107578. }
  107579. for (index = 0; index < opaqueSubMeshes.length; index++) {
  107580. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  107581. }
  107582. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  107583. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  107584. }
  107585. for (index = 0; index < transparentSubMeshes.length; index++) {
  107586. _this._renderSubMesh(transparentSubMeshes.data[index]);
  107587. }
  107588. };
  107589. this._mainTexture.onClearObservable.add(function (engine) {
  107590. engine.clear(_this.neutralColor, true, true, true);
  107591. });
  107592. };
  107593. /**
  107594. * Checks for the readiness of the element composing the layer.
  107595. * @param subMesh the mesh to check for
  107596. * @param useInstances specify wether or not to use instances to render the mesh
  107597. * @param emissiveTexture the associated emissive texture used to generate the glow
  107598. * @return true if ready otherwise, false
  107599. */
  107600. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  107601. var material = subMesh.getMaterial();
  107602. if (!material) {
  107603. return false;
  107604. }
  107605. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  107606. return false;
  107607. }
  107608. var defines = [];
  107609. var attribs = [BABYLON.VertexBuffer.PositionKind];
  107610. var mesh = subMesh.getMesh();
  107611. var uv1 = false;
  107612. var uv2 = false;
  107613. // Alpha test
  107614. if (material && material.needAlphaTesting()) {
  107615. var alphaTexture = material.getAlphaTestTexture();
  107616. if (alphaTexture) {
  107617. defines.push("#define ALPHATEST");
  107618. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  107619. alphaTexture.coordinatesIndex === 1) {
  107620. defines.push("#define DIFFUSEUV2");
  107621. uv2 = true;
  107622. }
  107623. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  107624. defines.push("#define DIFFUSEUV1");
  107625. uv1 = true;
  107626. }
  107627. }
  107628. }
  107629. // Emissive
  107630. if (emissiveTexture) {
  107631. defines.push("#define EMISSIVE");
  107632. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  107633. emissiveTexture.coordinatesIndex === 1) {
  107634. defines.push("#define EMISSIVEUV2");
  107635. uv2 = true;
  107636. }
  107637. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  107638. defines.push("#define EMISSIVEUV1");
  107639. uv1 = true;
  107640. }
  107641. }
  107642. if (uv1) {
  107643. attribs.push(BABYLON.VertexBuffer.UVKind);
  107644. defines.push("#define UV1");
  107645. }
  107646. if (uv2) {
  107647. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  107648. defines.push("#define UV2");
  107649. }
  107650. // Bones
  107651. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  107652. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  107653. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  107654. if (mesh.numBoneInfluencers > 4) {
  107655. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  107656. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  107657. }
  107658. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  107659. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  107660. }
  107661. else {
  107662. defines.push("#define NUM_BONE_INFLUENCERS 0");
  107663. }
  107664. // Morph targets
  107665. var manager = mesh.morphTargetManager;
  107666. var morphInfluencers = 0;
  107667. if (manager) {
  107668. if (manager.numInfluencers > 0) {
  107669. defines.push("#define MORPHTARGETS");
  107670. morphInfluencers = manager.numInfluencers;
  107671. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  107672. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  107673. }
  107674. }
  107675. // Instances
  107676. if (useInstances) {
  107677. defines.push("#define INSTANCES");
  107678. attribs.push("world0");
  107679. attribs.push("world1");
  107680. attribs.push("world2");
  107681. attribs.push("world3");
  107682. }
  107683. // Get correct effect
  107684. var join = defines.join("\n");
  107685. if (this._cachedDefines !== join) {
  107686. this._cachedDefines = join;
  107687. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  107688. }
  107689. return this._effectLayerMapGenerationEffect.isReady();
  107690. };
  107691. /**
  107692. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  107693. */
  107694. EffectLayer.prototype.render = function () {
  107695. var currentEffect = this._mergeEffect;
  107696. // Check
  107697. if (!currentEffect.isReady())
  107698. return;
  107699. for (var i = 0; i < this._postProcesses.length; i++) {
  107700. if (!this._postProcesses[i].isReady()) {
  107701. return;
  107702. }
  107703. }
  107704. var engine = this._scene.getEngine();
  107705. this.onBeforeComposeObservable.notifyObservers(this);
  107706. // Render
  107707. engine.enableEffect(currentEffect);
  107708. engine.setState(false);
  107709. // VBOs
  107710. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  107711. // Cache
  107712. var previousAlphaMode = engine.getAlphaMode();
  107713. // Go Blend.
  107714. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  107715. // Blends the map on the main canvas.
  107716. this._internalRender(currentEffect);
  107717. // Restore Alpha
  107718. engine.setAlphaMode(previousAlphaMode);
  107719. this.onAfterComposeObservable.notifyObservers(this);
  107720. // Handle size changes.
  107721. var size = this._mainTexture.getSize();
  107722. this._setMainTextureSize();
  107723. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  107724. // Recreate RTT and post processes on size change.
  107725. this.onSizeChangedObservable.notifyObservers(this);
  107726. this._disposeTextureAndPostProcesses();
  107727. this._createMainTexture();
  107728. this._createTextureAndPostProcesses();
  107729. }
  107730. };
  107731. /**
  107732. * Determine if a given mesh will be used in the current effect.
  107733. * @param mesh mesh to test
  107734. * @returns true if the mesh will be used
  107735. */
  107736. EffectLayer.prototype.hasMesh = function (mesh) {
  107737. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  107738. return true;
  107739. }
  107740. return false;
  107741. };
  107742. /**
  107743. * Returns true if the layer contains information to display, otherwise false.
  107744. * @returns true if the glow layer should be rendered
  107745. */
  107746. EffectLayer.prototype.shouldRender = function () {
  107747. return this.isEnabled && this._shouldRender;
  107748. };
  107749. /**
  107750. * Returns true if the mesh should render, otherwise false.
  107751. * @param mesh The mesh to render
  107752. * @returns true if it should render otherwise false
  107753. */
  107754. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  107755. return true;
  107756. };
  107757. /**
  107758. * Returns true if the mesh should render, otherwise false.
  107759. * @param mesh The mesh to render
  107760. * @returns true if it should render otherwise false
  107761. */
  107762. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  107763. return true;
  107764. };
  107765. /**
  107766. * Renders the submesh passed in parameter to the generation map.
  107767. */
  107768. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  107769. var _this = this;
  107770. if (!this.shouldRender()) {
  107771. return;
  107772. }
  107773. var material = subMesh.getMaterial();
  107774. var mesh = subMesh.getRenderingMesh();
  107775. var scene = this._scene;
  107776. var engine = scene.getEngine();
  107777. if (!material) {
  107778. return;
  107779. }
  107780. // Do not block in blend mode.
  107781. if (material.needAlphaBlendingForMesh(mesh)) {
  107782. return;
  107783. }
  107784. // Culling
  107785. engine.setState(material.backFaceCulling);
  107786. // Managing instances
  107787. var batch = mesh._getInstancesRenderList(subMesh._id);
  107788. if (batch.mustReturn) {
  107789. return;
  107790. }
  107791. // Early Exit per mesh
  107792. if (!this._shouldRenderMesh(mesh)) {
  107793. return;
  107794. }
  107795. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  107796. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  107797. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  107798. engine.enableEffect(this._effectLayerMapGenerationEffect);
  107799. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  107800. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  107801. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  107802. // Alpha test
  107803. if (material && material.needAlphaTesting()) {
  107804. var alphaTexture = material.getAlphaTestTexture();
  107805. if (alphaTexture) {
  107806. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  107807. var textureMatrix = alphaTexture.getTextureMatrix();
  107808. if (textureMatrix) {
  107809. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  107810. }
  107811. }
  107812. }
  107813. // Glow emissive only
  107814. if (this._emissiveTextureAndColor.texture) {
  107815. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  107816. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  107817. }
  107818. // Bones
  107819. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  107820. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  107821. }
  107822. // Morph targets
  107823. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  107824. // Draw
  107825. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  107826. }
  107827. else {
  107828. // Need to reset refresh rate of the main map
  107829. this._mainTexture.resetRefreshCounter();
  107830. }
  107831. };
  107832. /**
  107833. * Rebuild the required buffers.
  107834. * @hidden Internal use only.
  107835. */
  107836. EffectLayer.prototype._rebuild = function () {
  107837. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  107838. if (vb) {
  107839. vb._rebuild();
  107840. }
  107841. this._generateIndexBuffer();
  107842. };
  107843. /**
  107844. * Dispose only the render target textures and post process.
  107845. */
  107846. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  107847. this._mainTexture.dispose();
  107848. for (var i = 0; i < this._postProcesses.length; i++) {
  107849. if (this._postProcesses[i]) {
  107850. this._postProcesses[i].dispose();
  107851. }
  107852. }
  107853. this._postProcesses = [];
  107854. for (var i = 0; i < this._textures.length; i++) {
  107855. if (this._textures[i]) {
  107856. this._textures[i].dispose();
  107857. }
  107858. }
  107859. this._textures = [];
  107860. };
  107861. /**
  107862. * Dispose the highlight layer and free resources.
  107863. */
  107864. EffectLayer.prototype.dispose = function () {
  107865. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  107866. if (vertexBuffer) {
  107867. vertexBuffer.dispose();
  107868. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  107869. }
  107870. if (this._indexBuffer) {
  107871. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  107872. this._indexBuffer = null;
  107873. }
  107874. // Clean textures and post processes
  107875. this._disposeTextureAndPostProcesses();
  107876. // Remove from scene
  107877. var index = this._scene.effectLayers.indexOf(this, 0);
  107878. if (index > -1) {
  107879. this._scene.effectLayers.splice(index, 1);
  107880. }
  107881. // Callback
  107882. this.onDisposeObservable.notifyObservers(this);
  107883. this.onDisposeObservable.clear();
  107884. this.onBeforeRenderMainTextureObservable.clear();
  107885. this.onBeforeComposeObservable.clear();
  107886. this.onAfterComposeObservable.clear();
  107887. this.onSizeChangedObservable.clear();
  107888. };
  107889. /**
  107890. * Gets the class name of the effect layer
  107891. * @returns the string with the class name of the effect layer
  107892. */
  107893. EffectLayer.prototype.getClassName = function () {
  107894. return "EffectLayer";
  107895. };
  107896. /**
  107897. * Creates an effect layer from parsed effect layer data
  107898. * @param parsedEffectLayer defines effect layer data
  107899. * @param scene defines the current scene
  107900. * @param rootUrl defines the root URL containing the effect layer information
  107901. * @returns a parsed effect Layer
  107902. */
  107903. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  107904. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  107905. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  107906. };
  107907. __decorate([
  107908. BABYLON.serialize()
  107909. ], EffectLayer.prototype, "name", void 0);
  107910. __decorate([
  107911. BABYLON.serializeAsColor4()
  107912. ], EffectLayer.prototype, "neutralColor", void 0);
  107913. __decorate([
  107914. BABYLON.serialize()
  107915. ], EffectLayer.prototype, "isEnabled", void 0);
  107916. __decorate([
  107917. BABYLON.serializeAsCameraReference()
  107918. ], EffectLayer.prototype, "camera", null);
  107919. __decorate([
  107920. BABYLON.serialize()
  107921. ], EffectLayer.prototype, "renderingGroupId", null);
  107922. return EffectLayer;
  107923. }());
  107924. BABYLON.EffectLayer = EffectLayer;
  107925. })(BABYLON || (BABYLON = {}));
  107926. //# sourceMappingURL=babylon.effectLayer.js.map
  107927. var BABYLON;
  107928. (function (BABYLON) {
  107929. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  107930. for (var index = 0; index < this.effectLayers.length; index++) {
  107931. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  107932. return this.effectLayers[index];
  107933. }
  107934. }
  107935. return null;
  107936. };
  107937. /**
  107938. * Special Glow Blur post process only blurring the alpha channel
  107939. * It enforces keeping the most luminous color in the color channel.
  107940. */
  107941. var GlowBlurPostProcess = /** @class */ (function (_super) {
  107942. __extends(GlowBlurPostProcess, _super);
  107943. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  107944. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  107945. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  107946. _this.direction = direction;
  107947. _this.kernel = kernel;
  107948. _this.onApplyObservable.add(function (effect) {
  107949. effect.setFloat2("screenSize", _this.width, _this.height);
  107950. effect.setVector2("direction", _this.direction);
  107951. effect.setFloat("blurWidth", _this.kernel);
  107952. });
  107953. return _this;
  107954. }
  107955. return GlowBlurPostProcess;
  107956. }(BABYLON.PostProcess));
  107957. /**
  107958. * The highlight layer Helps adding a glow effect around a mesh.
  107959. *
  107960. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  107961. * glowy meshes to your scene.
  107962. *
  107963. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  107964. */
  107965. var HighlightLayer = /** @class */ (function (_super) {
  107966. __extends(HighlightLayer, _super);
  107967. /**
  107968. * Instantiates a new highlight Layer and references it to the scene..
  107969. * @param name The name of the layer
  107970. * @param scene The scene to use the layer in
  107971. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  107972. */
  107973. function HighlightLayer(name, scene, options) {
  107974. var _this = _super.call(this, name, scene) || this;
  107975. _this.name = name;
  107976. /**
  107977. * Specifies whether or not the inner glow is ACTIVE in the layer.
  107978. */
  107979. _this.innerGlow = true;
  107980. /**
  107981. * Specifies whether or not the outer glow is ACTIVE in the layer.
  107982. */
  107983. _this.outerGlow = true;
  107984. /**
  107985. * An event triggered when the highlight layer is being blurred.
  107986. */
  107987. _this.onBeforeBlurObservable = new BABYLON.Observable();
  107988. /**
  107989. * An event triggered when the highlight layer has been blurred.
  107990. */
  107991. _this.onAfterBlurObservable = new BABYLON.Observable();
  107992. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  107993. _this._meshes = {};
  107994. _this._excludedMeshes = {};
  107995. _this.neutralColor = HighlightLayer.NeutralColor;
  107996. // Warn on stencil
  107997. if (!_this._engine.isStencilEnable) {
  107998. 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 }");
  107999. }
  108000. // Adapt options
  108001. _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);
  108002. // Initialize the layer
  108003. _this._init({
  108004. alphaBlendingMode: _this._options.alphaBlendingMode,
  108005. camera: _this._options.camera,
  108006. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  108007. mainTextureRatio: _this._options.mainTextureRatio,
  108008. renderingGroupId: _this._options.renderingGroupId
  108009. });
  108010. // Do not render as long as no meshes have been added
  108011. _this._shouldRender = false;
  108012. return _this;
  108013. }
  108014. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  108015. /**
  108016. * Gets the horizontal size of the blur.
  108017. */
  108018. get: function () {
  108019. return this._horizontalBlurPostprocess.kernel;
  108020. },
  108021. /**
  108022. * Specifies the horizontal size of the blur.
  108023. */
  108024. set: function (value) {
  108025. this._horizontalBlurPostprocess.kernel = value;
  108026. },
  108027. enumerable: true,
  108028. configurable: true
  108029. });
  108030. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  108031. /**
  108032. * Gets the vertical size of the blur.
  108033. */
  108034. get: function () {
  108035. return this._verticalBlurPostprocess.kernel;
  108036. },
  108037. /**
  108038. * Specifies the vertical size of the blur.
  108039. */
  108040. set: function (value) {
  108041. this._verticalBlurPostprocess.kernel = value;
  108042. },
  108043. enumerable: true,
  108044. configurable: true
  108045. });
  108046. /**
  108047. * Get the effect name of the layer.
  108048. * @return The effect name
  108049. */
  108050. HighlightLayer.prototype.getEffectName = function () {
  108051. return HighlightLayer.EffectName;
  108052. };
  108053. /**
  108054. * Create the merge effect. This is the shader use to blit the information back
  108055. * to the main canvas at the end of the scene rendering.
  108056. */
  108057. HighlightLayer.prototype._createMergeEffect = function () {
  108058. // Effect
  108059. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  108060. };
  108061. /**
  108062. * Creates the render target textures and post processes used in the highlight layer.
  108063. */
  108064. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  108065. var _this = this;
  108066. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  108067. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  108068. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  108069. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  108070. var textureType = 0;
  108071. if (this._engine.getCaps().textureHalfFloatRender) {
  108072. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  108073. }
  108074. else {
  108075. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  108076. }
  108077. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  108078. width: blurTextureWidth,
  108079. height: blurTextureHeight
  108080. }, this._scene, false, true, textureType);
  108081. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108082. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108083. this._blurTexture.anisotropicFilteringLevel = 16;
  108084. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  108085. this._blurTexture.renderParticles = false;
  108086. this._blurTexture.ignoreCameraViewport = true;
  108087. this._textures = [this._blurTexture];
  108088. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  108089. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  108090. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  108091. effect.setTexture("textureSampler", _this._mainTexture);
  108092. });
  108093. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  108094. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  108095. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  108096. });
  108097. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  108098. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  108099. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  108100. });
  108101. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  108102. }
  108103. else {
  108104. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  108105. width: blurTextureWidth,
  108106. height: blurTextureHeight
  108107. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108108. this._horizontalBlurPostprocess.width = blurTextureWidth;
  108109. this._horizontalBlurPostprocess.height = blurTextureHeight;
  108110. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  108111. effect.setTexture("textureSampler", _this._mainTexture);
  108112. });
  108113. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  108114. width: blurTextureWidth,
  108115. height: blurTextureHeight
  108116. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108117. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  108118. }
  108119. this._mainTexture.onAfterUnbindObservable.add(function () {
  108120. _this.onBeforeBlurObservable.notifyObservers(_this);
  108121. var internalTexture = _this._blurTexture.getInternalTexture();
  108122. if (internalTexture) {
  108123. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  108124. }
  108125. _this.onAfterBlurObservable.notifyObservers(_this);
  108126. });
  108127. // Prevent autoClear.
  108128. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  108129. };
  108130. /**
  108131. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  108132. */
  108133. HighlightLayer.prototype.needStencil = function () {
  108134. return true;
  108135. };
  108136. /**
  108137. * Checks for the readiness of the element composing the layer.
  108138. * @param subMesh the mesh to check for
  108139. * @param useInstances specify wether or not to use instances to render the mesh
  108140. * @param emissiveTexture the associated emissive texture used to generate the glow
  108141. * @return true if ready otherwise, false
  108142. */
  108143. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  108144. var material = subMesh.getMaterial();
  108145. var mesh = subMesh.getRenderingMesh();
  108146. if (!material || !mesh || !this._meshes) {
  108147. return false;
  108148. }
  108149. var emissiveTexture = null;
  108150. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  108151. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  108152. emissiveTexture = material.emissiveTexture;
  108153. }
  108154. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  108155. };
  108156. /**
  108157. * Implementation specific of rendering the generating effect on the main canvas.
  108158. * @param effect The effect used to render through
  108159. */
  108160. HighlightLayer.prototype._internalRender = function (effect) {
  108161. // Texture
  108162. effect.setTexture("textureSampler", this._blurTexture);
  108163. // Cache
  108164. var engine = this._engine;
  108165. var previousStencilBuffer = engine.getStencilBuffer();
  108166. var previousStencilFunction = engine.getStencilFunction();
  108167. var previousStencilMask = engine.getStencilMask();
  108168. var previousStencilOperationPass = engine.getStencilOperationPass();
  108169. var previousStencilOperationFail = engine.getStencilOperationFail();
  108170. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  108171. var previousStencilReference = engine.getStencilFunctionReference();
  108172. // Stencil operations
  108173. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  108174. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  108175. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  108176. // Draw order
  108177. engine.setStencilMask(0x00);
  108178. engine.setStencilBuffer(true);
  108179. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  108180. // 2 passes inner outer
  108181. if (this.outerGlow) {
  108182. effect.setFloat("offset", 0);
  108183. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  108184. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108185. }
  108186. if (this.innerGlow) {
  108187. effect.setFloat("offset", 1);
  108188. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  108189. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108190. }
  108191. // Restore Cache
  108192. engine.setStencilFunction(previousStencilFunction);
  108193. engine.setStencilMask(previousStencilMask);
  108194. engine.setStencilBuffer(previousStencilBuffer);
  108195. engine.setStencilOperationPass(previousStencilOperationPass);
  108196. engine.setStencilOperationFail(previousStencilOperationFail);
  108197. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  108198. engine.setStencilFunctionReference(previousStencilReference);
  108199. };
  108200. /**
  108201. * Returns true if the layer contains information to display, otherwise false.
  108202. */
  108203. HighlightLayer.prototype.shouldRender = function () {
  108204. if (_super.prototype.shouldRender.call(this)) {
  108205. return this._meshes ? true : false;
  108206. }
  108207. return false;
  108208. };
  108209. /**
  108210. * Returns true if the mesh should render, otherwise false.
  108211. * @param mesh The mesh to render
  108212. * @returns true if it should render otherwise false
  108213. */
  108214. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  108215. // Excluded Mesh
  108216. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  108217. return false;
  108218. }
  108219. ;
  108220. if (!_super.prototype.hasMesh.call(this, mesh)) {
  108221. return false;
  108222. }
  108223. return true;
  108224. };
  108225. /**
  108226. * Sets the required values for both the emissive texture and and the main color.
  108227. */
  108228. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  108229. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  108230. if (highlightLayerMesh) {
  108231. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  108232. }
  108233. else {
  108234. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  108235. }
  108236. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  108237. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  108238. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  108239. }
  108240. else {
  108241. this._emissiveTextureAndColor.texture = null;
  108242. }
  108243. };
  108244. /**
  108245. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  108246. * @param mesh The mesh to exclude from the highlight layer
  108247. */
  108248. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  108249. if (!this._excludedMeshes) {
  108250. return;
  108251. }
  108252. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  108253. if (!meshExcluded) {
  108254. this._excludedMeshes[mesh.uniqueId] = {
  108255. mesh: mesh,
  108256. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  108257. mesh.getEngine().setStencilBuffer(false);
  108258. }),
  108259. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  108260. mesh.getEngine().setStencilBuffer(true);
  108261. }),
  108262. };
  108263. }
  108264. };
  108265. /**
  108266. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  108267. * @param mesh The mesh to highlight
  108268. */
  108269. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  108270. if (!this._excludedMeshes) {
  108271. return;
  108272. }
  108273. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  108274. if (meshExcluded) {
  108275. if (meshExcluded.beforeRender) {
  108276. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  108277. }
  108278. if (meshExcluded.afterRender) {
  108279. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  108280. }
  108281. }
  108282. this._excludedMeshes[mesh.uniqueId] = null;
  108283. };
  108284. /**
  108285. * Determine if a given mesh will be highlighted by the current HighlightLayer
  108286. * @param mesh mesh to test
  108287. * @returns true if the mesh will be highlighted by the current HighlightLayer
  108288. */
  108289. HighlightLayer.prototype.hasMesh = function (mesh) {
  108290. if (!this._meshes) {
  108291. return false;
  108292. }
  108293. if (!_super.prototype.hasMesh.call(this, mesh)) {
  108294. return false;
  108295. }
  108296. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  108297. };
  108298. /**
  108299. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  108300. * @param mesh The mesh to highlight
  108301. * @param color The color of the highlight
  108302. * @param glowEmissiveOnly Extract the glow from the emissive texture
  108303. */
  108304. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  108305. var _this = this;
  108306. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  108307. if (!this._meshes) {
  108308. return;
  108309. }
  108310. var meshHighlight = this._meshes[mesh.uniqueId];
  108311. if (meshHighlight) {
  108312. meshHighlight.color = color;
  108313. }
  108314. else {
  108315. this._meshes[mesh.uniqueId] = {
  108316. mesh: mesh,
  108317. color: color,
  108318. // Lambda required for capture due to Observable this context
  108319. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  108320. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  108321. _this._defaultStencilReference(mesh);
  108322. }
  108323. else {
  108324. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  108325. }
  108326. }),
  108327. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  108328. glowEmissiveOnly: glowEmissiveOnly
  108329. };
  108330. mesh.onDisposeObservable.add(function () {
  108331. _this._disposeMesh(mesh);
  108332. });
  108333. }
  108334. this._shouldRender = true;
  108335. };
  108336. /**
  108337. * Remove a mesh from the highlight layer in order to make it stop glowing.
  108338. * @param mesh The mesh to highlight
  108339. */
  108340. HighlightLayer.prototype.removeMesh = function (mesh) {
  108341. if (!this._meshes) {
  108342. return;
  108343. }
  108344. var meshHighlight = this._meshes[mesh.uniqueId];
  108345. if (meshHighlight) {
  108346. if (meshHighlight.observerHighlight) {
  108347. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  108348. }
  108349. if (meshHighlight.observerDefault) {
  108350. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  108351. }
  108352. delete this._meshes[mesh.uniqueId];
  108353. }
  108354. this._shouldRender = false;
  108355. for (var meshHighlightToCheck in this._meshes) {
  108356. if (this._meshes[meshHighlightToCheck]) {
  108357. this._shouldRender = true;
  108358. break;
  108359. }
  108360. }
  108361. };
  108362. /**
  108363. * Force the stencil to the normal expected value for none glowing parts
  108364. */
  108365. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  108366. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  108367. };
  108368. /**
  108369. * Free any resources and references associated to a mesh.
  108370. * Internal use
  108371. * @param mesh The mesh to free.
  108372. * @hidden
  108373. */
  108374. HighlightLayer.prototype._disposeMesh = function (mesh) {
  108375. this.removeMesh(mesh);
  108376. this.removeExcludedMesh(mesh);
  108377. };
  108378. /**
  108379. * Dispose the highlight layer and free resources.
  108380. */
  108381. HighlightLayer.prototype.dispose = function () {
  108382. if (this._meshes) {
  108383. // Clean mesh references
  108384. for (var id in this._meshes) {
  108385. var meshHighlight = this._meshes[id];
  108386. if (meshHighlight && meshHighlight.mesh) {
  108387. if (meshHighlight.observerHighlight) {
  108388. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  108389. }
  108390. if (meshHighlight.observerDefault) {
  108391. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  108392. }
  108393. }
  108394. }
  108395. this._meshes = null;
  108396. }
  108397. if (this._excludedMeshes) {
  108398. for (var id in this._excludedMeshes) {
  108399. var meshHighlight = this._excludedMeshes[id];
  108400. if (meshHighlight) {
  108401. if (meshHighlight.beforeRender) {
  108402. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  108403. }
  108404. if (meshHighlight.afterRender) {
  108405. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  108406. }
  108407. }
  108408. }
  108409. this._excludedMeshes = null;
  108410. }
  108411. _super.prototype.dispose.call(this);
  108412. };
  108413. /**
  108414. * Gets the class name of the effect layer
  108415. * @returns the string with the class name of the effect layer
  108416. */
  108417. HighlightLayer.prototype.getClassName = function () {
  108418. return "HighlightLayer";
  108419. };
  108420. /**
  108421. * Serializes this Highlight layer
  108422. * @returns a serialized Highlight layer object
  108423. */
  108424. HighlightLayer.prototype.serialize = function () {
  108425. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  108426. serializationObject.customType = "BABYLON.HighlightLayer";
  108427. // Highlighted meshes
  108428. serializationObject.meshes = [];
  108429. if (this._meshes) {
  108430. for (var m in this._meshes) {
  108431. var mesh = this._meshes[m];
  108432. if (mesh) {
  108433. serializationObject.meshes.push({
  108434. glowEmissiveOnly: mesh.glowEmissiveOnly,
  108435. color: mesh.color.asArray(),
  108436. meshId: mesh.mesh.id
  108437. });
  108438. }
  108439. }
  108440. }
  108441. // Excluded meshes
  108442. serializationObject.excludedMeshes = [];
  108443. if (this._excludedMeshes) {
  108444. for (var e in this._excludedMeshes) {
  108445. var excludedMesh = this._excludedMeshes[e];
  108446. if (excludedMesh) {
  108447. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  108448. }
  108449. }
  108450. }
  108451. return serializationObject;
  108452. };
  108453. /**
  108454. * Creates a Highlight layer from parsed Highlight layer data
  108455. * @param parsedHightlightLayer defines the Highlight layer data
  108456. * @param scene defines the current scene
  108457. * @param rootUrl defines the root URL containing the Highlight layer information
  108458. * @returns a parsed Highlight layer
  108459. */
  108460. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  108461. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  108462. var index;
  108463. // Excluded meshes
  108464. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  108465. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  108466. if (mesh) {
  108467. hl.addExcludedMesh(mesh);
  108468. }
  108469. }
  108470. // Included meshes
  108471. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  108472. var highlightedMesh = parsedHightlightLayer.meshes[index];
  108473. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  108474. if (mesh) {
  108475. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  108476. }
  108477. }
  108478. return hl;
  108479. };
  108480. /**
  108481. * Effect Name of the highlight layer.
  108482. */
  108483. HighlightLayer.EffectName = "HighlightLayer";
  108484. /**
  108485. * The neutral color used during the preparation of the glow effect.
  108486. * This is black by default as the blend operation is a blend operation.
  108487. */
  108488. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  108489. /**
  108490. * Stencil value used for glowing meshes.
  108491. */
  108492. HighlightLayer.GlowingMeshStencilReference = 0x02;
  108493. /**
  108494. * Stencil value used for the other meshes in the scene.
  108495. */
  108496. HighlightLayer.NormalMeshStencilReference = 0x01;
  108497. __decorate([
  108498. BABYLON.serialize()
  108499. ], HighlightLayer.prototype, "innerGlow", void 0);
  108500. __decorate([
  108501. BABYLON.serialize()
  108502. ], HighlightLayer.prototype, "outerGlow", void 0);
  108503. __decorate([
  108504. BABYLON.serialize()
  108505. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  108506. __decorate([
  108507. BABYLON.serialize()
  108508. ], HighlightLayer.prototype, "blurVerticalSize", null);
  108509. __decorate([
  108510. BABYLON.serialize("options")
  108511. ], HighlightLayer.prototype, "_options", void 0);
  108512. return HighlightLayer;
  108513. }(BABYLON.EffectLayer));
  108514. BABYLON.HighlightLayer = HighlightLayer;
  108515. })(BABYLON || (BABYLON = {}));
  108516. //# sourceMappingURL=babylon.highlightLayer.js.map
  108517. var BABYLON;
  108518. (function (BABYLON) {
  108519. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  108520. for (var index = 0; index < this.effectLayers.length; index++) {
  108521. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  108522. return this.effectLayers[index];
  108523. }
  108524. }
  108525. return null;
  108526. };
  108527. /**
  108528. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  108529. *
  108530. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  108531. * glowy meshes to your scene.
  108532. *
  108533. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  108534. */
  108535. var GlowLayer = /** @class */ (function (_super) {
  108536. __extends(GlowLayer, _super);
  108537. /**
  108538. * Instantiates a new glow Layer and references it to the scene.
  108539. * @param name The name of the layer
  108540. * @param scene The scene to use the layer in
  108541. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  108542. */
  108543. function GlowLayer(name, scene, options) {
  108544. var _this = _super.call(this, name, scene) || this;
  108545. _this._intensity = 1.0;
  108546. _this._includedOnlyMeshes = [];
  108547. _this._excludedMeshes = [];
  108548. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  108549. // Adapt options
  108550. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  108551. // Initialize the layer
  108552. _this._init({
  108553. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  108554. camera: _this._options.camera,
  108555. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  108556. mainTextureRatio: _this._options.mainTextureRatio,
  108557. renderingGroupId: _this._options.renderingGroupId
  108558. });
  108559. return _this;
  108560. }
  108561. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  108562. /**
  108563. * Gets the kernel size of the blur.
  108564. */
  108565. get: function () {
  108566. return this._horizontalBlurPostprocess1.kernel;
  108567. },
  108568. /**
  108569. * Sets the kernel size of the blur.
  108570. */
  108571. set: function (value) {
  108572. this._horizontalBlurPostprocess1.kernel = value;
  108573. this._verticalBlurPostprocess1.kernel = value;
  108574. this._horizontalBlurPostprocess2.kernel = value;
  108575. this._verticalBlurPostprocess2.kernel = value;
  108576. },
  108577. enumerable: true,
  108578. configurable: true
  108579. });
  108580. Object.defineProperty(GlowLayer.prototype, "intensity", {
  108581. /**
  108582. * Gets the glow intensity.
  108583. */
  108584. get: function () {
  108585. return this._intensity;
  108586. },
  108587. /**
  108588. * Sets the glow intensity.
  108589. */
  108590. set: function (value) {
  108591. this._intensity = value;
  108592. },
  108593. enumerable: true,
  108594. configurable: true
  108595. });
  108596. /**
  108597. * Get the effect name of the layer.
  108598. * @return The effect name
  108599. */
  108600. GlowLayer.prototype.getEffectName = function () {
  108601. return GlowLayer.EffectName;
  108602. };
  108603. /**
  108604. * Create the merge effect. This is the shader use to blit the information back
  108605. * to the main canvas at the end of the scene rendering.
  108606. */
  108607. GlowLayer.prototype._createMergeEffect = function () {
  108608. // Effect
  108609. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  108610. };
  108611. /**
  108612. * Creates the render target textures and post processes used in the glow layer.
  108613. */
  108614. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  108615. var _this = this;
  108616. var blurTextureWidth = this._mainTextureDesiredSize.width;
  108617. var blurTextureHeight = this._mainTextureDesiredSize.height;
  108618. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  108619. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  108620. var textureType = 0;
  108621. if (this._engine.getCaps().textureHalfFloatRender) {
  108622. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  108623. }
  108624. else {
  108625. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  108626. }
  108627. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  108628. width: blurTextureWidth,
  108629. height: blurTextureHeight
  108630. }, this._scene, false, true, textureType);
  108631. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108632. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108633. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  108634. this._blurTexture1.renderParticles = false;
  108635. this._blurTexture1.ignoreCameraViewport = true;
  108636. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  108637. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  108638. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  108639. width: blurTextureWidth2,
  108640. height: blurTextureHeight2
  108641. }, this._scene, false, true, textureType);
  108642. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108643. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108644. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  108645. this._blurTexture2.renderParticles = false;
  108646. this._blurTexture2.ignoreCameraViewport = true;
  108647. this._textures = [this._blurTexture1, this._blurTexture2];
  108648. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  108649. width: blurTextureWidth,
  108650. height: blurTextureHeight
  108651. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108652. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  108653. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  108654. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  108655. effect.setTexture("textureSampler", _this._mainTexture);
  108656. });
  108657. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  108658. width: blurTextureWidth,
  108659. height: blurTextureHeight
  108660. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108661. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  108662. width: blurTextureWidth2,
  108663. height: blurTextureHeight2
  108664. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108665. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  108666. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  108667. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  108668. effect.setTexture("textureSampler", _this._blurTexture1);
  108669. });
  108670. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  108671. width: blurTextureWidth2,
  108672. height: blurTextureHeight2
  108673. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  108674. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  108675. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  108676. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  108677. this._mainTexture.samples = this._options.mainTextureSamples;
  108678. this._mainTexture.onAfterUnbindObservable.add(function () {
  108679. var internalTexture = _this._blurTexture1.getInternalTexture();
  108680. if (internalTexture) {
  108681. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  108682. internalTexture = _this._blurTexture2.getInternalTexture();
  108683. if (internalTexture) {
  108684. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  108685. }
  108686. }
  108687. });
  108688. // Prevent autoClear.
  108689. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  108690. };
  108691. /**
  108692. * Checks for the readiness of the element composing the layer.
  108693. * @param subMesh the mesh to check for
  108694. * @param useInstances specify wether or not to use instances to render the mesh
  108695. * @param emissiveTexture the associated emissive texture used to generate the glow
  108696. * @return true if ready otherwise, false
  108697. */
  108698. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  108699. var material = subMesh.getMaterial();
  108700. var mesh = subMesh.getRenderingMesh();
  108701. if (!material || !mesh) {
  108702. return false;
  108703. }
  108704. var emissiveTexture = material.emissiveTexture;
  108705. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  108706. };
  108707. /**
  108708. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  108709. */
  108710. GlowLayer.prototype.needStencil = function () {
  108711. return false;
  108712. };
  108713. /**
  108714. * Implementation specific of rendering the generating effect on the main canvas.
  108715. * @param effect The effect used to render through
  108716. */
  108717. GlowLayer.prototype._internalRender = function (effect) {
  108718. // Texture
  108719. effect.setTexture("textureSampler", this._blurTexture1);
  108720. effect.setTexture("textureSampler2", this._blurTexture2);
  108721. effect.setFloat("offset", this._intensity);
  108722. // Cache
  108723. var engine = this._engine;
  108724. var previousStencilBuffer = engine.getStencilBuffer();
  108725. // Draw order
  108726. engine.setStencilBuffer(false);
  108727. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  108728. // Draw order
  108729. engine.setStencilBuffer(previousStencilBuffer);
  108730. };
  108731. /**
  108732. * Sets the required values for both the emissive texture and and the main color.
  108733. */
  108734. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  108735. var textureLevel = 1.0;
  108736. if (this.customEmissiveTextureSelector) {
  108737. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  108738. }
  108739. else {
  108740. if (material) {
  108741. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  108742. if (this._emissiveTextureAndColor.texture) {
  108743. textureLevel = this._emissiveTextureAndColor.texture.level;
  108744. }
  108745. }
  108746. else {
  108747. this._emissiveTextureAndColor.texture = null;
  108748. }
  108749. }
  108750. if (this.customEmissiveColorSelector) {
  108751. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  108752. }
  108753. else {
  108754. if (material.emissiveColor) {
  108755. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  108756. }
  108757. else {
  108758. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  108759. }
  108760. }
  108761. };
  108762. /**
  108763. * Returns true if the mesh should render, otherwise false.
  108764. * @param mesh The mesh to render
  108765. * @returns true if it should render otherwise false
  108766. */
  108767. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  108768. return this.hasMesh(mesh);
  108769. };
  108770. /**
  108771. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  108772. * @param mesh The mesh to exclude from the glow layer
  108773. */
  108774. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  108775. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  108776. this._excludedMeshes.push(mesh.uniqueId);
  108777. }
  108778. };
  108779. /**
  108780. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  108781. * @param mesh The mesh to remove
  108782. */
  108783. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  108784. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  108785. if (index !== -1) {
  108786. this._excludedMeshes.splice(index, 1);
  108787. }
  108788. };
  108789. /**
  108790. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  108791. * @param mesh The mesh to include in the glow layer
  108792. */
  108793. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  108794. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  108795. this._includedOnlyMeshes.push(mesh.uniqueId);
  108796. }
  108797. };
  108798. /**
  108799. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  108800. * @param mesh The mesh to remove
  108801. */
  108802. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  108803. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  108804. if (index !== -1) {
  108805. this._includedOnlyMeshes.splice(index, 1);
  108806. }
  108807. };
  108808. /**
  108809. * Determine if a given mesh will be used in the glow layer
  108810. * @param mesh The mesh to test
  108811. * @returns true if the mesh will be highlighted by the current glow layer
  108812. */
  108813. GlowLayer.prototype.hasMesh = function (mesh) {
  108814. if (!_super.prototype.hasMesh.call(this, mesh)) {
  108815. return false;
  108816. }
  108817. // Included Mesh
  108818. if (this._includedOnlyMeshes.length) {
  108819. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  108820. }
  108821. ;
  108822. // Excluded Mesh
  108823. if (this._excludedMeshes.length) {
  108824. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  108825. }
  108826. ;
  108827. return true;
  108828. };
  108829. /**
  108830. * Free any resources and references associated to a mesh.
  108831. * Internal use
  108832. * @param mesh The mesh to free.
  108833. * @hidden
  108834. */
  108835. GlowLayer.prototype._disposeMesh = function (mesh) {
  108836. this.removeIncludedOnlyMesh(mesh);
  108837. this.removeExcludedMesh(mesh);
  108838. };
  108839. /**
  108840. * Gets the class name of the effect layer
  108841. * @returns the string with the class name of the effect layer
  108842. */
  108843. GlowLayer.prototype.getClassName = function () {
  108844. return "GlowLayer";
  108845. };
  108846. /**
  108847. * Serializes this glow layer
  108848. * @returns a serialized glow layer object
  108849. */
  108850. GlowLayer.prototype.serialize = function () {
  108851. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  108852. serializationObject.customType = "BABYLON.GlowLayer";
  108853. var index;
  108854. // Included meshes
  108855. serializationObject.includedMeshes = [];
  108856. if (this._includedOnlyMeshes.length) {
  108857. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  108858. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  108859. if (mesh) {
  108860. serializationObject.includedMeshes.push(mesh.id);
  108861. }
  108862. }
  108863. }
  108864. // Excluded meshes
  108865. serializationObject.excludedMeshes = [];
  108866. if (this._excludedMeshes.length) {
  108867. for (index = 0; index < this._excludedMeshes.length; index++) {
  108868. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  108869. if (mesh) {
  108870. serializationObject.excludedMeshes.push(mesh.id);
  108871. }
  108872. }
  108873. }
  108874. return serializationObject;
  108875. };
  108876. /**
  108877. * Creates a Glow Layer from parsed glow layer data
  108878. * @param parsedGlowLayer defines glow layer data
  108879. * @param scene defines the current scene
  108880. * @param rootUrl defines the root URL containing the glow layer information
  108881. * @returns a parsed Glow Layer
  108882. */
  108883. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  108884. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  108885. var index;
  108886. // Excluded meshes
  108887. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  108888. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  108889. if (mesh) {
  108890. gl.addExcludedMesh(mesh);
  108891. }
  108892. }
  108893. // Included meshes
  108894. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  108895. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  108896. if (mesh) {
  108897. gl.addIncludedOnlyMesh(mesh);
  108898. }
  108899. }
  108900. return gl;
  108901. };
  108902. /**
  108903. * Effect Name of the layer.
  108904. */
  108905. GlowLayer.EffectName = "GlowLayer";
  108906. /**
  108907. * The default blur kernel size used for the glow.
  108908. */
  108909. GlowLayer.DefaultBlurKernelSize = 32;
  108910. /**
  108911. * The default texture size ratio used for the glow.
  108912. */
  108913. GlowLayer.DefaultTextureRatio = 0.5;
  108914. __decorate([
  108915. BABYLON.serialize()
  108916. ], GlowLayer.prototype, "blurKernelSize", null);
  108917. __decorate([
  108918. BABYLON.serialize()
  108919. ], GlowLayer.prototype, "intensity", null);
  108920. __decorate([
  108921. BABYLON.serialize("options")
  108922. ], GlowLayer.prototype, "_options", void 0);
  108923. return GlowLayer;
  108924. }(BABYLON.EffectLayer));
  108925. BABYLON.GlowLayer = GlowLayer;
  108926. })(BABYLON || (BABYLON = {}));
  108927. //# sourceMappingURL=babylon.glowLayer.js.map
  108928. var BABYLON;
  108929. (function (BABYLON) {
  108930. /**
  108931. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  108932. */
  108933. var AssetTaskState;
  108934. (function (AssetTaskState) {
  108935. /**
  108936. * Initialization
  108937. */
  108938. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  108939. /**
  108940. * Running
  108941. */
  108942. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  108943. /**
  108944. * Done
  108945. */
  108946. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  108947. /**
  108948. * Error
  108949. */
  108950. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  108951. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  108952. /**
  108953. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  108954. */
  108955. var AbstractAssetTask = /** @class */ (function () {
  108956. /**
  108957. * Creates a new {BABYLON.AssetsManager}
  108958. * @param name defines the name of the task
  108959. */
  108960. function AbstractAssetTask(
  108961. /**
  108962. * Task name
  108963. */ name) {
  108964. this.name = name;
  108965. this._isCompleted = false;
  108966. this._taskState = AssetTaskState.INIT;
  108967. }
  108968. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  108969. /**
  108970. * Get if the task is completed
  108971. */
  108972. get: function () {
  108973. return this._isCompleted;
  108974. },
  108975. enumerable: true,
  108976. configurable: true
  108977. });
  108978. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  108979. /**
  108980. * Gets the current state of the task
  108981. */
  108982. get: function () {
  108983. return this._taskState;
  108984. },
  108985. enumerable: true,
  108986. configurable: true
  108987. });
  108988. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  108989. /**
  108990. * Gets the current error object (if task is in error)
  108991. */
  108992. get: function () {
  108993. return this._errorObject;
  108994. },
  108995. enumerable: true,
  108996. configurable: true
  108997. });
  108998. /**
  108999. * Internal only
  109000. * @hidden
  109001. */
  109002. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  109003. if (this._errorObject) {
  109004. return;
  109005. }
  109006. this._errorObject = {
  109007. message: message,
  109008. exception: exception
  109009. };
  109010. };
  109011. /**
  109012. * Execute the current task
  109013. * @param scene defines the scene where you want your assets to be loaded
  109014. * @param onSuccess is a callback called when the task is successfully executed
  109015. * @param onError is a callback called if an error occurs
  109016. */
  109017. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  109018. var _this = this;
  109019. this._taskState = AssetTaskState.RUNNING;
  109020. this.runTask(scene, function () {
  109021. _this.onDoneCallback(onSuccess, onError);
  109022. }, function (msg, exception) {
  109023. _this.onErrorCallback(onError, msg, exception);
  109024. });
  109025. };
  109026. /**
  109027. * Execute the current task
  109028. * @param scene defines the scene where you want your assets to be loaded
  109029. * @param onSuccess is a callback called when the task is successfully executed
  109030. * @param onError is a callback called if an error occurs
  109031. */
  109032. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109033. throw new Error("runTask is not implemented");
  109034. };
  109035. /**
  109036. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  109037. * This can be used with failed tasks that have the reason for failure fixed.
  109038. */
  109039. AbstractAssetTask.prototype.reset = function () {
  109040. this._taskState = AssetTaskState.INIT;
  109041. };
  109042. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  109043. this._taskState = AssetTaskState.ERROR;
  109044. this._errorObject = {
  109045. message: message,
  109046. exception: exception
  109047. };
  109048. if (this.onError) {
  109049. this.onError(this, message, exception);
  109050. }
  109051. onError();
  109052. };
  109053. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  109054. try {
  109055. this._taskState = AssetTaskState.DONE;
  109056. this._isCompleted = true;
  109057. if (this.onSuccess) {
  109058. this.onSuccess(this);
  109059. }
  109060. onSuccess();
  109061. }
  109062. catch (e) {
  109063. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  109064. }
  109065. };
  109066. return AbstractAssetTask;
  109067. }());
  109068. BABYLON.AbstractAssetTask = AbstractAssetTask;
  109069. /**
  109070. * Class used to share progress information about assets loading
  109071. */
  109072. var AssetsProgressEvent = /** @class */ (function () {
  109073. /**
  109074. * Creates a {BABYLON.AssetsProgressEvent}
  109075. * @param remainingCount defines the number of remaining tasks to process
  109076. * @param totalCount defines the total number of tasks
  109077. * @param task defines the task that was just processed
  109078. */
  109079. function AssetsProgressEvent(remainingCount, totalCount, task) {
  109080. this.remainingCount = remainingCount;
  109081. this.totalCount = totalCount;
  109082. this.task = task;
  109083. }
  109084. return AssetsProgressEvent;
  109085. }());
  109086. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  109087. /**
  109088. * Define a task used by {BABYLON.AssetsManager} to load meshes
  109089. */
  109090. var MeshAssetTask = /** @class */ (function (_super) {
  109091. __extends(MeshAssetTask, _super);
  109092. /**
  109093. * Creates a new {BABYLON.MeshAssetTask}
  109094. * @param name defines the name of the task
  109095. * @param meshesNames defines the list of mesh's names you want to load
  109096. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  109097. * @param sceneFilename defines the filename of the scene to load from
  109098. */
  109099. function MeshAssetTask(
  109100. /**
  109101. * Defines the name of the task
  109102. */
  109103. name,
  109104. /**
  109105. * Defines the list of mesh's names you want to load
  109106. */
  109107. meshesNames,
  109108. /**
  109109. * Defines the root url to use as a base to load your meshes and associated resources
  109110. */
  109111. rootUrl,
  109112. /**
  109113. * Defines the filename of the scene to load from
  109114. */
  109115. sceneFilename) {
  109116. var _this = _super.call(this, name) || this;
  109117. _this.name = name;
  109118. _this.meshesNames = meshesNames;
  109119. _this.rootUrl = rootUrl;
  109120. _this.sceneFilename = sceneFilename;
  109121. return _this;
  109122. }
  109123. /**
  109124. * Execute the current task
  109125. * @param scene defines the scene where you want your assets to be loaded
  109126. * @param onSuccess is a callback called when the task is successfully executed
  109127. * @param onError is a callback called if an error occurs
  109128. */
  109129. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109130. var _this = this;
  109131. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  109132. _this.loadedMeshes = meshes;
  109133. _this.loadedParticleSystems = particleSystems;
  109134. _this.loadedSkeletons = skeletons;
  109135. onSuccess();
  109136. }, null, function (scene, message, exception) {
  109137. onError(message, exception);
  109138. });
  109139. };
  109140. return MeshAssetTask;
  109141. }(AbstractAssetTask));
  109142. BABYLON.MeshAssetTask = MeshAssetTask;
  109143. /**
  109144. * Define a task used by {BABYLON.AssetsManager} to load text content
  109145. */
  109146. var TextFileAssetTask = /** @class */ (function (_super) {
  109147. __extends(TextFileAssetTask, _super);
  109148. /**
  109149. * Creates a new TextFileAssetTask object
  109150. * @param name defines the name of the task
  109151. * @param url defines the location of the file to load
  109152. */
  109153. function TextFileAssetTask(
  109154. /**
  109155. * Defines the name of the task
  109156. */
  109157. name,
  109158. /**
  109159. * Defines the location of the file to load
  109160. */
  109161. url) {
  109162. var _this = _super.call(this, name) || this;
  109163. _this.name = name;
  109164. _this.url = url;
  109165. return _this;
  109166. }
  109167. /**
  109168. * Execute the current task
  109169. * @param scene defines the scene where you want your assets to be loaded
  109170. * @param onSuccess is a callback called when the task is successfully executed
  109171. * @param onError is a callback called if an error occurs
  109172. */
  109173. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109174. var _this = this;
  109175. scene._loadFile(this.url, function (data) {
  109176. _this.text = data;
  109177. onSuccess();
  109178. }, undefined, false, false, function (request, exception) {
  109179. if (request) {
  109180. onError(request.status + " " + request.statusText, exception);
  109181. }
  109182. });
  109183. };
  109184. return TextFileAssetTask;
  109185. }(AbstractAssetTask));
  109186. BABYLON.TextFileAssetTask = TextFileAssetTask;
  109187. /**
  109188. * Define a task used by {BABYLON.AssetsManager} to load binary data
  109189. */
  109190. var BinaryFileAssetTask = /** @class */ (function (_super) {
  109191. __extends(BinaryFileAssetTask, _super);
  109192. /**
  109193. * Creates a new BinaryFileAssetTask object
  109194. * @param name defines the name of the new task
  109195. * @param url defines the location of the file to load
  109196. */
  109197. function BinaryFileAssetTask(
  109198. /**
  109199. * Defines the name of the task
  109200. */
  109201. name,
  109202. /**
  109203. * Defines the location of the file to load
  109204. */
  109205. url) {
  109206. var _this = _super.call(this, name) || this;
  109207. _this.name = name;
  109208. _this.url = url;
  109209. return _this;
  109210. }
  109211. /**
  109212. * Execute the current task
  109213. * @param scene defines the scene where you want your assets to be loaded
  109214. * @param onSuccess is a callback called when the task is successfully executed
  109215. * @param onError is a callback called if an error occurs
  109216. */
  109217. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109218. var _this = this;
  109219. scene._loadFile(this.url, function (data) {
  109220. _this.data = data;
  109221. onSuccess();
  109222. }, undefined, true, true, function (request, exception) {
  109223. if (request) {
  109224. onError(request.status + " " + request.statusText, exception);
  109225. }
  109226. });
  109227. };
  109228. return BinaryFileAssetTask;
  109229. }(AbstractAssetTask));
  109230. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  109231. /**
  109232. * Define a task used by {BABYLON.AssetsManager} to load images
  109233. */
  109234. var ImageAssetTask = /** @class */ (function (_super) {
  109235. __extends(ImageAssetTask, _super);
  109236. /**
  109237. * Creates a new ImageAssetTask
  109238. * @param name defines the name of the task
  109239. * @param url defines the location of the image to load
  109240. */
  109241. function ImageAssetTask(
  109242. /**
  109243. * Defines the name of the task
  109244. */
  109245. name,
  109246. /**
  109247. * Defines the location of the image to load
  109248. */
  109249. url) {
  109250. var _this = _super.call(this, name) || this;
  109251. _this.name = name;
  109252. _this.url = url;
  109253. return _this;
  109254. }
  109255. /**
  109256. * Execute the current task
  109257. * @param scene defines the scene where you want your assets to be loaded
  109258. * @param onSuccess is a callback called when the task is successfully executed
  109259. * @param onError is a callback called if an error occurs
  109260. */
  109261. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109262. var _this = this;
  109263. var img = new Image();
  109264. BABYLON.Tools.SetCorsBehavior(this.url, img);
  109265. img.onload = function () {
  109266. _this.image = img;
  109267. onSuccess();
  109268. };
  109269. img.onerror = function (err) {
  109270. onError("Error loading image", err);
  109271. };
  109272. img.src = this.url;
  109273. };
  109274. return ImageAssetTask;
  109275. }(AbstractAssetTask));
  109276. BABYLON.ImageAssetTask = ImageAssetTask;
  109277. /**
  109278. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  109279. */
  109280. var TextureAssetTask = /** @class */ (function (_super) {
  109281. __extends(TextureAssetTask, _super);
  109282. /**
  109283. * Creates a new TextureAssetTask object
  109284. * @param name defines the name of the task
  109285. * @param url defines the location of the file to load
  109286. * @param noMipmap defines if mipmap should not be generated (default is false)
  109287. * @param invertY defines if texture must be inverted on Y axis (default is false)
  109288. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  109289. */
  109290. function TextureAssetTask(
  109291. /**
  109292. * Defines the name of the task
  109293. */
  109294. name,
  109295. /**
  109296. * Defines the location of the file to load
  109297. */
  109298. url,
  109299. /**
  109300. * Defines if mipmap should not be generated (default is false)
  109301. */
  109302. noMipmap,
  109303. /**
  109304. * Defines if texture must be inverted on Y axis (default is false)
  109305. */
  109306. invertY,
  109307. /**
  109308. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  109309. */
  109310. samplingMode) {
  109311. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  109312. var _this = _super.call(this, name) || this;
  109313. _this.name = name;
  109314. _this.url = url;
  109315. _this.noMipmap = noMipmap;
  109316. _this.invertY = invertY;
  109317. _this.samplingMode = samplingMode;
  109318. return _this;
  109319. }
  109320. /**
  109321. * Execute the current task
  109322. * @param scene defines the scene where you want your assets to be loaded
  109323. * @param onSuccess is a callback called when the task is successfully executed
  109324. * @param onError is a callback called if an error occurs
  109325. */
  109326. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109327. var onload = function () {
  109328. onSuccess();
  109329. };
  109330. var onerror = function (message, exception) {
  109331. onError(message, exception);
  109332. };
  109333. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  109334. };
  109335. return TextureAssetTask;
  109336. }(AbstractAssetTask));
  109337. BABYLON.TextureAssetTask = TextureAssetTask;
  109338. /**
  109339. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  109340. */
  109341. var CubeTextureAssetTask = /** @class */ (function (_super) {
  109342. __extends(CubeTextureAssetTask, _super);
  109343. /**
  109344. * Creates a new CubeTextureAssetTask
  109345. * @param name defines the name of the task
  109346. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  109347. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  109348. * @param noMipmap defines if mipmaps should not be generated (default is false)
  109349. * @param files defines the explicit list of files (undefined by default)
  109350. */
  109351. function CubeTextureAssetTask(
  109352. /**
  109353. * Defines the name of the task
  109354. */
  109355. name,
  109356. /**
  109357. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  109358. */
  109359. url,
  109360. /**
  109361. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  109362. */
  109363. extensions,
  109364. /**
  109365. * Defines if mipmaps should not be generated (default is false)
  109366. */
  109367. noMipmap,
  109368. /**
  109369. * Defines the explicit list of files (undefined by default)
  109370. */
  109371. files) {
  109372. var _this = _super.call(this, name) || this;
  109373. _this.name = name;
  109374. _this.url = url;
  109375. _this.extensions = extensions;
  109376. _this.noMipmap = noMipmap;
  109377. _this.files = files;
  109378. return _this;
  109379. }
  109380. /**
  109381. * Execute the current task
  109382. * @param scene defines the scene where you want your assets to be loaded
  109383. * @param onSuccess is a callback called when the task is successfully executed
  109384. * @param onError is a callback called if an error occurs
  109385. */
  109386. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  109387. var onload = function () {
  109388. onSuccess();
  109389. };
  109390. var onerror = function (message, exception) {
  109391. onError(message, exception);
  109392. };
  109393. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  109394. };
  109395. return CubeTextureAssetTask;
  109396. }(AbstractAssetTask));
  109397. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  109398. /**
  109399. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  109400. */
  109401. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  109402. __extends(HDRCubeTextureAssetTask, _super);
  109403. /**
  109404. * Creates a new HDRCubeTextureAssetTask object
  109405. * @param name defines the name of the task
  109406. * @param url defines the location of the file to load
  109407. * @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.
  109408. * @param noMipmap defines if mipmaps should not be generated (default is false)
  109409. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  109410. * @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)
  109411. * @param reserved Internal use only
  109412. */
  109413. function HDRCubeTextureAssetTask(
  109414. /**
  109415. * Defines the name of the task
  109416. */
  109417. name,
  109418. /**
  109419. * Defines the location of the file to load
  109420. */
  109421. url,
  109422. /**
  109423. * Defines the desired size (the more it increases the longer the generation will be)
  109424. */
  109425. size,
  109426. /**
  109427. * Defines if mipmaps should not be generated (default is false)
  109428. */
  109429. noMipmap,
  109430. /**
  109431. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  109432. */
  109433. generateHarmonics,
  109434. /**
  109435. * 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)
  109436. */
  109437. gammaSpace,
  109438. /**
  109439. * Internal Use Only
  109440. */
  109441. reserved) {
  109442. if (noMipmap === void 0) { noMipmap = false; }
  109443. if (generateHarmonics === void 0) { generateHarmonics = true; }
  109444. if (gammaSpace === void 0) { gammaSpace = false; }
  109445. if (reserved === void 0) { reserved = false; }
  109446. var _this = _super.call(this, name) || this;
  109447. _this.name = name;
  109448. _this.url = url;
  109449. _this.size = size;
  109450. _this.noMipmap = noMipmap;
  109451. _this.generateHarmonics = generateHarmonics;
  109452. _this.gammaSpace = gammaSpace;
  109453. _this.reserved = reserved;
  109454. return _this;
  109455. }
  109456. /**
  109457. * Execute the current task
  109458. * @param scene defines the scene where you want your assets to be loaded
  109459. * @param onSuccess is a callback called when the task is successfully executed
  109460. * @param onError is a callback called if an error occurs
  109461. */
  109462. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  109463. var onload = function () {
  109464. onSuccess();
  109465. };
  109466. var onerror = function (message, exception) {
  109467. onError(message, exception);
  109468. };
  109469. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  109470. };
  109471. return HDRCubeTextureAssetTask;
  109472. }(AbstractAssetTask));
  109473. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  109474. /**
  109475. * This class can be used to easily import assets into a scene
  109476. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  109477. */
  109478. var AssetsManager = /** @class */ (function () {
  109479. /**
  109480. * Creates a new AssetsManager
  109481. * @param scene defines the scene to work on
  109482. */
  109483. function AssetsManager(scene) {
  109484. this._isLoading = false;
  109485. this._tasks = new Array();
  109486. this._waitingTasksCount = 0;
  109487. this._totalTasksCount = 0;
  109488. /**
  109489. * Observable called when all tasks are processed
  109490. */
  109491. this.onTaskSuccessObservable = new BABYLON.Observable();
  109492. /**
  109493. * Observable called when a task had an error
  109494. */
  109495. this.onTaskErrorObservable = new BABYLON.Observable();
  109496. /**
  109497. * Observable called when a task is successful
  109498. */
  109499. this.onTasksDoneObservable = new BABYLON.Observable();
  109500. /**
  109501. * Observable called when a task is done (whatever the result is)
  109502. */
  109503. this.onProgressObservable = new BABYLON.Observable();
  109504. /**
  109505. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  109506. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  109507. */
  109508. this.useDefaultLoadingScreen = true;
  109509. this._scene = scene;
  109510. }
  109511. /**
  109512. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  109513. * @param taskName defines the name of the new task
  109514. * @param meshesNames defines the name of meshes to load
  109515. * @param rootUrl defines the root url to use to locate files
  109516. * @param sceneFilename defines the filename of the scene file
  109517. * @returns a new {BABYLON.MeshAssetTask} object
  109518. */
  109519. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  109520. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  109521. this._tasks.push(task);
  109522. return task;
  109523. };
  109524. /**
  109525. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  109526. * @param taskName defines the name of the new task
  109527. * @param url defines the url of the file to load
  109528. * @returns a new {BABYLON.TextFileAssetTask} object
  109529. */
  109530. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  109531. var task = new TextFileAssetTask(taskName, url);
  109532. this._tasks.push(task);
  109533. return task;
  109534. };
  109535. /**
  109536. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  109537. * @param taskName defines the name of the new task
  109538. * @param url defines the url of the file to load
  109539. * @returns a new {BABYLON.BinaryFileAssetTask} object
  109540. */
  109541. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  109542. var task = new BinaryFileAssetTask(taskName, url);
  109543. this._tasks.push(task);
  109544. return task;
  109545. };
  109546. /**
  109547. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  109548. * @param taskName defines the name of the new task
  109549. * @param url defines the url of the file to load
  109550. * @returns a new {BABYLON.ImageAssetTask} object
  109551. */
  109552. AssetsManager.prototype.addImageTask = function (taskName, url) {
  109553. var task = new ImageAssetTask(taskName, url);
  109554. this._tasks.push(task);
  109555. return task;
  109556. };
  109557. /**
  109558. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  109559. * @param taskName defines the name of the new task
  109560. * @param url defines the url of the file to load
  109561. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  109562. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  109563. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  109564. * @returns a new {BABYLON.TextureAssetTask} object
  109565. */
  109566. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  109567. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  109568. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  109569. this._tasks.push(task);
  109570. return task;
  109571. };
  109572. /**
  109573. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  109574. * @param taskName defines the name of the new task
  109575. * @param url defines the url of the file to load
  109576. * @param extensions defines the extension to use to load the cube map (can be null)
  109577. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  109578. * @param files defines the list of files to load (can be null)
  109579. * @returns a new {BABYLON.CubeTextureAssetTask} object
  109580. */
  109581. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  109582. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  109583. this._tasks.push(task);
  109584. return task;
  109585. };
  109586. /**
  109587. *
  109588. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  109589. * @param taskName defines the name of the new task
  109590. * @param url defines the url of the file to load
  109591. * @param size defines the size you want for the cubemap (can be null)
  109592. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  109593. * @param generateHarmonics defines if you want to automatically generate (true by default)
  109594. * @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)
  109595. * @param reserved Internal use only
  109596. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  109597. */
  109598. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  109599. if (noMipmap === void 0) { noMipmap = false; }
  109600. if (generateHarmonics === void 0) { generateHarmonics = true; }
  109601. if (gammaSpace === void 0) { gammaSpace = false; }
  109602. if (reserved === void 0) { reserved = false; }
  109603. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  109604. this._tasks.push(task);
  109605. return task;
  109606. };
  109607. /**
  109608. * Remove a task from the assets manager.
  109609. * @param task the task to remove
  109610. */
  109611. AssetsManager.prototype.removeTask = function (task) {
  109612. var index = this._tasks.indexOf(task);
  109613. if (index > -1) {
  109614. this._tasks.splice(index, 1);
  109615. }
  109616. };
  109617. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  109618. this._waitingTasksCount--;
  109619. try {
  109620. if (this.onProgress) {
  109621. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  109622. }
  109623. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  109624. }
  109625. catch (e) {
  109626. BABYLON.Tools.Error("Error running progress callbacks.");
  109627. console.log(e);
  109628. }
  109629. if (this._waitingTasksCount === 0) {
  109630. try {
  109631. if (this.onFinish) {
  109632. this.onFinish(this._tasks);
  109633. }
  109634. // Let's remove successfull tasks
  109635. var currentTasks = this._tasks.slice();
  109636. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  109637. var task = currentTasks_1[_i];
  109638. if (task.taskState === AssetTaskState.DONE) {
  109639. var index = this._tasks.indexOf(task);
  109640. if (index > -1) {
  109641. this._tasks.splice(index, 1);
  109642. }
  109643. }
  109644. }
  109645. this.onTasksDoneObservable.notifyObservers(this._tasks);
  109646. }
  109647. catch (e) {
  109648. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  109649. console.log(e);
  109650. }
  109651. this._isLoading = false;
  109652. this._scene.getEngine().hideLoadingUI();
  109653. }
  109654. };
  109655. AssetsManager.prototype._runTask = function (task) {
  109656. var _this = this;
  109657. var done = function () {
  109658. try {
  109659. if (_this.onTaskSuccess) {
  109660. _this.onTaskSuccess(task);
  109661. }
  109662. _this.onTaskSuccessObservable.notifyObservers(task);
  109663. _this._decreaseWaitingTasksCount(task);
  109664. }
  109665. catch (e) {
  109666. error("Error executing task success callbacks", e);
  109667. }
  109668. };
  109669. var error = function (message, exception) {
  109670. task._setErrorObject(message, exception);
  109671. if (_this.onTaskError) {
  109672. _this.onTaskError(task);
  109673. }
  109674. _this.onTaskErrorObservable.notifyObservers(task);
  109675. _this._decreaseWaitingTasksCount(task);
  109676. };
  109677. task.run(this._scene, done, error);
  109678. };
  109679. /**
  109680. * Reset the {BABYLON.AssetsManager} and remove all tasks
  109681. * @return the current instance of the {BABYLON.AssetsManager}
  109682. */
  109683. AssetsManager.prototype.reset = function () {
  109684. this._isLoading = false;
  109685. this._tasks = new Array();
  109686. return this;
  109687. };
  109688. /**
  109689. * Start the loading process
  109690. * @return the current instance of the {BABYLON.AssetsManager}
  109691. */
  109692. AssetsManager.prototype.load = function () {
  109693. if (this._isLoading) {
  109694. return this;
  109695. }
  109696. this._isLoading = true;
  109697. this._waitingTasksCount = this._tasks.length;
  109698. this._totalTasksCount = this._tasks.length;
  109699. if (this._waitingTasksCount === 0) {
  109700. this._isLoading = false;
  109701. if (this.onFinish) {
  109702. this.onFinish(this._tasks);
  109703. }
  109704. this.onTasksDoneObservable.notifyObservers(this._tasks);
  109705. return this;
  109706. }
  109707. if (this.useDefaultLoadingScreen) {
  109708. this._scene.getEngine().displayLoadingUI();
  109709. }
  109710. for (var index = 0; index < this._tasks.length; index++) {
  109711. var task = this._tasks[index];
  109712. if (task.taskState === AssetTaskState.INIT) {
  109713. this._runTask(task);
  109714. }
  109715. }
  109716. return this;
  109717. };
  109718. return AssetsManager;
  109719. }());
  109720. BABYLON.AssetsManager = AssetsManager;
  109721. })(BABYLON || (BABYLON = {}));
  109722. //# sourceMappingURL=babylon.assetsManager.js.map
  109723. var BABYLON;
  109724. (function (BABYLON) {
  109725. var serializedGeometries = [];
  109726. var serializeGeometry = function (geometry, serializationGeometries) {
  109727. if (serializedGeometries[geometry.id]) {
  109728. return;
  109729. }
  109730. if (geometry.doNotSerialize) {
  109731. return;
  109732. }
  109733. if (geometry instanceof BABYLON.BoxGeometry) {
  109734. serializationGeometries.boxes.push(geometry.serialize());
  109735. }
  109736. else if (geometry instanceof BABYLON.SphereGeometry) {
  109737. serializationGeometries.spheres.push(geometry.serialize());
  109738. }
  109739. else if (geometry instanceof BABYLON.CylinderGeometry) {
  109740. serializationGeometries.cylinders.push(geometry.serialize());
  109741. }
  109742. else if (geometry instanceof BABYLON.TorusGeometry) {
  109743. serializationGeometries.toruses.push(geometry.serialize());
  109744. }
  109745. else if (geometry instanceof BABYLON.GroundGeometry) {
  109746. serializationGeometries.grounds.push(geometry.serialize());
  109747. }
  109748. else if (geometry instanceof BABYLON.Plane) {
  109749. serializationGeometries.planes.push(geometry.serialize());
  109750. }
  109751. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  109752. serializationGeometries.torusKnots.push(geometry.serialize());
  109753. }
  109754. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  109755. throw new Error("Unknown primitive type");
  109756. }
  109757. else {
  109758. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  109759. }
  109760. serializedGeometries[geometry.id] = true;
  109761. };
  109762. var serializeMesh = function (mesh, serializationScene) {
  109763. var serializationObject = {};
  109764. // Geometry
  109765. var geometry = mesh._geometry;
  109766. if (geometry) {
  109767. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  109768. // 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
  109769. serializeGeometry(geometry, serializationScene.geometries);
  109770. }
  109771. }
  109772. // Custom
  109773. if (mesh.serialize) {
  109774. mesh.serialize(serializationObject);
  109775. }
  109776. return serializationObject;
  109777. };
  109778. var finalizeSingleMesh = function (mesh, serializationObject) {
  109779. //only works if the mesh is already loaded
  109780. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  109781. //serialize material
  109782. if (mesh.material) {
  109783. if (mesh.material instanceof BABYLON.MultiMaterial) {
  109784. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  109785. serializationObject.materials = serializationObject.materials || [];
  109786. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  109787. serializationObject.multiMaterials.push(mesh.material.serialize());
  109788. var _loop_1 = function (submaterial) {
  109789. if (submaterial) {
  109790. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  109791. serializationObject.materials.push(submaterial.serialize());
  109792. }
  109793. }
  109794. };
  109795. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  109796. var submaterial = _a[_i];
  109797. _loop_1(submaterial);
  109798. }
  109799. }
  109800. }
  109801. else {
  109802. serializationObject.materials = serializationObject.materials || [];
  109803. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  109804. serializationObject.materials.push(mesh.material.serialize());
  109805. }
  109806. }
  109807. }
  109808. //serialize geometry
  109809. var geometry = mesh._geometry;
  109810. if (geometry) {
  109811. if (!serializationObject.geometries) {
  109812. serializationObject.geometries = {};
  109813. serializationObject.geometries.boxes = [];
  109814. serializationObject.geometries.spheres = [];
  109815. serializationObject.geometries.cylinders = [];
  109816. serializationObject.geometries.toruses = [];
  109817. serializationObject.geometries.grounds = [];
  109818. serializationObject.geometries.planes = [];
  109819. serializationObject.geometries.torusKnots = [];
  109820. serializationObject.geometries.vertexData = [];
  109821. }
  109822. serializeGeometry(geometry, serializationObject.geometries);
  109823. }
  109824. // Skeletons
  109825. if (mesh.skeleton) {
  109826. serializationObject.skeletons = serializationObject.skeletons || [];
  109827. serializationObject.skeletons.push(mesh.skeleton.serialize());
  109828. }
  109829. //serialize the actual mesh
  109830. serializationObject.meshes = serializationObject.meshes || [];
  109831. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  109832. }
  109833. };
  109834. /**
  109835. * Class used to serialize a scene into a string
  109836. */
  109837. var SceneSerializer = /** @class */ (function () {
  109838. function SceneSerializer() {
  109839. }
  109840. /**
  109841. * Clear cache used by a previous serialization
  109842. */
  109843. SceneSerializer.ClearCache = function () {
  109844. serializedGeometries = [];
  109845. };
  109846. /**
  109847. * Serialize a scene into a JSON compatible object
  109848. * @param scene defines the scene to serialize
  109849. * @returns a JSON compatible object
  109850. */
  109851. SceneSerializer.Serialize = function (scene) {
  109852. var serializationObject = {};
  109853. SceneSerializer.ClearCache();
  109854. // Scene
  109855. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  109856. serializationObject.autoClear = scene.autoClear;
  109857. serializationObject.clearColor = scene.clearColor.asArray();
  109858. serializationObject.ambientColor = scene.ambientColor.asArray();
  109859. serializationObject.gravity = scene.gravity.asArray();
  109860. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  109861. serializationObject.workerCollisions = scene.workerCollisions;
  109862. // Fog
  109863. if (scene.fogMode && scene.fogMode !== 0) {
  109864. serializationObject.fogMode = scene.fogMode;
  109865. serializationObject.fogColor = scene.fogColor.asArray();
  109866. serializationObject.fogStart = scene.fogStart;
  109867. serializationObject.fogEnd = scene.fogEnd;
  109868. serializationObject.fogDensity = scene.fogDensity;
  109869. }
  109870. //Physics
  109871. if (scene.isPhysicsEnabled()) {
  109872. var physicEngine = scene.getPhysicsEngine();
  109873. if (physicEngine) {
  109874. serializationObject.physicsEnabled = true;
  109875. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  109876. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  109877. }
  109878. }
  109879. // Metadata
  109880. if (scene.metadata) {
  109881. serializationObject.metadata = scene.metadata;
  109882. }
  109883. // Morph targets
  109884. serializationObject.morphTargetManagers = [];
  109885. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  109886. var abstractMesh = _a[_i];
  109887. var manager = abstractMesh.morphTargetManager;
  109888. if (manager) {
  109889. serializationObject.morphTargetManagers.push(manager.serialize());
  109890. }
  109891. }
  109892. // Lights
  109893. serializationObject.lights = [];
  109894. var index;
  109895. var light;
  109896. for (index = 0; index < scene.lights.length; index++) {
  109897. light = scene.lights[index];
  109898. if (!light.doNotSerialize) {
  109899. serializationObject.lights.push(light.serialize());
  109900. }
  109901. }
  109902. // Cameras
  109903. serializationObject.cameras = [];
  109904. for (index = 0; index < scene.cameras.length; index++) {
  109905. var camera = scene.cameras[index];
  109906. if (!camera.doNotSerialize) {
  109907. serializationObject.cameras.push(camera.serialize());
  109908. }
  109909. }
  109910. if (scene.activeCamera) {
  109911. serializationObject.activeCameraID = scene.activeCamera.id;
  109912. }
  109913. // Animations
  109914. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  109915. // Materials
  109916. serializationObject.materials = [];
  109917. serializationObject.multiMaterials = [];
  109918. var material;
  109919. for (index = 0; index < scene.materials.length; index++) {
  109920. material = scene.materials[index];
  109921. if (!material.doNotSerialize) {
  109922. serializationObject.materials.push(material.serialize());
  109923. }
  109924. }
  109925. // MultiMaterials
  109926. serializationObject.multiMaterials = [];
  109927. for (index = 0; index < scene.multiMaterials.length; index++) {
  109928. var multiMaterial = scene.multiMaterials[index];
  109929. serializationObject.multiMaterials.push(multiMaterial.serialize());
  109930. }
  109931. // Environment texture
  109932. if (scene.environmentTexture) {
  109933. serializationObject.environmentTexture = scene.environmentTexture.name;
  109934. }
  109935. // Skeletons
  109936. serializationObject.skeletons = [];
  109937. for (index = 0; index < scene.skeletons.length; index++) {
  109938. var skeleton = scene.skeletons[index];
  109939. if (!skeleton.doNotSerialize) {
  109940. serializationObject.skeletons.push(skeleton.serialize());
  109941. }
  109942. }
  109943. // Transform nodes
  109944. serializationObject.transformNodes = [];
  109945. for (index = 0; index < scene.transformNodes.length; index++) {
  109946. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  109947. }
  109948. // Geometries
  109949. serializationObject.geometries = {};
  109950. serializationObject.geometries.boxes = [];
  109951. serializationObject.geometries.spheres = [];
  109952. serializationObject.geometries.cylinders = [];
  109953. serializationObject.geometries.toruses = [];
  109954. serializationObject.geometries.grounds = [];
  109955. serializationObject.geometries.planes = [];
  109956. serializationObject.geometries.torusKnots = [];
  109957. serializationObject.geometries.vertexData = [];
  109958. serializedGeometries = [];
  109959. var geometries = scene.getGeometries();
  109960. for (index = 0; index < geometries.length; index++) {
  109961. var geometry = geometries[index];
  109962. if (geometry.isReady()) {
  109963. serializeGeometry(geometry, serializationObject.geometries);
  109964. }
  109965. }
  109966. // Meshes
  109967. serializationObject.meshes = [];
  109968. for (index = 0; index < scene.meshes.length; index++) {
  109969. var abstractMesh = scene.meshes[index];
  109970. if (abstractMesh instanceof BABYLON.Mesh) {
  109971. var mesh = abstractMesh;
  109972. if (!mesh.doNotSerialize) {
  109973. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  109974. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  109975. }
  109976. }
  109977. }
  109978. }
  109979. // Particles Systems
  109980. serializationObject.particleSystems = [];
  109981. for (index = 0; index < scene.particleSystems.length; index++) {
  109982. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  109983. }
  109984. // Action Manager
  109985. if (scene.actionManager) {
  109986. serializationObject.actions = scene.actionManager.serialize("scene");
  109987. }
  109988. // Components
  109989. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  109990. var component = _c[_b];
  109991. component.serialize(serializationObject);
  109992. }
  109993. return serializationObject;
  109994. };
  109995. /**
  109996. * Serialize a mesh into a JSON compatible object
  109997. * @param toSerialize defines the mesh to serialize
  109998. * @param withParents defines if parents must be serialized as well
  109999. * @param withChildren defines if children must be serialized as well
  110000. * @returns a JSON compatible object
  110001. */
  110002. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  110003. if (withParents === void 0) { withParents = false; }
  110004. if (withChildren === void 0) { withChildren = false; }
  110005. var serializationObject = {};
  110006. SceneSerializer.ClearCache();
  110007. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  110008. if (withParents || withChildren) {
  110009. //deliberate for loop! not for each, appended should be processed as well.
  110010. for (var i = 0; i < toSerialize.length; ++i) {
  110011. if (withChildren) {
  110012. toSerialize[i].getDescendants().forEach(function (node) {
  110013. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  110014. toSerialize.push(node);
  110015. }
  110016. });
  110017. }
  110018. //make sure the array doesn't contain the object already
  110019. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  110020. toSerialize.push(toSerialize[i].parent);
  110021. }
  110022. }
  110023. }
  110024. toSerialize.forEach(function (mesh) {
  110025. finalizeSingleMesh(mesh, serializationObject);
  110026. });
  110027. return serializationObject;
  110028. };
  110029. return SceneSerializer;
  110030. }());
  110031. BABYLON.SceneSerializer = SceneSerializer;
  110032. })(BABYLON || (BABYLON = {}));
  110033. //# sourceMappingURL=babylon.sceneSerializer.js.map
  110034. var BABYLON;
  110035. (function (BABYLON) {
  110036. /**
  110037. * Class used to generate realtime reflection / refraction cube textures
  110038. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  110039. */
  110040. var ReflectionProbe = /** @class */ (function () {
  110041. /**
  110042. * Creates a new reflection probe
  110043. * @param name defines the name of the probe
  110044. * @param size defines the texture resolution (for each face)
  110045. * @param scene defines the hosting scene
  110046. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  110047. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  110048. */
  110049. function ReflectionProbe(
  110050. /** defines the name of the probe */
  110051. name, size, scene, generateMipMaps, useFloat) {
  110052. if (generateMipMaps === void 0) { generateMipMaps = true; }
  110053. if (useFloat === void 0) { useFloat = false; }
  110054. var _this = this;
  110055. this.name = name;
  110056. this._viewMatrix = BABYLON.Matrix.Identity();
  110057. this._target = BABYLON.Vector3.Zero();
  110058. this._add = BABYLON.Vector3.Zero();
  110059. this._invertYAxis = false;
  110060. /** Gets or sets probe position (center of the cube map) */
  110061. this.position = BABYLON.Vector3.Zero();
  110062. this._scene = scene;
  110063. // Create the scene field if not exist.
  110064. if (!this._scene.reflectionProbes) {
  110065. this._scene.reflectionProbes = new Array();
  110066. }
  110067. this._scene.reflectionProbes.push(this);
  110068. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  110069. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  110070. switch (faceIndex) {
  110071. case 0:
  110072. _this._add.copyFromFloats(1, 0, 0);
  110073. break;
  110074. case 1:
  110075. _this._add.copyFromFloats(-1, 0, 0);
  110076. break;
  110077. case 2:
  110078. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  110079. break;
  110080. case 3:
  110081. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  110082. break;
  110083. case 4:
  110084. _this._add.copyFromFloats(0, 0, 1);
  110085. break;
  110086. case 5:
  110087. _this._add.copyFromFloats(0, 0, -1);
  110088. break;
  110089. }
  110090. if (_this._attachedMesh) {
  110091. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  110092. }
  110093. _this.position.addToRef(_this._add, _this._target);
  110094. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  110095. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  110096. scene._forcedViewPosition = _this.position;
  110097. });
  110098. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  110099. scene._forcedViewPosition = null;
  110100. scene.updateTransformMatrix(true);
  110101. });
  110102. if (scene.activeCamera) {
  110103. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  110104. }
  110105. }
  110106. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  110107. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  110108. get: function () {
  110109. return this._renderTargetTexture.samples;
  110110. },
  110111. set: function (value) {
  110112. this._renderTargetTexture.samples = value;
  110113. },
  110114. enumerable: true,
  110115. configurable: true
  110116. });
  110117. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  110118. /** Gets or sets the refresh rate to use (on every frame by default) */
  110119. get: function () {
  110120. return this._renderTargetTexture.refreshRate;
  110121. },
  110122. set: function (value) {
  110123. this._renderTargetTexture.refreshRate = value;
  110124. },
  110125. enumerable: true,
  110126. configurable: true
  110127. });
  110128. /**
  110129. * Gets the hosting scene
  110130. * @returns a Scene
  110131. */
  110132. ReflectionProbe.prototype.getScene = function () {
  110133. return this._scene;
  110134. };
  110135. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  110136. /** Gets the internal CubeTexture used to render to */
  110137. get: function () {
  110138. return this._renderTargetTexture;
  110139. },
  110140. enumerable: true,
  110141. configurable: true
  110142. });
  110143. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  110144. /** Gets the list of meshes to render */
  110145. get: function () {
  110146. return this._renderTargetTexture.renderList;
  110147. },
  110148. enumerable: true,
  110149. configurable: true
  110150. });
  110151. /**
  110152. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  110153. * @param mesh defines the mesh to attach to
  110154. */
  110155. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  110156. this._attachedMesh = mesh;
  110157. };
  110158. /**
  110159. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  110160. * @param renderingGroupId The rendering group id corresponding to its index
  110161. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  110162. */
  110163. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  110164. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  110165. };
  110166. /**
  110167. * Clean all associated resources
  110168. */
  110169. ReflectionProbe.prototype.dispose = function () {
  110170. var index = this._scene.reflectionProbes.indexOf(this);
  110171. if (index !== -1) {
  110172. // Remove from the scene if found
  110173. this._scene.reflectionProbes.splice(index, 1);
  110174. }
  110175. if (this._renderTargetTexture) {
  110176. this._renderTargetTexture.dispose();
  110177. this._renderTargetTexture = null;
  110178. }
  110179. };
  110180. return ReflectionProbe;
  110181. }());
  110182. BABYLON.ReflectionProbe = ReflectionProbe;
  110183. })(BABYLON || (BABYLON = {}));
  110184. //# sourceMappingURL=babylon.reflectionProbe.js.map
  110185. var BABYLON;
  110186. (function (BABYLON) {
  110187. /**
  110188. * Defines the layer scene component responsible to manage any layers
  110189. * in a given scene.
  110190. */
  110191. var LayerSceneComponent = /** @class */ (function () {
  110192. /**
  110193. * Creates a new instance of the component for the given scene
  110194. * @param scene Defines the scene to register the component in
  110195. */
  110196. function LayerSceneComponent(scene) {
  110197. /**
  110198. * The component name helpfull to identify the component in the list of scene components.
  110199. */
  110200. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  110201. this.scene = scene;
  110202. this._engine = scene.getEngine();
  110203. scene.layers = new Array();
  110204. }
  110205. /**
  110206. * Registers the component in a given scene
  110207. */
  110208. LayerSceneComponent.prototype.register = function () {
  110209. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  110210. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  110211. };
  110212. /**
  110213. * Rebuilds the elements related to this component in case of
  110214. * context lost for instance.
  110215. */
  110216. LayerSceneComponent.prototype.rebuild = function () {
  110217. var layers = this.scene.layers;
  110218. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  110219. var layer = layers_1[_i];
  110220. layer._rebuild();
  110221. }
  110222. };
  110223. /**
  110224. * Disposes the component and the associated ressources.
  110225. */
  110226. LayerSceneComponent.prototype.dispose = function () {
  110227. var layers = this.scene.layers;
  110228. while (layers.length) {
  110229. layers[0].dispose();
  110230. }
  110231. };
  110232. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  110233. var layers = this.scene.layers;
  110234. if (layers.length) {
  110235. this._engine.setDepthBuffer(false);
  110236. var cameraLayerMask = camera.layerMask;
  110237. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  110238. var layer = layers_2[_i];
  110239. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  110240. layer.render();
  110241. }
  110242. }
  110243. this._engine.setDepthBuffer(true);
  110244. }
  110245. };
  110246. LayerSceneComponent.prototype._drawBackground = function (camera) {
  110247. this._draw(camera, true);
  110248. };
  110249. LayerSceneComponent.prototype._drawForeground = function (camera) {
  110250. this._draw(camera, false);
  110251. };
  110252. return LayerSceneComponent;
  110253. }());
  110254. BABYLON.LayerSceneComponent = LayerSceneComponent;
  110255. })(BABYLON || (BABYLON = {}));
  110256. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  110257. var BABYLON;
  110258. (function (BABYLON) {
  110259. /**
  110260. * This represents a full screen 2d layer.
  110261. * This can be usefull to display a picture in the background of your scene for instance.
  110262. * @see https://www.babylonjs-playground.com/#08A2BS#1
  110263. */
  110264. var Layer = /** @class */ (function () {
  110265. /**
  110266. * Instantiates a new layer.
  110267. * This represents a full screen 2d layer.
  110268. * This can be usefull to display a picture in the background of your scene for instance.
  110269. * @see https://www.babylonjs-playground.com/#08A2BS#1
  110270. * @param name Define the name of the layer in the scene
  110271. * @param imgUrl Define the url of the texture to display in the layer
  110272. * @param scene Define the scene the layer belongs to
  110273. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  110274. * @param color Defines a color for the layer
  110275. */
  110276. function Layer(
  110277. /**
  110278. * Define the name of the layer.
  110279. */
  110280. name, imgUrl, scene, isBackground, color) {
  110281. this.name = name;
  110282. /**
  110283. * Define the scale of the layer in order to zoom in out of the texture.
  110284. */
  110285. this.scale = new BABYLON.Vector2(1, 1);
  110286. /**
  110287. * Define an offset for the layer in order to shift the texture.
  110288. */
  110289. this.offset = new BABYLON.Vector2(0, 0);
  110290. /**
  110291. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  110292. */
  110293. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  110294. /**
  110295. * Define a mask to restrict the layer to only some of the scene cameras.
  110296. */
  110297. this.layerMask = 0x0FFFFFFF;
  110298. this._vertexBuffers = {};
  110299. /**
  110300. * An event triggered when the layer is disposed.
  110301. */
  110302. this.onDisposeObservable = new BABYLON.Observable();
  110303. /**
  110304. * An event triggered before rendering the scene
  110305. */
  110306. this.onBeforeRenderObservable = new BABYLON.Observable();
  110307. /**
  110308. * An event triggered after rendering the scene
  110309. */
  110310. this.onAfterRenderObservable = new BABYLON.Observable();
  110311. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  110312. this.isBackground = isBackground === undefined ? true : isBackground;
  110313. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  110314. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  110315. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  110316. if (!layerComponent) {
  110317. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  110318. this._scene._addComponent(layerComponent);
  110319. }
  110320. this._scene.layers.push(this);
  110321. var engine = this._scene.getEngine();
  110322. // VBO
  110323. var vertices = [];
  110324. vertices.push(1, 1);
  110325. vertices.push(-1, 1);
  110326. vertices.push(-1, -1);
  110327. vertices.push(1, -1);
  110328. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  110329. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  110330. this._createIndexBuffer();
  110331. // Effects
  110332. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  110333. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  110334. }
  110335. Object.defineProperty(Layer.prototype, "onDispose", {
  110336. /**
  110337. * Back compatibility with callback before the onDisposeObservable existed.
  110338. * The set callback will be triggered when the layer has been disposed.
  110339. */
  110340. set: function (callback) {
  110341. if (this._onDisposeObserver) {
  110342. this.onDisposeObservable.remove(this._onDisposeObserver);
  110343. }
  110344. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  110345. },
  110346. enumerable: true,
  110347. configurable: true
  110348. });
  110349. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  110350. /**
  110351. * Back compatibility with callback before the onBeforeRenderObservable existed.
  110352. * The set callback will be triggered just before rendering the layer.
  110353. */
  110354. set: function (callback) {
  110355. if (this._onBeforeRenderObserver) {
  110356. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  110357. }
  110358. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  110359. },
  110360. enumerable: true,
  110361. configurable: true
  110362. });
  110363. Object.defineProperty(Layer.prototype, "onAfterRender", {
  110364. /**
  110365. * Back compatibility with callback before the onAfterRenderObservable existed.
  110366. * The set callback will be triggered just after rendering the layer.
  110367. */
  110368. set: function (callback) {
  110369. if (this._onAfterRenderObserver) {
  110370. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  110371. }
  110372. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  110373. },
  110374. enumerable: true,
  110375. configurable: true
  110376. });
  110377. Layer.prototype._createIndexBuffer = function () {
  110378. var engine = this._scene.getEngine();
  110379. // Indices
  110380. var indices = [];
  110381. indices.push(0);
  110382. indices.push(1);
  110383. indices.push(2);
  110384. indices.push(0);
  110385. indices.push(2);
  110386. indices.push(3);
  110387. this._indexBuffer = engine.createIndexBuffer(indices);
  110388. };
  110389. /** @hidden */
  110390. Layer.prototype._rebuild = function () {
  110391. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  110392. if (vb) {
  110393. vb._rebuild();
  110394. }
  110395. this._createIndexBuffer();
  110396. };
  110397. /**
  110398. * Renders the layer in the scene.
  110399. */
  110400. Layer.prototype.render = function () {
  110401. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  110402. // Check
  110403. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  110404. return;
  110405. var engine = this._scene.getEngine();
  110406. this.onBeforeRenderObservable.notifyObservers(this);
  110407. // Render
  110408. engine.enableEffect(currentEffect);
  110409. engine.setState(false);
  110410. // Texture
  110411. currentEffect.setTexture("textureSampler", this.texture);
  110412. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  110413. // Color
  110414. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  110415. // Scale / offset
  110416. currentEffect.setVector2("offset", this.offset);
  110417. currentEffect.setVector2("scale", this.scale);
  110418. // VBOs
  110419. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  110420. // Draw order
  110421. if (!this.alphaTest) {
  110422. engine.setAlphaMode(this.alphaBlendingMode);
  110423. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  110424. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  110425. }
  110426. else {
  110427. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  110428. }
  110429. this.onAfterRenderObservable.notifyObservers(this);
  110430. };
  110431. /**
  110432. * Disposes and releases the associated ressources.
  110433. */
  110434. Layer.prototype.dispose = function () {
  110435. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  110436. if (vertexBuffer) {
  110437. vertexBuffer.dispose();
  110438. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  110439. }
  110440. if (this._indexBuffer) {
  110441. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  110442. this._indexBuffer = null;
  110443. }
  110444. if (this.texture) {
  110445. this.texture.dispose();
  110446. this.texture = null;
  110447. }
  110448. // Remove from scene
  110449. var index = this._scene.layers.indexOf(this);
  110450. this._scene.layers.splice(index, 1);
  110451. // Callback
  110452. this.onDisposeObservable.notifyObservers(this);
  110453. this.onDisposeObservable.clear();
  110454. this.onAfterRenderObservable.clear();
  110455. this.onBeforeRenderObservable.clear();
  110456. };
  110457. return Layer;
  110458. }());
  110459. BABYLON.Layer = Layer;
  110460. })(BABYLON || (BABYLON = {}));
  110461. //# sourceMappingURL=babylon.layer.js.map
  110462. var BABYLON;
  110463. (function (BABYLON) {
  110464. /**
  110465. * Class used to host texture specific utilities
  110466. */
  110467. var TextureTools = /** @class */ (function () {
  110468. function TextureTools() {
  110469. }
  110470. /**
  110471. * Uses the GPU to create a copy texture rescaled at a given size
  110472. * @param texture Texture to copy from
  110473. * @param width defines the desired width
  110474. * @param height defines the desired height
  110475. * @param useBilinearMode defines if bilinear mode has to be used
  110476. * @return the generated texture
  110477. */
  110478. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  110479. if (useBilinearMode === void 0) { useBilinearMode = true; }
  110480. var scene = texture.getScene();
  110481. var engine = scene.getEngine();
  110482. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  110483. rtt.wrapU = texture.wrapU;
  110484. rtt.wrapV = texture.wrapV;
  110485. rtt.uOffset = texture.uOffset;
  110486. rtt.vOffset = texture.vOffset;
  110487. rtt.uScale = texture.uScale;
  110488. rtt.vScale = texture.vScale;
  110489. rtt.uAng = texture.uAng;
  110490. rtt.vAng = texture.vAng;
  110491. rtt.wAng = texture.wAng;
  110492. rtt.coordinatesIndex = texture.coordinatesIndex;
  110493. rtt.level = texture.level;
  110494. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  110495. rtt._texture.isReady = false;
  110496. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110497. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110498. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  110499. passPostProcess.getEffect().executeWhenCompiled(function () {
  110500. passPostProcess.onApply = function (effect) {
  110501. effect.setTexture("textureSampler", texture);
  110502. };
  110503. var internalTexture = rtt.getInternalTexture();
  110504. if (internalTexture) {
  110505. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  110506. engine.unBindFramebuffer(internalTexture);
  110507. rtt.disposeFramebufferObjects();
  110508. passPostProcess.dispose();
  110509. internalTexture.isReady = true;
  110510. }
  110511. });
  110512. return rtt;
  110513. };
  110514. /**
  110515. * Gets an environment BRDF texture for a given scene
  110516. * @param scene defines the hosting scene
  110517. * @returns the environment BRDF texture
  110518. */
  110519. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  110520. if (!scene._environmentBRDFTexture) {
  110521. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  110522. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110523. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110524. scene._environmentBRDFTexture = texture;
  110525. }
  110526. return scene._environmentBRDFTexture;
  110527. };
  110528. 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=";
  110529. return TextureTools;
  110530. }());
  110531. BABYLON.TextureTools = TextureTools;
  110532. })(BABYLON || (BABYLON = {}));
  110533. //# sourceMappingURL=babylon.textureTools.js.map
  110534. var BABYLON;
  110535. (function (BABYLON) {
  110536. /**
  110537. * The framing behavior (BABYLON.FramingBehavior) is designed to automatically position an ArcRotateCamera when its target is set to a mesh. It is also useful if you want to prevent the camera to go under a virtual horizontal plane.
  110538. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  110539. */
  110540. var FramingBehavior = /** @class */ (function () {
  110541. function FramingBehavior() {
  110542. this._mode = FramingBehavior.FitFrustumSidesMode;
  110543. this._radiusScale = 1.0;
  110544. this._positionScale = 0.5;
  110545. this._defaultElevation = 0.3;
  110546. this._elevationReturnTime = 1500;
  110547. this._elevationReturnWaitTime = 1000;
  110548. this._zoomStopsAnimation = false;
  110549. this._framingTime = 1500;
  110550. /**
  110551. * Define if the behavior should automatically change the configured
  110552. * camera limits and sensibilities.
  110553. */
  110554. this.autoCorrectCameraLimitsAndSensibility = true;
  110555. this._isPointerDown = false;
  110556. this._lastInteractionTime = -Infinity;
  110557. // Framing control
  110558. this._animatables = new Array();
  110559. this._betaIsAnimating = false;
  110560. }
  110561. Object.defineProperty(FramingBehavior.prototype, "name", {
  110562. /**
  110563. * Gets the name of the behavior.
  110564. */
  110565. get: function () {
  110566. return "Framing";
  110567. },
  110568. enumerable: true,
  110569. configurable: true
  110570. });
  110571. Object.defineProperty(FramingBehavior.prototype, "mode", {
  110572. /**
  110573. * Gets current mode used by the behavior.
  110574. */
  110575. get: function () {
  110576. return this._mode;
  110577. },
  110578. /**
  110579. * Sets the current mode used by the behavior
  110580. */
  110581. set: function (mode) {
  110582. this._mode = mode;
  110583. },
  110584. enumerable: true,
  110585. configurable: true
  110586. });
  110587. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  110588. /**
  110589. * Gets the scale applied to the radius
  110590. */
  110591. get: function () {
  110592. return this._radiusScale;
  110593. },
  110594. /**
  110595. * Sets the scale applied to the radius (1 by default)
  110596. */
  110597. set: function (radius) {
  110598. this._radiusScale = radius;
  110599. },
  110600. enumerable: true,
  110601. configurable: true
  110602. });
  110603. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  110604. /**
  110605. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  110606. */
  110607. get: function () {
  110608. return this._positionScale;
  110609. },
  110610. /**
  110611. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  110612. */
  110613. set: function (scale) {
  110614. this._positionScale = scale;
  110615. },
  110616. enumerable: true,
  110617. configurable: true
  110618. });
  110619. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  110620. /**
  110621. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  110622. * behaviour is triggered, in radians.
  110623. */
  110624. get: function () {
  110625. return this._defaultElevation;
  110626. },
  110627. /**
  110628. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  110629. * behaviour is triggered, in radians.
  110630. */
  110631. set: function (elevation) {
  110632. this._defaultElevation = elevation;
  110633. },
  110634. enumerable: true,
  110635. configurable: true
  110636. });
  110637. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  110638. /**
  110639. * Gets the time (in milliseconds) taken to return to the default beta position.
  110640. * Negative value indicates camera should not return to default.
  110641. */
  110642. get: function () {
  110643. return this._elevationReturnTime;
  110644. },
  110645. /**
  110646. * Sets the time (in milliseconds) taken to return to the default beta position.
  110647. * Negative value indicates camera should not return to default.
  110648. */
  110649. set: function (speed) {
  110650. this._elevationReturnTime = speed;
  110651. },
  110652. enumerable: true,
  110653. configurable: true
  110654. });
  110655. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  110656. /**
  110657. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  110658. */
  110659. get: function () {
  110660. return this._elevationReturnWaitTime;
  110661. },
  110662. /**
  110663. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  110664. */
  110665. set: function (time) {
  110666. this._elevationReturnWaitTime = time;
  110667. },
  110668. enumerable: true,
  110669. configurable: true
  110670. });
  110671. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  110672. /**
  110673. * Gets the flag that indicates if user zooming should stop animation.
  110674. */
  110675. get: function () {
  110676. return this._zoomStopsAnimation;
  110677. },
  110678. /**
  110679. * Sets the flag that indicates if user zooming should stop animation.
  110680. */
  110681. set: function (flag) {
  110682. this._zoomStopsAnimation = flag;
  110683. },
  110684. enumerable: true,
  110685. configurable: true
  110686. });
  110687. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  110688. /**
  110689. * Gets the transition time when framing the mesh, in milliseconds
  110690. */
  110691. get: function () {
  110692. return this._framingTime;
  110693. },
  110694. /**
  110695. * Sets the transition time when framing the mesh, in milliseconds
  110696. */
  110697. set: function (time) {
  110698. this._framingTime = time;
  110699. },
  110700. enumerable: true,
  110701. configurable: true
  110702. });
  110703. /**
  110704. * Initializes the behavior.
  110705. */
  110706. FramingBehavior.prototype.init = function () {
  110707. // Do notihng
  110708. };
  110709. /**
  110710. * Attaches the behavior to its arc rotate camera.
  110711. * @param camera Defines the camera to attach the behavior to
  110712. */
  110713. FramingBehavior.prototype.attach = function (camera) {
  110714. var _this = this;
  110715. this._attachedCamera = camera;
  110716. var scene = this._attachedCamera.getScene();
  110717. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  110718. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  110719. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  110720. _this._isPointerDown = true;
  110721. return;
  110722. }
  110723. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  110724. _this._isPointerDown = false;
  110725. }
  110726. });
  110727. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  110728. if (mesh) {
  110729. _this.zoomOnMesh(mesh);
  110730. }
  110731. });
  110732. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  110733. // Stop the animation if there is user interaction and the animation should stop for this interaction
  110734. _this._applyUserInteraction();
  110735. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  110736. // back to the default position after a given timeout
  110737. _this._maintainCameraAboveGround();
  110738. });
  110739. };
  110740. /**
  110741. * Detaches the behavior from its current arc rotate camera.
  110742. */
  110743. FramingBehavior.prototype.detach = function () {
  110744. if (!this._attachedCamera) {
  110745. return;
  110746. }
  110747. var scene = this._attachedCamera.getScene();
  110748. if (this._onPrePointerObservableObserver) {
  110749. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  110750. }
  110751. if (this._onAfterCheckInputsObserver) {
  110752. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  110753. }
  110754. if (this._onMeshTargetChangedObserver) {
  110755. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  110756. }
  110757. this._attachedCamera = null;
  110758. };
  110759. /**
  110760. * Targets the given mesh and updates zoom level accordingly.
  110761. * @param mesh The mesh to target.
  110762. * @param radius Optional. If a cached radius position already exists, overrides default.
  110763. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  110764. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  110765. * @param onAnimationEnd Callback triggered at the end of the framing animation
  110766. */
  110767. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  110768. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  110769. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  110770. mesh.computeWorldMatrix(true);
  110771. var boundingBox = mesh.getBoundingInfo().boundingBox;
  110772. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  110773. };
  110774. /**
  110775. * Targets the given mesh with its children and updates zoom level accordingly.
  110776. * @param mesh The mesh to target.
  110777. * @param radius Optional. If a cached radius position already exists, overrides default.
  110778. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  110779. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  110780. * @param onAnimationEnd Callback triggered at the end of the framing animation
  110781. */
  110782. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  110783. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  110784. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  110785. mesh.computeWorldMatrix(true);
  110786. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  110787. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  110788. };
  110789. /**
  110790. * Targets the given meshes with their children and updates zoom level accordingly.
  110791. * @param meshes The mesh to target.
  110792. * @param radius Optional. If a cached radius position already exists, overrides default.
  110793. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  110794. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  110795. * @param onAnimationEnd Callback triggered at the end of the framing animation
  110796. */
  110797. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  110798. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  110799. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  110800. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  110801. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  110802. for (var i = 0; i < meshes.length; i++) {
  110803. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  110804. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  110805. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  110806. }
  110807. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  110808. };
  110809. /**
  110810. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  110811. * @param minimumWorld Determines the smaller position of the bounding box extend
  110812. * @param maximumWorld Determines the bigger position of the bounding box extend
  110813. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  110814. * @param onAnimationEnd Callback triggered at the end of the framing animation
  110815. */
  110816. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  110817. var _this = this;
  110818. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  110819. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  110820. var zoomTarget;
  110821. if (!this._attachedCamera) {
  110822. return;
  110823. }
  110824. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  110825. var bottom = minimumWorld.y;
  110826. var top = maximumWorld.y;
  110827. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  110828. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  110829. if (focusOnOriginXZ) {
  110830. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  110831. }
  110832. else {
  110833. var centerWorld = minimumWorld.add(radiusWorld);
  110834. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  110835. }
  110836. if (!this._vectorTransition) {
  110837. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  110838. }
  110839. this._betaIsAnimating = true;
  110840. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  110841. if (animatable) {
  110842. this._animatables.push(animatable);
  110843. }
  110844. // sets the radius and lower radius bounds
  110845. // Small delta ensures camera is not always at lower zoom limit.
  110846. var radius = 0;
  110847. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  110848. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  110849. if (this.autoCorrectCameraLimitsAndSensibility) {
  110850. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  110851. }
  110852. radius = position;
  110853. }
  110854. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  110855. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  110856. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  110857. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  110858. }
  110859. }
  110860. // Set sensibilities
  110861. if (this.autoCorrectCameraLimitsAndSensibility) {
  110862. var extend = maximumWorld.subtract(minimumWorld).length();
  110863. this._attachedCamera.panningSensibility = 5000 / extend;
  110864. this._attachedCamera.wheelPrecision = 100 / radius;
  110865. }
  110866. // transition to new radius
  110867. if (!this._radiusTransition) {
  110868. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  110869. }
  110870. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  110871. _this.stopAllAnimations();
  110872. if (onAnimationEnd) {
  110873. onAnimationEnd();
  110874. }
  110875. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  110876. _this._attachedCamera.storeState();
  110877. }
  110878. });
  110879. if (animatable) {
  110880. this._animatables.push(animatable);
  110881. }
  110882. };
  110883. /**
  110884. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  110885. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  110886. * frustum width.
  110887. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  110888. * to fully enclose the mesh in the viewing frustum.
  110889. */
  110890. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  110891. var size = maximumWorld.subtract(minimumWorld);
  110892. var boxVectorGlobalDiagonal = size.length();
  110893. var frustumSlope = this._getFrustumSlope();
  110894. // Formula for setting distance
  110895. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  110896. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  110897. // Horizon distance
  110898. var radius = radiusWithoutFraming * this._radiusScale;
  110899. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  110900. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  110901. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  110902. var camera = this._attachedCamera;
  110903. if (!camera) {
  110904. return 0;
  110905. }
  110906. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  110907. // Don't exceed the requested limit
  110908. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  110909. }
  110910. // Don't exceed the upper radius limit
  110911. if (camera.upperRadiusLimit) {
  110912. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  110913. }
  110914. return distance;
  110915. };
  110916. /**
  110917. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  110918. * is automatically returned to its default position (expected to be above ground plane).
  110919. */
  110920. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  110921. var _this = this;
  110922. if (this._elevationReturnTime < 0) {
  110923. return;
  110924. }
  110925. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  110926. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  110927. var limitBeta = Math.PI * 0.5;
  110928. // Bring the camera back up if below the ground plane
  110929. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  110930. this._betaIsAnimating = true;
  110931. //Transition to new position
  110932. this.stopAllAnimations();
  110933. if (!this._betaTransition) {
  110934. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  110935. }
  110936. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  110937. _this._clearAnimationLocks();
  110938. _this.stopAllAnimations();
  110939. });
  110940. if (animatabe) {
  110941. this._animatables.push(animatabe);
  110942. }
  110943. }
  110944. };
  110945. /**
  110946. * Returns the frustum slope based on the canvas ratio and camera FOV
  110947. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  110948. */
  110949. FramingBehavior.prototype._getFrustumSlope = function () {
  110950. // Calculate the viewport ratio
  110951. // Aspect Ratio is Height/Width.
  110952. var camera = this._attachedCamera;
  110953. if (!camera) {
  110954. return BABYLON.Vector2.Zero();
  110955. }
  110956. var engine = camera.getScene().getEngine();
  110957. var aspectRatio = engine.getAspectRatio(camera);
  110958. // Camera FOV is the vertical field of view (top-bottom) in radians.
  110959. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  110960. var frustumSlopeY = Math.tan(camera.fov / 2);
  110961. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  110962. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  110963. // along the forward vector.
  110964. var frustumSlopeX = frustumSlopeY * aspectRatio;
  110965. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  110966. };
  110967. /**
  110968. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  110969. */
  110970. FramingBehavior.prototype._clearAnimationLocks = function () {
  110971. this._betaIsAnimating = false;
  110972. };
  110973. /**
  110974. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  110975. */
  110976. FramingBehavior.prototype._applyUserInteraction = function () {
  110977. if (this.isUserIsMoving) {
  110978. this._lastInteractionTime = BABYLON.Tools.Now;
  110979. this.stopAllAnimations();
  110980. this._clearAnimationLocks();
  110981. }
  110982. };
  110983. /**
  110984. * Stops and removes all animations that have been applied to the camera
  110985. */
  110986. FramingBehavior.prototype.stopAllAnimations = function () {
  110987. if (this._attachedCamera) {
  110988. this._attachedCamera.animations = [];
  110989. }
  110990. while (this._animatables.length) {
  110991. if (this._animatables[0]) {
  110992. this._animatables[0].onAnimationEnd = null;
  110993. this._animatables[0].stop();
  110994. }
  110995. this._animatables.shift();
  110996. }
  110997. };
  110998. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  110999. /**
  111000. * Gets a value indicating if the user is moving the camera
  111001. */
  111002. get: function () {
  111003. if (!this._attachedCamera) {
  111004. return false;
  111005. }
  111006. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  111007. this._attachedCamera.inertialBetaOffset !== 0 ||
  111008. this._attachedCamera.inertialRadiusOffset !== 0 ||
  111009. this._attachedCamera.inertialPanningX !== 0 ||
  111010. this._attachedCamera.inertialPanningY !== 0 ||
  111011. this._isPointerDown;
  111012. },
  111013. enumerable: true,
  111014. configurable: true
  111015. });
  111016. /**
  111017. * The easing function used by animations
  111018. */
  111019. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  111020. /**
  111021. * The easing mode used by animations
  111022. */
  111023. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  111024. // Statics
  111025. /**
  111026. * The camera can move all the way towards the mesh.
  111027. */
  111028. FramingBehavior.IgnoreBoundsSizeMode = 0;
  111029. /**
  111030. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  111031. */
  111032. FramingBehavior.FitFrustumSidesMode = 1;
  111033. return FramingBehavior;
  111034. }());
  111035. BABYLON.FramingBehavior = FramingBehavior;
  111036. })(BABYLON || (BABYLON = {}));
  111037. //# sourceMappingURL=babylon.framingBehavior.js.map
  111038. var BABYLON;
  111039. (function (BABYLON) {
  111040. /**
  111041. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  111042. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  111043. */
  111044. var BouncingBehavior = /** @class */ (function () {
  111045. function BouncingBehavior() {
  111046. /**
  111047. * The duration of the animation, in milliseconds
  111048. */
  111049. this.transitionDuration = 450;
  111050. /**
  111051. * Length of the distance animated by the transition when lower radius is reached
  111052. */
  111053. this.lowerRadiusTransitionRange = 2;
  111054. /**
  111055. * Length of the distance animated by the transition when upper radius is reached
  111056. */
  111057. this.upperRadiusTransitionRange = -2;
  111058. this._autoTransitionRange = false;
  111059. // Animations
  111060. this._radiusIsAnimating = false;
  111061. this._radiusBounceTransition = null;
  111062. this._animatables = new Array();
  111063. }
  111064. Object.defineProperty(BouncingBehavior.prototype, "name", {
  111065. /**
  111066. * Gets the name of the behavior.
  111067. */
  111068. get: function () {
  111069. return "Bouncing";
  111070. },
  111071. enumerable: true,
  111072. configurable: true
  111073. });
  111074. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  111075. /**
  111076. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  111077. */
  111078. get: function () {
  111079. return this._autoTransitionRange;
  111080. },
  111081. /**
  111082. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  111083. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  111084. */
  111085. set: function (value) {
  111086. var _this = this;
  111087. if (this._autoTransitionRange === value) {
  111088. return;
  111089. }
  111090. this._autoTransitionRange = value;
  111091. var camera = this._attachedCamera;
  111092. if (!camera) {
  111093. return;
  111094. }
  111095. if (value) {
  111096. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  111097. if (!mesh) {
  111098. return;
  111099. }
  111100. mesh.computeWorldMatrix(true);
  111101. var diagonal = mesh.getBoundingInfo().diagonalLength;
  111102. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  111103. _this.upperRadiusTransitionRange = diagonal * 0.05;
  111104. });
  111105. }
  111106. else if (this._onMeshTargetChangedObserver) {
  111107. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  111108. }
  111109. },
  111110. enumerable: true,
  111111. configurable: true
  111112. });
  111113. /**
  111114. * Initializes the behavior.
  111115. */
  111116. BouncingBehavior.prototype.init = function () {
  111117. // Do notihng
  111118. };
  111119. /**
  111120. * Attaches the behavior to its arc rotate camera.
  111121. * @param camera Defines the camera to attach the behavior to
  111122. */
  111123. BouncingBehavior.prototype.attach = function (camera) {
  111124. var _this = this;
  111125. this._attachedCamera = camera;
  111126. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  111127. if (!_this._attachedCamera) {
  111128. return;
  111129. }
  111130. // Add the bounce animation to the lower radius limit
  111131. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  111132. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  111133. }
  111134. // Add the bounce animation to the upper radius limit
  111135. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  111136. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  111137. }
  111138. });
  111139. };
  111140. /**
  111141. * Detaches the behavior from its current arc rotate camera.
  111142. */
  111143. BouncingBehavior.prototype.detach = function () {
  111144. if (!this._attachedCamera) {
  111145. return;
  111146. }
  111147. if (this._onAfterCheckInputsObserver) {
  111148. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  111149. }
  111150. if (this._onMeshTargetChangedObserver) {
  111151. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  111152. }
  111153. this._attachedCamera = null;
  111154. };
  111155. /**
  111156. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  111157. * @param radiusLimit The limit to check against.
  111158. * @return Bool to indicate if at limit.
  111159. */
  111160. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  111161. if (!this._attachedCamera) {
  111162. return false;
  111163. }
  111164. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  111165. return true;
  111166. }
  111167. return false;
  111168. };
  111169. /**
  111170. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  111171. * @param radiusDelta The delta by which to animate to. Can be negative.
  111172. */
  111173. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  111174. var _this = this;
  111175. if (!this._attachedCamera) {
  111176. return;
  111177. }
  111178. if (!this._radiusBounceTransition) {
  111179. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  111180. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  111181. }
  111182. // Prevent zoom until bounce has completed
  111183. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  111184. this._attachedCamera.wheelPrecision = Infinity;
  111185. this._attachedCamera.inertialRadiusOffset = 0;
  111186. // Animate to the radius limit
  111187. this.stopAllAnimations();
  111188. this._radiusIsAnimating = true;
  111189. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  111190. if (animatable) {
  111191. this._animatables.push(animatable);
  111192. }
  111193. };
  111194. /**
  111195. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  111196. */
  111197. BouncingBehavior.prototype._clearAnimationLocks = function () {
  111198. this._radiusIsAnimating = false;
  111199. if (this._attachedCamera) {
  111200. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  111201. }
  111202. };
  111203. /**
  111204. * Stops and removes all animations that have been applied to the camera
  111205. */
  111206. BouncingBehavior.prototype.stopAllAnimations = function () {
  111207. if (this._attachedCamera) {
  111208. this._attachedCamera.animations = [];
  111209. }
  111210. while (this._animatables.length) {
  111211. this._animatables[0].onAnimationEnd = null;
  111212. this._animatables[0].stop();
  111213. this._animatables.shift();
  111214. }
  111215. };
  111216. /**
  111217. * The easing function used by animations
  111218. */
  111219. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  111220. /**
  111221. * The easing mode used by animations
  111222. */
  111223. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  111224. return BouncingBehavior;
  111225. }());
  111226. BABYLON.BouncingBehavior = BouncingBehavior;
  111227. })(BABYLON || (BABYLON = {}));
  111228. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  111229. var BABYLON;
  111230. (function (BABYLON) {
  111231. /**
  111232. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  111233. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  111234. */
  111235. var AutoRotationBehavior = /** @class */ (function () {
  111236. function AutoRotationBehavior() {
  111237. this._zoomStopsAnimation = false;
  111238. this._idleRotationSpeed = 0.05;
  111239. this._idleRotationWaitTime = 2000;
  111240. this._idleRotationSpinupTime = 2000;
  111241. this._isPointerDown = false;
  111242. this._lastFrameTime = null;
  111243. this._lastInteractionTime = -Infinity;
  111244. this._cameraRotationSpeed = 0;
  111245. this._lastFrameRadius = 0;
  111246. }
  111247. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  111248. /**
  111249. * Gets the name of the behavior.
  111250. */
  111251. get: function () {
  111252. return "AutoRotation";
  111253. },
  111254. enumerable: true,
  111255. configurable: true
  111256. });
  111257. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  111258. /**
  111259. * Gets the flag that indicates if user zooming should stop animation.
  111260. */
  111261. get: function () {
  111262. return this._zoomStopsAnimation;
  111263. },
  111264. /**
  111265. * Sets the flag that indicates if user zooming should stop animation.
  111266. */
  111267. set: function (flag) {
  111268. this._zoomStopsAnimation = flag;
  111269. },
  111270. enumerable: true,
  111271. configurable: true
  111272. });
  111273. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  111274. /**
  111275. * Gets the default speed at which the camera rotates around the model.
  111276. */
  111277. get: function () {
  111278. return this._idleRotationSpeed;
  111279. },
  111280. /**
  111281. * Sets the default speed at which the camera rotates around the model.
  111282. */
  111283. set: function (speed) {
  111284. this._idleRotationSpeed = speed;
  111285. },
  111286. enumerable: true,
  111287. configurable: true
  111288. });
  111289. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  111290. /**
  111291. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  111292. */
  111293. get: function () {
  111294. return this._idleRotationWaitTime;
  111295. },
  111296. /**
  111297. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  111298. */
  111299. set: function (time) {
  111300. this._idleRotationWaitTime = time;
  111301. },
  111302. enumerable: true,
  111303. configurable: true
  111304. });
  111305. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  111306. /**
  111307. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  111308. */
  111309. get: function () {
  111310. return this._idleRotationSpinupTime;
  111311. },
  111312. /**
  111313. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  111314. */
  111315. set: function (time) {
  111316. this._idleRotationSpinupTime = time;
  111317. },
  111318. enumerable: true,
  111319. configurable: true
  111320. });
  111321. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  111322. /**
  111323. * Gets a value indicating if the camera is currently rotating because of this behavior
  111324. */
  111325. get: function () {
  111326. return Math.abs(this._cameraRotationSpeed) > 0;
  111327. },
  111328. enumerable: true,
  111329. configurable: true
  111330. });
  111331. /**
  111332. * Initializes the behavior.
  111333. */
  111334. AutoRotationBehavior.prototype.init = function () {
  111335. // Do notihng
  111336. };
  111337. /**
  111338. * Attaches the behavior to its arc rotate camera.
  111339. * @param camera Defines the camera to attach the behavior to
  111340. */
  111341. AutoRotationBehavior.prototype.attach = function (camera) {
  111342. var _this = this;
  111343. this._attachedCamera = camera;
  111344. var scene = this._attachedCamera.getScene();
  111345. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  111346. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  111347. _this._isPointerDown = true;
  111348. return;
  111349. }
  111350. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  111351. _this._isPointerDown = false;
  111352. }
  111353. });
  111354. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  111355. var now = BABYLON.Tools.Now;
  111356. var dt = 0;
  111357. if (_this._lastFrameTime != null) {
  111358. dt = now - _this._lastFrameTime;
  111359. }
  111360. _this._lastFrameTime = now;
  111361. // Stop the animation if there is user interaction and the animation should stop for this interaction
  111362. _this._applyUserInteraction();
  111363. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  111364. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  111365. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  111366. // Step camera rotation by rotation speed
  111367. if (_this._attachedCamera) {
  111368. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  111369. }
  111370. });
  111371. };
  111372. /**
  111373. * Detaches the behavior from its current arc rotate camera.
  111374. */
  111375. AutoRotationBehavior.prototype.detach = function () {
  111376. if (!this._attachedCamera) {
  111377. return;
  111378. }
  111379. var scene = this._attachedCamera.getScene();
  111380. if (this._onPrePointerObservableObserver) {
  111381. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  111382. }
  111383. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  111384. this._attachedCamera = null;
  111385. };
  111386. /**
  111387. * Returns true if user is scrolling.
  111388. * @return true if user is scrolling.
  111389. */
  111390. AutoRotationBehavior.prototype._userIsZooming = function () {
  111391. if (!this._attachedCamera) {
  111392. return false;
  111393. }
  111394. return this._attachedCamera.inertialRadiusOffset !== 0;
  111395. };
  111396. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  111397. if (!this._attachedCamera) {
  111398. return false;
  111399. }
  111400. var zoomHasHitLimit = false;
  111401. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  111402. zoomHasHitLimit = true;
  111403. }
  111404. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  111405. this._lastFrameRadius = this._attachedCamera.radius;
  111406. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  111407. };
  111408. /**
  111409. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  111410. */
  111411. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  111412. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  111413. this._lastInteractionTime = BABYLON.Tools.Now;
  111414. }
  111415. };
  111416. // Tools
  111417. AutoRotationBehavior.prototype._userIsMoving = function () {
  111418. if (!this._attachedCamera) {
  111419. return false;
  111420. }
  111421. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  111422. this._attachedCamera.inertialBetaOffset !== 0 ||
  111423. this._attachedCamera.inertialRadiusOffset !== 0 ||
  111424. this._attachedCamera.inertialPanningX !== 0 ||
  111425. this._attachedCamera.inertialPanningY !== 0 ||
  111426. this._isPointerDown;
  111427. };
  111428. return AutoRotationBehavior;
  111429. }());
  111430. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  111431. })(BABYLON || (BABYLON = {}));
  111432. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  111433. var BABYLON;
  111434. (function (BABYLON) {
  111435. var NullEngineOptions = /** @class */ (function () {
  111436. function NullEngineOptions() {
  111437. this.renderWidth = 512;
  111438. this.renderHeight = 256;
  111439. this.textureSize = 512;
  111440. this.deterministicLockstep = false;
  111441. this.lockstepMaxSteps = 4;
  111442. }
  111443. return NullEngineOptions;
  111444. }());
  111445. BABYLON.NullEngineOptions = NullEngineOptions;
  111446. /**
  111447. * The null engine class provides support for headless version of babylon.js.
  111448. * This can be used in server side scenario or for testing purposes
  111449. */
  111450. var NullEngine = /** @class */ (function (_super) {
  111451. __extends(NullEngine, _super);
  111452. function NullEngine(options) {
  111453. if (options === void 0) { options = new NullEngineOptions(); }
  111454. var _this = _super.call(this, null) || this;
  111455. if (options.deterministicLockstep === undefined) {
  111456. options.deterministicLockstep = false;
  111457. }
  111458. if (options.lockstepMaxSteps === undefined) {
  111459. options.lockstepMaxSteps = 4;
  111460. }
  111461. _this._options = options;
  111462. // Init caps
  111463. // We consider we are on a webgl1 capable device
  111464. _this._caps = new BABYLON.EngineCapabilities();
  111465. _this._caps.maxTexturesImageUnits = 16;
  111466. _this._caps.maxVertexTextureImageUnits = 16;
  111467. _this._caps.maxTextureSize = 512;
  111468. _this._caps.maxCubemapTextureSize = 512;
  111469. _this._caps.maxRenderTextureSize = 512;
  111470. _this._caps.maxVertexAttribs = 16;
  111471. _this._caps.maxVaryingVectors = 16;
  111472. _this._caps.maxFragmentUniformVectors = 16;
  111473. _this._caps.maxVertexUniformVectors = 16;
  111474. // Extensions
  111475. _this._caps.standardDerivatives = false;
  111476. _this._caps.astc = null;
  111477. _this._caps.s3tc = null;
  111478. _this._caps.pvrtc = null;
  111479. _this._caps.etc1 = null;
  111480. _this._caps.etc2 = null;
  111481. _this._caps.textureAnisotropicFilterExtension = null;
  111482. _this._caps.maxAnisotropy = 0;
  111483. _this._caps.uintIndices = false;
  111484. _this._caps.fragmentDepthSupported = false;
  111485. _this._caps.highPrecisionShaderSupported = true;
  111486. _this._caps.colorBufferFloat = false;
  111487. _this._caps.textureFloat = false;
  111488. _this._caps.textureFloatLinearFiltering = false;
  111489. _this._caps.textureFloatRender = false;
  111490. _this._caps.textureHalfFloat = false;
  111491. _this._caps.textureHalfFloatLinearFiltering = false;
  111492. _this._caps.textureHalfFloatRender = false;
  111493. _this._caps.textureLOD = false;
  111494. _this._caps.drawBuffersExtension = false;
  111495. _this._caps.depthTextureExtension = false;
  111496. _this._caps.vertexArrayObject = false;
  111497. _this._caps.instancedArrays = false;
  111498. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  111499. // Wrappers
  111500. if (typeof URL === "undefined") {
  111501. URL = {
  111502. createObjectURL: function () { },
  111503. revokeObjectURL: function () { }
  111504. };
  111505. }
  111506. if (typeof Blob === "undefined") {
  111507. Blob = function () { };
  111508. }
  111509. return _this;
  111510. }
  111511. NullEngine.prototype.isDeterministicLockStep = function () {
  111512. return this._options.deterministicLockstep;
  111513. };
  111514. NullEngine.prototype.getLockstepMaxSteps = function () {
  111515. return this._options.lockstepMaxSteps;
  111516. };
  111517. NullEngine.prototype.getHardwareScalingLevel = function () {
  111518. return 1.0;
  111519. };
  111520. NullEngine.prototype.createVertexBuffer = function (vertices) {
  111521. return {
  111522. capacity: 0,
  111523. references: 1,
  111524. is32Bits: false
  111525. };
  111526. };
  111527. NullEngine.prototype.createIndexBuffer = function (indices) {
  111528. return {
  111529. capacity: 0,
  111530. references: 1,
  111531. is32Bits: false
  111532. };
  111533. };
  111534. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  111535. if (stencil === void 0) { stencil = false; }
  111536. };
  111537. NullEngine.prototype.getRenderWidth = function (useScreen) {
  111538. if (useScreen === void 0) { useScreen = false; }
  111539. if (!useScreen && this._currentRenderTarget) {
  111540. return this._currentRenderTarget.width;
  111541. }
  111542. return this._options.renderWidth;
  111543. };
  111544. NullEngine.prototype.getRenderHeight = function (useScreen) {
  111545. if (useScreen === void 0) { useScreen = false; }
  111546. if (!useScreen && this._currentRenderTarget) {
  111547. return this._currentRenderTarget.height;
  111548. }
  111549. return this._options.renderHeight;
  111550. };
  111551. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  111552. this._cachedViewport = viewport;
  111553. };
  111554. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  111555. return {
  111556. transformFeedback: null,
  111557. __SPECTOR_rebuildProgram: null
  111558. };
  111559. };
  111560. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  111561. return [];
  111562. };
  111563. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  111564. return [];
  111565. };
  111566. NullEngine.prototype.bindSamplers = function (effect) {
  111567. this._currentEffect = null;
  111568. };
  111569. NullEngine.prototype.enableEffect = function (effect) {
  111570. this._currentEffect = effect;
  111571. if (effect.onBind) {
  111572. effect.onBind(effect);
  111573. }
  111574. if (effect._onBindObservable) {
  111575. effect._onBindObservable.notifyObservers(effect);
  111576. }
  111577. };
  111578. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  111579. if (zOffset === void 0) { zOffset = 0; }
  111580. if (reverseSide === void 0) { reverseSide = false; }
  111581. };
  111582. NullEngine.prototype.setIntArray = function (uniform, array) {
  111583. };
  111584. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  111585. };
  111586. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  111587. };
  111588. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  111589. };
  111590. NullEngine.prototype.setFloatArray = function (uniform, array) {
  111591. };
  111592. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  111593. };
  111594. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  111595. };
  111596. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  111597. };
  111598. NullEngine.prototype.setArray = function (uniform, array) {
  111599. };
  111600. NullEngine.prototype.setArray2 = function (uniform, array) {
  111601. };
  111602. NullEngine.prototype.setArray3 = function (uniform, array) {
  111603. };
  111604. NullEngine.prototype.setArray4 = function (uniform, array) {
  111605. };
  111606. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  111607. };
  111608. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  111609. };
  111610. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  111611. };
  111612. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  111613. };
  111614. NullEngine.prototype.setFloat = function (uniform, value) {
  111615. };
  111616. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  111617. };
  111618. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  111619. };
  111620. NullEngine.prototype.setBool = function (uniform, bool) {
  111621. };
  111622. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  111623. };
  111624. NullEngine.prototype.setColor3 = function (uniform, color3) {
  111625. };
  111626. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  111627. };
  111628. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  111629. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  111630. if (this._alphaMode === mode) {
  111631. return;
  111632. }
  111633. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  111634. if (!noDepthWriteChange) {
  111635. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  111636. }
  111637. this._alphaMode = mode;
  111638. };
  111639. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  111640. };
  111641. NullEngine.prototype.wipeCaches = function (bruteForce) {
  111642. if (this.preventCacheWipeBetweenFrames) {
  111643. return;
  111644. }
  111645. this.resetTextureCache();
  111646. this._currentEffect = null;
  111647. if (bruteForce) {
  111648. this._currentProgram = null;
  111649. this._stencilState.reset();
  111650. this._depthCullingState.reset();
  111651. this._alphaState.reset();
  111652. }
  111653. this._cachedVertexBuffers = null;
  111654. this._cachedIndexBuffer = null;
  111655. this._cachedEffectForVertexBuffers = null;
  111656. };
  111657. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  111658. };
  111659. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  111660. };
  111661. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  111662. };
  111663. /** @hidden */
  111664. NullEngine.prototype._createTexture = function () {
  111665. return {};
  111666. };
  111667. /** @hidden */
  111668. NullEngine.prototype._releaseTexture = function (texture) {
  111669. };
  111670. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  111671. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  111672. if (onLoad === void 0) { onLoad = null; }
  111673. if (onError === void 0) { onError = null; }
  111674. if (buffer === void 0) { buffer = null; }
  111675. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  111676. var url = String(urlArg);
  111677. texture.url = url;
  111678. texture.generateMipMaps = !noMipmap;
  111679. texture.samplingMode = samplingMode;
  111680. texture.invertY = invertY;
  111681. texture.baseWidth = this._options.textureSize;
  111682. texture.baseHeight = this._options.textureSize;
  111683. texture.width = this._options.textureSize;
  111684. texture.height = this._options.textureSize;
  111685. if (format) {
  111686. texture.format = format;
  111687. }
  111688. texture.isReady = true;
  111689. if (onLoad) {
  111690. onLoad();
  111691. }
  111692. this._internalTexturesCache.push(texture);
  111693. return texture;
  111694. };
  111695. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  111696. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  111697. if (options !== undefined && typeof options === "object") {
  111698. fullOptions.generateMipMaps = options.generateMipMaps;
  111699. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  111700. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  111701. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  111702. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  111703. }
  111704. else {
  111705. fullOptions.generateMipMaps = options;
  111706. fullOptions.generateDepthBuffer = true;
  111707. fullOptions.generateStencilBuffer = false;
  111708. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  111709. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  111710. }
  111711. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  111712. var width = size.width || size;
  111713. var height = size.height || size;
  111714. texture._depthStencilBuffer = {};
  111715. texture._framebuffer = {};
  111716. texture.baseWidth = width;
  111717. texture.baseHeight = height;
  111718. texture.width = width;
  111719. texture.height = height;
  111720. texture.isReady = true;
  111721. texture.samples = 1;
  111722. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  111723. texture.samplingMode = fullOptions.samplingMode;
  111724. texture.type = fullOptions.type;
  111725. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  111726. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  111727. this._internalTexturesCache.push(texture);
  111728. return texture;
  111729. };
  111730. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  111731. texture.samplingMode = samplingMode;
  111732. };
  111733. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  111734. if (this._currentRenderTarget) {
  111735. this.unBindFramebuffer(this._currentRenderTarget);
  111736. }
  111737. this._currentRenderTarget = texture;
  111738. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  111739. if (this._cachedViewport && !forceFullscreenViewport) {
  111740. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  111741. }
  111742. };
  111743. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  111744. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  111745. this._currentRenderTarget = null;
  111746. if (onBeforeUnbind) {
  111747. if (texture._MSAAFramebuffer) {
  111748. this._currentFramebuffer = texture._framebuffer;
  111749. }
  111750. onBeforeUnbind();
  111751. }
  111752. this._currentFramebuffer = null;
  111753. };
  111754. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  111755. var vbo = {
  111756. capacity: 1,
  111757. references: 1,
  111758. is32Bits: false
  111759. };
  111760. return vbo;
  111761. };
  111762. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  111763. if (premulAlpha === void 0) { premulAlpha = false; }
  111764. };
  111765. /**
  111766. * @hidden
  111767. * Get the current error code of the webGL context
  111768. * @returns the error code
  111769. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  111770. */
  111771. NullEngine.prototype.getError = function () {
  111772. return 0;
  111773. };
  111774. /** @hidden */
  111775. NullEngine.prototype._getUnpackAlignement = function () {
  111776. return 1;
  111777. };
  111778. /** @hidden */
  111779. NullEngine.prototype._unpackFlipY = function (value) {
  111780. };
  111781. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  111782. if (offset === void 0) { offset = 0; }
  111783. };
  111784. /**
  111785. * Updates a dynamic vertex buffer.
  111786. * @param vertexBuffer the vertex buffer to update
  111787. * @param data the data used to update the vertex buffer
  111788. * @param byteOffset the byte offset of the data (optional)
  111789. * @param byteLength the byte length of the data (optional)
  111790. */
  111791. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  111792. };
  111793. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  111794. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  111795. this._boundTexturesCache[this._activeChannel] = texture;
  111796. return true;
  111797. }
  111798. return false;
  111799. };
  111800. /** @hidden */
  111801. NullEngine.prototype._bindTexture = function (channel, texture) {
  111802. if (channel < 0) {
  111803. return;
  111804. }
  111805. this._bindTextureDirectly(0, texture);
  111806. };
  111807. /** @hidden */
  111808. NullEngine.prototype._releaseBuffer = function (buffer) {
  111809. buffer.references--;
  111810. if (buffer.references === 0) {
  111811. return true;
  111812. }
  111813. return false;
  111814. };
  111815. NullEngine.prototype.releaseEffects = function () {
  111816. };
  111817. NullEngine.prototype.displayLoadingUI = function () {
  111818. };
  111819. NullEngine.prototype.hideLoadingUI = function () {
  111820. };
  111821. /** @hidden */
  111822. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  111823. if (faceIndex === void 0) { faceIndex = 0; }
  111824. if (lod === void 0) { lod = 0; }
  111825. };
  111826. /** @hidden */
  111827. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  111828. if (faceIndex === void 0) { faceIndex = 0; }
  111829. if (lod === void 0) { lod = 0; }
  111830. };
  111831. /** @hidden */
  111832. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  111833. if (faceIndex === void 0) { faceIndex = 0; }
  111834. if (lod === void 0) { lod = 0; }
  111835. };
  111836. /** @hidden */
  111837. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  111838. if (faceIndex === void 0) { faceIndex = 0; }
  111839. if (lod === void 0) { lod = 0; }
  111840. };
  111841. return NullEngine;
  111842. }(BABYLON.Engine));
  111843. BABYLON.NullEngine = NullEngine;
  111844. })(BABYLON || (BABYLON = {}));
  111845. //# sourceMappingURL=babylon.nullEngine.js.map
  111846. var BABYLON;
  111847. (function (BABYLON) {
  111848. /**
  111849. * This class can be used to get instrumentation data from a Babylon engine
  111850. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  111851. */
  111852. var EngineInstrumentation = /** @class */ (function () {
  111853. /**
  111854. * Instantiates a new engine instrumentation.
  111855. * This class can be used to get instrumentation data from a Babylon engine
  111856. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  111857. * @param engine Defines the engine to instrument
  111858. */
  111859. function EngineInstrumentation(
  111860. /**
  111861. * Define the instrumented engine.
  111862. */
  111863. engine) {
  111864. this.engine = engine;
  111865. this._captureGPUFrameTime = false;
  111866. this._gpuFrameTime = new BABYLON.PerfCounter();
  111867. this._captureShaderCompilationTime = false;
  111868. this._shaderCompilationTime = new BABYLON.PerfCounter();
  111869. // Observers
  111870. this._onBeginFrameObserver = null;
  111871. this._onEndFrameObserver = null;
  111872. this._onBeforeShaderCompilationObserver = null;
  111873. this._onAfterShaderCompilationObserver = null;
  111874. }
  111875. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  111876. // Properties
  111877. /**
  111878. * Gets the perf counter used for GPU frame time
  111879. */
  111880. get: function () {
  111881. return this._gpuFrameTime;
  111882. },
  111883. enumerable: true,
  111884. configurable: true
  111885. });
  111886. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  111887. /**
  111888. * Gets the GPU frame time capture status
  111889. */
  111890. get: function () {
  111891. return this._captureGPUFrameTime;
  111892. },
  111893. /**
  111894. * Enable or disable the GPU frame time capture
  111895. */
  111896. set: function (value) {
  111897. var _this = this;
  111898. if (value === this._captureGPUFrameTime) {
  111899. return;
  111900. }
  111901. this._captureGPUFrameTime = value;
  111902. if (value) {
  111903. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  111904. if (!_this._gpuFrameTimeToken) {
  111905. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  111906. }
  111907. });
  111908. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  111909. if (!_this._gpuFrameTimeToken) {
  111910. return;
  111911. }
  111912. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  111913. if (time > -1) {
  111914. _this._gpuFrameTimeToken = null;
  111915. _this._gpuFrameTime.fetchNewFrame();
  111916. _this._gpuFrameTime.addCount(time, true);
  111917. }
  111918. });
  111919. }
  111920. else {
  111921. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  111922. this._onBeginFrameObserver = null;
  111923. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  111924. this._onEndFrameObserver = null;
  111925. }
  111926. },
  111927. enumerable: true,
  111928. configurable: true
  111929. });
  111930. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  111931. /**
  111932. * Gets the perf counter used for shader compilation time
  111933. */
  111934. get: function () {
  111935. return this._shaderCompilationTime;
  111936. },
  111937. enumerable: true,
  111938. configurable: true
  111939. });
  111940. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  111941. /**
  111942. * Gets the shader compilation time capture status
  111943. */
  111944. get: function () {
  111945. return this._captureShaderCompilationTime;
  111946. },
  111947. /**
  111948. * Enable or disable the shader compilation time capture
  111949. */
  111950. set: function (value) {
  111951. var _this = this;
  111952. if (value === this._captureShaderCompilationTime) {
  111953. return;
  111954. }
  111955. this._captureShaderCompilationTime = value;
  111956. if (value) {
  111957. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  111958. _this._shaderCompilationTime.fetchNewFrame();
  111959. _this._shaderCompilationTime.beginMonitoring();
  111960. });
  111961. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  111962. _this._shaderCompilationTime.endMonitoring();
  111963. });
  111964. }
  111965. else {
  111966. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  111967. this._onBeforeShaderCompilationObserver = null;
  111968. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  111969. this._onAfterShaderCompilationObserver = null;
  111970. }
  111971. },
  111972. enumerable: true,
  111973. configurable: true
  111974. });
  111975. /**
  111976. * Dispose and release associated resources.
  111977. */
  111978. EngineInstrumentation.prototype.dispose = function () {
  111979. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  111980. this._onBeginFrameObserver = null;
  111981. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  111982. this._onEndFrameObserver = null;
  111983. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  111984. this._onBeforeShaderCompilationObserver = null;
  111985. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  111986. this._onAfterShaderCompilationObserver = null;
  111987. this.engine = null;
  111988. };
  111989. return EngineInstrumentation;
  111990. }());
  111991. BABYLON.EngineInstrumentation = EngineInstrumentation;
  111992. })(BABYLON || (BABYLON = {}));
  111993. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  111994. var BABYLON;
  111995. (function (BABYLON) {
  111996. /**
  111997. * This class can be used to get instrumentation data from a Babylon engine
  111998. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  111999. */
  112000. var SceneInstrumentation = /** @class */ (function () {
  112001. /**
  112002. * Instantiates a new scene instrumentation.
  112003. * This class can be used to get instrumentation data from a Babylon engine
  112004. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  112005. * @param scene Defines the scene to instrument
  112006. */
  112007. function SceneInstrumentation(
  112008. /**
  112009. * Defines the scene to instrument
  112010. */
  112011. scene) {
  112012. var _this = this;
  112013. this.scene = scene;
  112014. this._captureActiveMeshesEvaluationTime = false;
  112015. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  112016. this._captureRenderTargetsRenderTime = false;
  112017. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  112018. this._captureFrameTime = false;
  112019. this._frameTime = new BABYLON.PerfCounter();
  112020. this._captureRenderTime = false;
  112021. this._renderTime = new BABYLON.PerfCounter();
  112022. this._captureInterFrameTime = false;
  112023. this._interFrameTime = new BABYLON.PerfCounter();
  112024. this._captureParticlesRenderTime = false;
  112025. this._particlesRenderTime = new BABYLON.PerfCounter();
  112026. this._captureSpritesRenderTime = false;
  112027. this._spritesRenderTime = new BABYLON.PerfCounter();
  112028. this._capturePhysicsTime = false;
  112029. this._physicsTime = new BABYLON.PerfCounter();
  112030. this._captureAnimationsTime = false;
  112031. this._animationsTime = new BABYLON.PerfCounter();
  112032. this._captureCameraRenderTime = false;
  112033. this._cameraRenderTime = new BABYLON.PerfCounter();
  112034. // Observers
  112035. this._onBeforeActiveMeshesEvaluationObserver = null;
  112036. this._onAfterActiveMeshesEvaluationObserver = null;
  112037. this._onBeforeRenderTargetsRenderObserver = null;
  112038. this._onAfterRenderTargetsRenderObserver = null;
  112039. this._onAfterRenderObserver = null;
  112040. this._onBeforeDrawPhaseObserver = null;
  112041. this._onAfterDrawPhaseObserver = null;
  112042. this._onBeforeAnimationsObserver = null;
  112043. this._onBeforeParticlesRenderingObserver = null;
  112044. this._onAfterParticlesRenderingObserver = null;
  112045. this._onBeforeSpritesRenderingObserver = null;
  112046. this._onAfterSpritesRenderingObserver = null;
  112047. this._onBeforePhysicsObserver = null;
  112048. this._onAfterPhysicsObserver = null;
  112049. this._onAfterAnimationsObserver = null;
  112050. this._onBeforeCameraRenderObserver = null;
  112051. this._onAfterCameraRenderObserver = null;
  112052. // Before render
  112053. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  112054. if (_this._captureActiveMeshesEvaluationTime) {
  112055. _this._activeMeshesEvaluationTime.fetchNewFrame();
  112056. }
  112057. if (_this._captureRenderTargetsRenderTime) {
  112058. _this._renderTargetsRenderTime.fetchNewFrame();
  112059. }
  112060. if (_this._captureFrameTime) {
  112061. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  112062. _this._frameTime.beginMonitoring();
  112063. }
  112064. if (_this._captureInterFrameTime) {
  112065. _this._interFrameTime.endMonitoring();
  112066. }
  112067. if (_this._captureParticlesRenderTime) {
  112068. _this._particlesRenderTime.fetchNewFrame();
  112069. }
  112070. if (_this._captureSpritesRenderTime) {
  112071. _this._spritesRenderTime.fetchNewFrame();
  112072. }
  112073. if (_this._captureAnimationsTime) {
  112074. _this._animationsTime.beginMonitoring();
  112075. }
  112076. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  112077. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  112078. });
  112079. // After render
  112080. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  112081. if (_this._captureFrameTime) {
  112082. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  112083. _this._frameTime.endMonitoring();
  112084. }
  112085. if (_this._captureRenderTime) {
  112086. _this._renderTime.endMonitoring(false);
  112087. }
  112088. if (_this._captureInterFrameTime) {
  112089. _this._interFrameTime.beginMonitoring();
  112090. }
  112091. });
  112092. }
  112093. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  112094. // Properties
  112095. /**
  112096. * Gets the perf counter used for active meshes evaluation time
  112097. */
  112098. get: function () {
  112099. return this._activeMeshesEvaluationTime;
  112100. },
  112101. enumerable: true,
  112102. configurable: true
  112103. });
  112104. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  112105. /**
  112106. * Gets the active meshes evaluation time capture status
  112107. */
  112108. get: function () {
  112109. return this._captureActiveMeshesEvaluationTime;
  112110. },
  112111. /**
  112112. * Enable or disable the active meshes evaluation time capture
  112113. */
  112114. set: function (value) {
  112115. var _this = this;
  112116. if (value === this._captureActiveMeshesEvaluationTime) {
  112117. return;
  112118. }
  112119. this._captureActiveMeshesEvaluationTime = value;
  112120. if (value) {
  112121. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  112122. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  112123. _this._activeMeshesEvaluationTime.beginMonitoring();
  112124. });
  112125. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  112126. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  112127. _this._activeMeshesEvaluationTime.endMonitoring();
  112128. });
  112129. }
  112130. else {
  112131. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  112132. this._onBeforeActiveMeshesEvaluationObserver = null;
  112133. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  112134. this._onAfterActiveMeshesEvaluationObserver = null;
  112135. }
  112136. },
  112137. enumerable: true,
  112138. configurable: true
  112139. });
  112140. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  112141. /**
  112142. * Gets the perf counter used for render targets render time
  112143. */
  112144. get: function () {
  112145. return this._renderTargetsRenderTime;
  112146. },
  112147. enumerable: true,
  112148. configurable: true
  112149. });
  112150. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  112151. /**
  112152. * Gets the render targets render time capture status
  112153. */
  112154. get: function () {
  112155. return this._captureRenderTargetsRenderTime;
  112156. },
  112157. /**
  112158. * Enable or disable the render targets render time capture
  112159. */
  112160. set: function (value) {
  112161. var _this = this;
  112162. if (value === this._captureRenderTargetsRenderTime) {
  112163. return;
  112164. }
  112165. this._captureRenderTargetsRenderTime = value;
  112166. if (value) {
  112167. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  112168. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  112169. _this._renderTargetsRenderTime.beginMonitoring();
  112170. });
  112171. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  112172. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  112173. _this._renderTargetsRenderTime.endMonitoring(false);
  112174. });
  112175. }
  112176. else {
  112177. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  112178. this._onBeforeRenderTargetsRenderObserver = null;
  112179. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  112180. this._onAfterRenderTargetsRenderObserver = null;
  112181. }
  112182. },
  112183. enumerable: true,
  112184. configurable: true
  112185. });
  112186. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  112187. /**
  112188. * Gets the perf counter used for particles render time
  112189. */
  112190. get: function () {
  112191. return this._particlesRenderTime;
  112192. },
  112193. enumerable: true,
  112194. configurable: true
  112195. });
  112196. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  112197. /**
  112198. * Gets the particles render time capture status
  112199. */
  112200. get: function () {
  112201. return this._captureParticlesRenderTime;
  112202. },
  112203. /**
  112204. * Enable or disable the particles render time capture
  112205. */
  112206. set: function (value) {
  112207. var _this = this;
  112208. if (value === this._captureParticlesRenderTime) {
  112209. return;
  112210. }
  112211. this._captureParticlesRenderTime = value;
  112212. if (value) {
  112213. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  112214. BABYLON.Tools.StartPerformanceCounter("Particles");
  112215. _this._particlesRenderTime.beginMonitoring();
  112216. });
  112217. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  112218. BABYLON.Tools.EndPerformanceCounter("Particles");
  112219. _this._particlesRenderTime.endMonitoring(false);
  112220. });
  112221. }
  112222. else {
  112223. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  112224. this._onBeforeParticlesRenderingObserver = null;
  112225. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  112226. this._onAfterParticlesRenderingObserver = null;
  112227. }
  112228. },
  112229. enumerable: true,
  112230. configurable: true
  112231. });
  112232. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  112233. /**
  112234. * Gets the perf counter used for sprites render time
  112235. */
  112236. get: function () {
  112237. return this._spritesRenderTime;
  112238. },
  112239. enumerable: true,
  112240. configurable: true
  112241. });
  112242. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  112243. /**
  112244. * Gets the sprites render time capture status
  112245. */
  112246. get: function () {
  112247. return this._captureSpritesRenderTime;
  112248. },
  112249. /**
  112250. * Enable or disable the sprites render time capture
  112251. */
  112252. set: function (value) {
  112253. var _this = this;
  112254. if (value === this._captureSpritesRenderTime) {
  112255. return;
  112256. }
  112257. this._captureSpritesRenderTime = value;
  112258. if (!this.scene.spriteManagers) {
  112259. return;
  112260. }
  112261. if (value) {
  112262. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  112263. BABYLON.Tools.StartPerformanceCounter("Sprites");
  112264. _this._spritesRenderTime.beginMonitoring();
  112265. });
  112266. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  112267. BABYLON.Tools.EndPerformanceCounter("Sprites");
  112268. _this._spritesRenderTime.endMonitoring(false);
  112269. });
  112270. }
  112271. else {
  112272. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  112273. this._onBeforeSpritesRenderingObserver = null;
  112274. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  112275. this._onAfterSpritesRenderingObserver = null;
  112276. }
  112277. },
  112278. enumerable: true,
  112279. configurable: true
  112280. });
  112281. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  112282. /**
  112283. * Gets the perf counter used for physics time
  112284. */
  112285. get: function () {
  112286. return this._physicsTime;
  112287. },
  112288. enumerable: true,
  112289. configurable: true
  112290. });
  112291. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  112292. /**
  112293. * Gets the physics time capture status
  112294. */
  112295. get: function () {
  112296. return this._capturePhysicsTime;
  112297. },
  112298. /**
  112299. * Enable or disable the physics time capture
  112300. */
  112301. set: function (value) {
  112302. var _this = this;
  112303. if (value === this._capturePhysicsTime) {
  112304. return;
  112305. }
  112306. if (!this.scene.onBeforePhysicsObservable) {
  112307. return;
  112308. }
  112309. this._capturePhysicsTime = value;
  112310. if (value) {
  112311. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  112312. BABYLON.Tools.StartPerformanceCounter("Physics");
  112313. _this._physicsTime.beginMonitoring();
  112314. });
  112315. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  112316. BABYLON.Tools.EndPerformanceCounter("Physics");
  112317. _this._physicsTime.endMonitoring();
  112318. });
  112319. }
  112320. else {
  112321. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  112322. this._onBeforePhysicsObserver = null;
  112323. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  112324. this._onAfterPhysicsObserver = null;
  112325. }
  112326. },
  112327. enumerable: true,
  112328. configurable: true
  112329. });
  112330. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  112331. /**
  112332. * Gets the perf counter used for animations time
  112333. */
  112334. get: function () {
  112335. return this._animationsTime;
  112336. },
  112337. enumerable: true,
  112338. configurable: true
  112339. });
  112340. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  112341. /**
  112342. * Gets the animations time capture status
  112343. */
  112344. get: function () {
  112345. return this._captureAnimationsTime;
  112346. },
  112347. /**
  112348. * Enable or disable the animations time capture
  112349. */
  112350. set: function (value) {
  112351. var _this = this;
  112352. if (value === this._captureAnimationsTime) {
  112353. return;
  112354. }
  112355. this._captureAnimationsTime = value;
  112356. if (value) {
  112357. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  112358. _this._animationsTime.endMonitoring();
  112359. });
  112360. }
  112361. else {
  112362. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  112363. this._onAfterAnimationsObserver = null;
  112364. }
  112365. },
  112366. enumerable: true,
  112367. configurable: true
  112368. });
  112369. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  112370. /**
  112371. * Gets the perf counter used for frame time capture
  112372. */
  112373. get: function () {
  112374. return this._frameTime;
  112375. },
  112376. enumerable: true,
  112377. configurable: true
  112378. });
  112379. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  112380. /**
  112381. * Gets the frame time capture status
  112382. */
  112383. get: function () {
  112384. return this._captureFrameTime;
  112385. },
  112386. /**
  112387. * Enable or disable the frame time capture
  112388. */
  112389. set: function (value) {
  112390. this._captureFrameTime = value;
  112391. },
  112392. enumerable: true,
  112393. configurable: true
  112394. });
  112395. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  112396. /**
  112397. * Gets the perf counter used for inter-frames time capture
  112398. */
  112399. get: function () {
  112400. return this._interFrameTime;
  112401. },
  112402. enumerable: true,
  112403. configurable: true
  112404. });
  112405. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  112406. /**
  112407. * Gets the inter-frames time capture status
  112408. */
  112409. get: function () {
  112410. return this._captureInterFrameTime;
  112411. },
  112412. /**
  112413. * Enable or disable the inter-frames time capture
  112414. */
  112415. set: function (value) {
  112416. this._captureInterFrameTime = value;
  112417. },
  112418. enumerable: true,
  112419. configurable: true
  112420. });
  112421. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  112422. /**
  112423. * Gets the perf counter used for render time capture
  112424. */
  112425. get: function () {
  112426. return this._renderTime;
  112427. },
  112428. enumerable: true,
  112429. configurable: true
  112430. });
  112431. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  112432. /**
  112433. * Gets the render time capture status
  112434. */
  112435. get: function () {
  112436. return this._captureRenderTime;
  112437. },
  112438. /**
  112439. * Enable or disable the render time capture
  112440. */
  112441. set: function (value) {
  112442. var _this = this;
  112443. if (value === this._captureRenderTime) {
  112444. return;
  112445. }
  112446. this._captureRenderTime = value;
  112447. if (value) {
  112448. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  112449. _this._renderTime.beginMonitoring();
  112450. BABYLON.Tools.StartPerformanceCounter("Main render");
  112451. });
  112452. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  112453. _this._renderTime.endMonitoring(false);
  112454. BABYLON.Tools.EndPerformanceCounter("Main render");
  112455. });
  112456. }
  112457. else {
  112458. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  112459. this._onBeforeDrawPhaseObserver = null;
  112460. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  112461. this._onAfterDrawPhaseObserver = null;
  112462. }
  112463. },
  112464. enumerable: true,
  112465. configurable: true
  112466. });
  112467. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  112468. /**
  112469. * Gets the perf counter used for camera render time capture
  112470. */
  112471. get: function () {
  112472. return this._cameraRenderTime;
  112473. },
  112474. enumerable: true,
  112475. configurable: true
  112476. });
  112477. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  112478. /**
  112479. * Gets the camera render time capture status
  112480. */
  112481. get: function () {
  112482. return this._captureCameraRenderTime;
  112483. },
  112484. /**
  112485. * Enable or disable the camera render time capture
  112486. */
  112487. set: function (value) {
  112488. var _this = this;
  112489. if (value === this._captureCameraRenderTime) {
  112490. return;
  112491. }
  112492. this._captureCameraRenderTime = value;
  112493. if (value) {
  112494. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  112495. _this._cameraRenderTime.beginMonitoring();
  112496. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  112497. });
  112498. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  112499. _this._cameraRenderTime.endMonitoring(false);
  112500. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  112501. });
  112502. }
  112503. else {
  112504. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  112505. this._onBeforeCameraRenderObserver = null;
  112506. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  112507. this._onAfterCameraRenderObserver = null;
  112508. }
  112509. },
  112510. enumerable: true,
  112511. configurable: true
  112512. });
  112513. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  112514. /**
  112515. * Gets the perf counter used for draw calls
  112516. */
  112517. get: function () {
  112518. return this.scene.getEngine()._drawCalls;
  112519. },
  112520. enumerable: true,
  112521. configurable: true
  112522. });
  112523. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  112524. /**
  112525. * Gets the perf counter used for texture collisions
  112526. */
  112527. get: function () {
  112528. return this.scene.getEngine()._textureCollisions;
  112529. },
  112530. enumerable: true,
  112531. configurable: true
  112532. });
  112533. /**
  112534. * Dispose and release associated resources.
  112535. */
  112536. SceneInstrumentation.prototype.dispose = function () {
  112537. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  112538. this._onAfterRenderObserver = null;
  112539. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  112540. this._onBeforeActiveMeshesEvaluationObserver = null;
  112541. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  112542. this._onAfterActiveMeshesEvaluationObserver = null;
  112543. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  112544. this._onBeforeRenderTargetsRenderObserver = null;
  112545. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  112546. this._onAfterRenderTargetsRenderObserver = null;
  112547. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  112548. this._onBeforeAnimationsObserver = null;
  112549. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  112550. this._onBeforeParticlesRenderingObserver = null;
  112551. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  112552. this._onAfterParticlesRenderingObserver = null;
  112553. if (this._onBeforeSpritesRenderingObserver) {
  112554. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  112555. this._onBeforeSpritesRenderingObserver = null;
  112556. }
  112557. if (this._onAfterSpritesRenderingObserver) {
  112558. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  112559. this._onAfterSpritesRenderingObserver = null;
  112560. }
  112561. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  112562. this._onBeforeDrawPhaseObserver = null;
  112563. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  112564. this._onAfterDrawPhaseObserver = null;
  112565. if (this._onBeforePhysicsObserver) {
  112566. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  112567. this._onBeforePhysicsObserver = null;
  112568. }
  112569. if (this._onAfterPhysicsObserver) {
  112570. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  112571. this._onAfterPhysicsObserver = null;
  112572. }
  112573. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  112574. this._onAfterAnimationsObserver = null;
  112575. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  112576. this._onBeforeCameraRenderObserver = null;
  112577. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  112578. this._onAfterCameraRenderObserver = null;
  112579. this.scene = null;
  112580. };
  112581. return SceneInstrumentation;
  112582. }());
  112583. BABYLON.SceneInstrumentation = SceneInstrumentation;
  112584. })(BABYLON || (BABYLON = {}));
  112585. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  112586. var BABYLON;
  112587. (function (BABYLON) {
  112588. /**
  112589. * @hidden
  112590. **/
  112591. var _TimeToken = /** @class */ (function () {
  112592. function _TimeToken() {
  112593. this._timeElapsedQueryEnded = false;
  112594. }
  112595. return _TimeToken;
  112596. }());
  112597. BABYLON._TimeToken = _TimeToken;
  112598. })(BABYLON || (BABYLON = {}));
  112599. //# sourceMappingURL=babylon.timeToken.js.map
  112600. var BABYLON;
  112601. (function (BABYLON) {
  112602. /**
  112603. * Background material defines definition.
  112604. * @hidden Mainly internal Use
  112605. */
  112606. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  112607. __extends(BackgroundMaterialDefines, _super);
  112608. /**
  112609. * Constructor of the defines.
  112610. */
  112611. function BackgroundMaterialDefines() {
  112612. var _this = _super.call(this) || this;
  112613. /**
  112614. * True if the diffuse texture is in use.
  112615. */
  112616. _this.DIFFUSE = false;
  112617. /**
  112618. * The direct UV channel to use.
  112619. */
  112620. _this.DIFFUSEDIRECTUV = 0;
  112621. /**
  112622. * True if the diffuse texture is in gamma space.
  112623. */
  112624. _this.GAMMADIFFUSE = false;
  112625. /**
  112626. * True if the diffuse texture has opacity in the alpha channel.
  112627. */
  112628. _this.DIFFUSEHASALPHA = false;
  112629. /**
  112630. * True if you want the material to fade to transparent at grazing angle.
  112631. */
  112632. _this.OPACITYFRESNEL = false;
  112633. /**
  112634. * True if an extra blur needs to be added in the reflection.
  112635. */
  112636. _this.REFLECTIONBLUR = false;
  112637. /**
  112638. * True if you want the material to fade to reflection at grazing angle.
  112639. */
  112640. _this.REFLECTIONFRESNEL = false;
  112641. /**
  112642. * True if you want the material to falloff as far as you move away from the scene center.
  112643. */
  112644. _this.REFLECTIONFALLOFF = false;
  112645. /**
  112646. * False if the current Webgl implementation does not support the texture lod extension.
  112647. */
  112648. _this.TEXTURELODSUPPORT = false;
  112649. /**
  112650. * True to ensure the data are premultiplied.
  112651. */
  112652. _this.PREMULTIPLYALPHA = false;
  112653. /**
  112654. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  112655. */
  112656. _this.USERGBCOLOR = false;
  112657. /**
  112658. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  112659. * stays aligned with the desired configuration.
  112660. */
  112661. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  112662. /**
  112663. * True to add noise in order to reduce the banding effect.
  112664. */
  112665. _this.NOISE = false;
  112666. /**
  112667. * is the reflection texture in BGR color scheme?
  112668. * Mainly used to solve a bug in ios10 video tag
  112669. */
  112670. _this.REFLECTIONBGR = false;
  112671. _this.IMAGEPROCESSING = false;
  112672. _this.VIGNETTE = false;
  112673. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  112674. _this.VIGNETTEBLENDMODEOPAQUE = false;
  112675. _this.TONEMAPPING = false;
  112676. _this.TONEMAPPING_ACES = false;
  112677. _this.CONTRAST = false;
  112678. _this.COLORCURVES = false;
  112679. _this.COLORGRADING = false;
  112680. _this.COLORGRADING3D = false;
  112681. _this.SAMPLER3DGREENDEPTH = false;
  112682. _this.SAMPLER3DBGRMAP = false;
  112683. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  112684. _this.EXPOSURE = false;
  112685. // Reflection.
  112686. _this.REFLECTION = false;
  112687. _this.REFLECTIONMAP_3D = false;
  112688. _this.REFLECTIONMAP_SPHERICAL = false;
  112689. _this.REFLECTIONMAP_PLANAR = false;
  112690. _this.REFLECTIONMAP_CUBIC = false;
  112691. _this.REFLECTIONMAP_PROJECTION = false;
  112692. _this.REFLECTIONMAP_SKYBOX = false;
  112693. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  112694. _this.REFLECTIONMAP_EXPLICIT = false;
  112695. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  112696. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  112697. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  112698. _this.INVERTCUBICMAP = false;
  112699. _this.REFLECTIONMAP_OPPOSITEZ = false;
  112700. _this.LODINREFLECTIONALPHA = false;
  112701. _this.GAMMAREFLECTION = false;
  112702. _this.RGBDREFLECTION = false;
  112703. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  112704. // Default BJS.
  112705. _this.MAINUV1 = false;
  112706. _this.MAINUV2 = false;
  112707. _this.UV1 = false;
  112708. _this.UV2 = false;
  112709. _this.CLIPPLANE = false;
  112710. _this.CLIPPLANE2 = false;
  112711. _this.CLIPPLANE3 = false;
  112712. _this.CLIPPLANE4 = false;
  112713. _this.POINTSIZE = false;
  112714. _this.FOG = false;
  112715. _this.NORMAL = false;
  112716. _this.NUM_BONE_INFLUENCERS = 0;
  112717. _this.BonesPerMesh = 0;
  112718. _this.INSTANCES = false;
  112719. _this.SHADOWFLOAT = false;
  112720. _this.rebuild();
  112721. return _this;
  112722. }
  112723. return BackgroundMaterialDefines;
  112724. }(BABYLON.MaterialDefines));
  112725. /**
  112726. * Background material used to create an efficient environement around your scene.
  112727. */
  112728. var BackgroundMaterial = /** @class */ (function (_super) {
  112729. __extends(BackgroundMaterial, _super);
  112730. /**
  112731. * Instantiates a Background Material in the given scene
  112732. * @param name The friendly name of the material
  112733. * @param scene The scene to add the material to
  112734. */
  112735. function BackgroundMaterial(name, scene) {
  112736. var _this = _super.call(this, name, scene) || this;
  112737. /**
  112738. * Key light Color (multiply against the environement texture)
  112739. */
  112740. _this.primaryColor = BABYLON.Color3.White();
  112741. _this._primaryColorShadowLevel = 0;
  112742. _this._primaryColorHighlightLevel = 0;
  112743. /**
  112744. * Reflection Texture used in the material.
  112745. * Should be author in a specific way for the best result (refer to the documentation).
  112746. */
  112747. _this.reflectionTexture = null;
  112748. /**
  112749. * Reflection Texture level of blur.
  112750. *
  112751. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  112752. * texture twice.
  112753. */
  112754. _this.reflectionBlur = 0;
  112755. /**
  112756. * Diffuse Texture used in the material.
  112757. * Should be author in a specific way for the best result (refer to the documentation).
  112758. */
  112759. _this.diffuseTexture = null;
  112760. _this._shadowLights = null;
  112761. /**
  112762. * Specify the list of lights casting shadow on the material.
  112763. * All scene shadow lights will be included if null.
  112764. */
  112765. _this.shadowLights = null;
  112766. /**
  112767. * Helps adjusting the shadow to a softer level if required.
  112768. * 0 means black shadows and 1 means no shadows.
  112769. */
  112770. _this.shadowLevel = 0;
  112771. /**
  112772. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  112773. * It is usually zero but might be interesting to modify according to your setup.
  112774. */
  112775. _this.sceneCenter = BABYLON.Vector3.Zero();
  112776. /**
  112777. * This helps specifying that the material is falling off to the sky box at grazing angle.
  112778. * This helps ensuring a nice transition when the camera goes under the ground.
  112779. */
  112780. _this.opacityFresnel = true;
  112781. /**
  112782. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  112783. * This helps adding a mirror texture on the ground.
  112784. */
  112785. _this.reflectionFresnel = false;
  112786. /**
  112787. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  112788. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  112789. */
  112790. _this.reflectionFalloffDistance = 0.0;
  112791. /**
  112792. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  112793. */
  112794. _this.reflectionAmount = 1.0;
  112795. /**
  112796. * This specifies the weight of the reflection at grazing angle.
  112797. */
  112798. _this.reflectionReflectance0 = 0.05;
  112799. /**
  112800. * This specifies the weight of the reflection at a perpendicular point of view.
  112801. */
  112802. _this.reflectionReflectance90 = 0.5;
  112803. /**
  112804. * Helps to directly use the maps channels instead of their level.
  112805. */
  112806. _this.useRGBColor = true;
  112807. /**
  112808. * This helps reducing the banding effect that could occur on the background.
  112809. */
  112810. _this.enableNoise = false;
  112811. _this._fovMultiplier = 1.0;
  112812. /**
  112813. * Enable the FOV adjustment feature controlled by fovMultiplier.
  112814. */
  112815. _this.useEquirectangularFOV = false;
  112816. _this._maxSimultaneousLights = 4;
  112817. /**
  112818. * Number of Simultaneous lights allowed on the material.
  112819. */
  112820. _this.maxSimultaneousLights = 4;
  112821. /**
  112822. * Keep track of the image processing observer to allow dispose and replace.
  112823. */
  112824. _this._imageProcessingObserver = null;
  112825. /**
  112826. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  112827. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  112828. */
  112829. _this.switchToBGR = false;
  112830. // Temp values kept as cache in the material.
  112831. _this._renderTargets = new BABYLON.SmartArray(16);
  112832. _this._reflectionControls = BABYLON.Vector4.Zero();
  112833. _this._white = BABYLON.Color3.White();
  112834. _this._primaryShadowColor = BABYLON.Color3.Black();
  112835. _this._primaryHighlightColor = BABYLON.Color3.Black();
  112836. // Setup the default processing configuration to the scene.
  112837. _this._attachImageProcessingConfiguration(null);
  112838. _this.getRenderTargetTextures = function () {
  112839. _this._renderTargets.reset();
  112840. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  112841. _this._renderTargets.push(_this._diffuseTexture);
  112842. }
  112843. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  112844. _this._renderTargets.push(_this._reflectionTexture);
  112845. }
  112846. return _this._renderTargets;
  112847. };
  112848. return _this;
  112849. }
  112850. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  112851. /**
  112852. * Experimental Internal Use Only.
  112853. *
  112854. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  112855. * This acts as a helper to set the primary color to a more "human friendly" value.
  112856. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  112857. * output color as close as possible from the chosen value.
  112858. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  112859. * part of lighting setup.)
  112860. */
  112861. get: function () {
  112862. return this.__perceptualColor;
  112863. },
  112864. set: function (value) {
  112865. this.__perceptualColor = value;
  112866. this._computePrimaryColorFromPerceptualColor();
  112867. this._markAllSubMeshesAsLightsDirty();
  112868. },
  112869. enumerable: true,
  112870. configurable: true
  112871. });
  112872. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  112873. /**
  112874. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  112875. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  112876. */
  112877. get: function () {
  112878. return this._primaryColorShadowLevel;
  112879. },
  112880. set: function (value) {
  112881. this._primaryColorShadowLevel = value;
  112882. this._computePrimaryColors();
  112883. this._markAllSubMeshesAsLightsDirty();
  112884. },
  112885. enumerable: true,
  112886. configurable: true
  112887. });
  112888. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  112889. /**
  112890. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  112891. * The primary color is used at the level chosen to define what the white area would look.
  112892. */
  112893. get: function () {
  112894. return this._primaryColorHighlightLevel;
  112895. },
  112896. set: function (value) {
  112897. this._primaryColorHighlightLevel = value;
  112898. this._computePrimaryColors();
  112899. this._markAllSubMeshesAsLightsDirty();
  112900. },
  112901. enumerable: true,
  112902. configurable: true
  112903. });
  112904. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  112905. /**
  112906. * Sets the reflection reflectance fresnel values according to the default standard
  112907. * empirically know to work well :-)
  112908. */
  112909. set: function (value) {
  112910. var reflectionWeight = value;
  112911. if (reflectionWeight < 0.5) {
  112912. reflectionWeight = reflectionWeight * 2.0;
  112913. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  112914. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  112915. }
  112916. else {
  112917. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  112918. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  112919. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  112920. }
  112921. },
  112922. enumerable: true,
  112923. configurable: true
  112924. });
  112925. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  112926. /**
  112927. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  112928. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  112929. * Recommended to be keep at 1.0 except for special cases.
  112930. */
  112931. get: function () {
  112932. return this._fovMultiplier;
  112933. },
  112934. set: function (value) {
  112935. if (isNaN(value)) {
  112936. value = 1.0;
  112937. }
  112938. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  112939. },
  112940. enumerable: true,
  112941. configurable: true
  112942. });
  112943. /**
  112944. * Attaches a new image processing configuration to the PBR Material.
  112945. * @param configuration (if null the scene configuration will be use)
  112946. */
  112947. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  112948. var _this = this;
  112949. if (configuration === this._imageProcessingConfiguration) {
  112950. return;
  112951. }
  112952. // Detaches observer.
  112953. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  112954. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  112955. }
  112956. // Pick the scene configuration if needed.
  112957. if (!configuration) {
  112958. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  112959. }
  112960. else {
  112961. this._imageProcessingConfiguration = configuration;
  112962. }
  112963. // Attaches observer.
  112964. if (this._imageProcessingConfiguration) {
  112965. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  112966. _this._computePrimaryColorFromPerceptualColor();
  112967. _this._markAllSubMeshesAsImageProcessingDirty();
  112968. });
  112969. }
  112970. };
  112971. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  112972. /**
  112973. * Gets the image processing configuration used either in this material.
  112974. */
  112975. get: function () {
  112976. return this._imageProcessingConfiguration;
  112977. },
  112978. /**
  112979. * Sets the Default image processing configuration used either in the this material.
  112980. *
  112981. * If sets to null, the scene one is in use.
  112982. */
  112983. set: function (value) {
  112984. this._attachImageProcessingConfiguration(value);
  112985. // Ensure the effect will be rebuilt.
  112986. this._markAllSubMeshesAsTexturesDirty();
  112987. },
  112988. enumerable: true,
  112989. configurable: true
  112990. });
  112991. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  112992. /**
  112993. * Gets wether the color curves effect is enabled.
  112994. */
  112995. get: function () {
  112996. return this.imageProcessingConfiguration.colorCurvesEnabled;
  112997. },
  112998. /**
  112999. * Sets wether the color curves effect is enabled.
  113000. */
  113001. set: function (value) {
  113002. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  113003. },
  113004. enumerable: true,
  113005. configurable: true
  113006. });
  113007. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  113008. /**
  113009. * Gets wether the color grading effect is enabled.
  113010. */
  113011. get: function () {
  113012. return this.imageProcessingConfiguration.colorGradingEnabled;
  113013. },
  113014. /**
  113015. * Gets wether the color grading effect is enabled.
  113016. */
  113017. set: function (value) {
  113018. this.imageProcessingConfiguration.colorGradingEnabled = value;
  113019. },
  113020. enumerable: true,
  113021. configurable: true
  113022. });
  113023. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  113024. /**
  113025. * Gets wether tonemapping is enabled or not.
  113026. */
  113027. get: function () {
  113028. return this._imageProcessingConfiguration.toneMappingEnabled;
  113029. },
  113030. /**
  113031. * Sets wether tonemapping is enabled or not
  113032. */
  113033. set: function (value) {
  113034. this._imageProcessingConfiguration.toneMappingEnabled = value;
  113035. },
  113036. enumerable: true,
  113037. configurable: true
  113038. });
  113039. ;
  113040. ;
  113041. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  113042. /**
  113043. * The camera exposure used on this material.
  113044. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  113045. * This corresponds to a photographic exposure.
  113046. */
  113047. get: function () {
  113048. return this._imageProcessingConfiguration.exposure;
  113049. },
  113050. /**
  113051. * The camera exposure used on this material.
  113052. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  113053. * This corresponds to a photographic exposure.
  113054. */
  113055. set: function (value) {
  113056. this._imageProcessingConfiguration.exposure = value;
  113057. },
  113058. enumerable: true,
  113059. configurable: true
  113060. });
  113061. ;
  113062. ;
  113063. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  113064. /**
  113065. * Gets The camera contrast used on this material.
  113066. */
  113067. get: function () {
  113068. return this._imageProcessingConfiguration.contrast;
  113069. },
  113070. /**
  113071. * Sets The camera contrast used on this material.
  113072. */
  113073. set: function (value) {
  113074. this._imageProcessingConfiguration.contrast = value;
  113075. },
  113076. enumerable: true,
  113077. configurable: true
  113078. });
  113079. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  113080. /**
  113081. * Gets the Color Grading 2D Lookup Texture.
  113082. */
  113083. get: function () {
  113084. return this._imageProcessingConfiguration.colorGradingTexture;
  113085. },
  113086. /**
  113087. * Sets the Color Grading 2D Lookup Texture.
  113088. */
  113089. set: function (value) {
  113090. this.imageProcessingConfiguration.colorGradingTexture = value;
  113091. },
  113092. enumerable: true,
  113093. configurable: true
  113094. });
  113095. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  113096. /**
  113097. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  113098. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  113099. * 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;
  113100. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  113101. */
  113102. get: function () {
  113103. return this.imageProcessingConfiguration.colorCurves;
  113104. },
  113105. /**
  113106. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  113107. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  113108. * 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;
  113109. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  113110. */
  113111. set: function (value) {
  113112. this.imageProcessingConfiguration.colorCurves = value;
  113113. },
  113114. enumerable: true,
  113115. configurable: true
  113116. });
  113117. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  113118. /**
  113119. * Gets a boolean indicating that current material needs to register RTT
  113120. */
  113121. get: function () {
  113122. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  113123. return true;
  113124. }
  113125. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  113126. return true;
  113127. }
  113128. return false;
  113129. },
  113130. enumerable: true,
  113131. configurable: true
  113132. });
  113133. /**
  113134. * The entire material has been created in order to prevent overdraw.
  113135. * @returns false
  113136. */
  113137. BackgroundMaterial.prototype.needAlphaTesting = function () {
  113138. return true;
  113139. };
  113140. /**
  113141. * The entire material has been created in order to prevent overdraw.
  113142. * @returns true if blending is enable
  113143. */
  113144. BackgroundMaterial.prototype.needAlphaBlending = function () {
  113145. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  113146. };
  113147. /**
  113148. * Checks wether the material is ready to be rendered for a given mesh.
  113149. * @param mesh The mesh to render
  113150. * @param subMesh The submesh to check against
  113151. * @param useInstances Specify wether or not the material is used with instances
  113152. * @returns true if all the dependencies are ready (Textures, Effects...)
  113153. */
  113154. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  113155. var _this = this;
  113156. if (useInstances === void 0) { useInstances = false; }
  113157. if (subMesh.effect && this.isFrozen) {
  113158. if (this._wasPreviouslyReady) {
  113159. return true;
  113160. }
  113161. }
  113162. if (!subMesh._materialDefines) {
  113163. subMesh._materialDefines = new BackgroundMaterialDefines();
  113164. }
  113165. var scene = this.getScene();
  113166. var defines = subMesh._materialDefines;
  113167. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  113168. if (defines._renderId === scene.getRenderId()) {
  113169. return true;
  113170. }
  113171. }
  113172. var engine = scene.getEngine();
  113173. // Lights
  113174. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  113175. defines._needNormals = true;
  113176. // Textures
  113177. if (defines._areTexturesDirty) {
  113178. defines._needUVs = false;
  113179. if (scene.texturesEnabled) {
  113180. if (scene.getEngine().getCaps().textureLOD) {
  113181. defines.TEXTURELODSUPPORT = true;
  113182. }
  113183. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  113184. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  113185. return false;
  113186. }
  113187. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  113188. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  113189. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  113190. defines.OPACITYFRESNEL = this._opacityFresnel;
  113191. }
  113192. else {
  113193. defines.DIFFUSE = false;
  113194. defines.DIFFUSEHASALPHA = false;
  113195. defines.GAMMADIFFUSE = false;
  113196. defines.OPACITYFRESNEL = false;
  113197. }
  113198. var reflectionTexture = this._reflectionTexture;
  113199. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  113200. if (!reflectionTexture.isReadyOrNotBlocking()) {
  113201. return false;
  113202. }
  113203. defines.REFLECTION = true;
  113204. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  113205. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  113206. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  113207. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  113208. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  113209. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  113210. defines.REFLECTIONBGR = this.switchToBGR;
  113211. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  113212. defines.INVERTCUBICMAP = true;
  113213. }
  113214. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  113215. switch (reflectionTexture.coordinatesMode) {
  113216. case BABYLON.Texture.EXPLICIT_MODE:
  113217. defines.REFLECTIONMAP_EXPLICIT = true;
  113218. break;
  113219. case BABYLON.Texture.PLANAR_MODE:
  113220. defines.REFLECTIONMAP_PLANAR = true;
  113221. break;
  113222. case BABYLON.Texture.PROJECTION_MODE:
  113223. defines.REFLECTIONMAP_PROJECTION = true;
  113224. break;
  113225. case BABYLON.Texture.SKYBOX_MODE:
  113226. defines.REFLECTIONMAP_SKYBOX = true;
  113227. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  113228. break;
  113229. case BABYLON.Texture.SPHERICAL_MODE:
  113230. defines.REFLECTIONMAP_SPHERICAL = true;
  113231. break;
  113232. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  113233. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  113234. break;
  113235. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  113236. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  113237. break;
  113238. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  113239. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  113240. break;
  113241. case BABYLON.Texture.CUBIC_MODE:
  113242. case BABYLON.Texture.INVCUBIC_MODE:
  113243. default:
  113244. defines.REFLECTIONMAP_CUBIC = true;
  113245. break;
  113246. }
  113247. if (this.reflectionFresnel) {
  113248. defines.REFLECTIONFRESNEL = true;
  113249. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  113250. this._reflectionControls.x = this.reflectionAmount;
  113251. this._reflectionControls.y = this.reflectionReflectance0;
  113252. this._reflectionControls.z = this.reflectionReflectance90;
  113253. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  113254. }
  113255. else {
  113256. defines.REFLECTIONFRESNEL = false;
  113257. defines.REFLECTIONFALLOFF = false;
  113258. }
  113259. }
  113260. else {
  113261. defines.REFLECTION = false;
  113262. defines.REFLECTIONFRESNEL = false;
  113263. defines.REFLECTIONFALLOFF = false;
  113264. defines.REFLECTIONBLUR = false;
  113265. defines.REFLECTIONMAP_3D = false;
  113266. defines.REFLECTIONMAP_SPHERICAL = false;
  113267. defines.REFLECTIONMAP_PLANAR = false;
  113268. defines.REFLECTIONMAP_CUBIC = false;
  113269. defines.REFLECTIONMAP_PROJECTION = false;
  113270. defines.REFLECTIONMAP_SKYBOX = false;
  113271. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  113272. defines.REFLECTIONMAP_EXPLICIT = false;
  113273. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  113274. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  113275. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  113276. defines.INVERTCUBICMAP = false;
  113277. defines.REFLECTIONMAP_OPPOSITEZ = false;
  113278. defines.LODINREFLECTIONALPHA = false;
  113279. defines.GAMMAREFLECTION = false;
  113280. defines.RGBDREFLECTION = false;
  113281. }
  113282. }
  113283. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  113284. defines.USERGBCOLOR = this._useRGBColor;
  113285. defines.NOISE = this._enableNoise;
  113286. }
  113287. if (defines._areLightsDirty) {
  113288. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  113289. }
  113290. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  113291. if (!this._imageProcessingConfiguration.isReady()) {
  113292. return false;
  113293. }
  113294. this._imageProcessingConfiguration.prepareDefines(defines);
  113295. }
  113296. // Misc.
  113297. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  113298. // Values that need to be evaluated on every frame
  113299. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  113300. // Attribs
  113301. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  113302. if (mesh) {
  113303. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  113304. mesh.createNormals(true);
  113305. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  113306. }
  113307. }
  113308. }
  113309. // Get correct effect
  113310. if (defines.isDirty) {
  113311. defines.markAsProcessed();
  113312. scene.resetCachedMaterial();
  113313. // Fallbacks
  113314. var fallbacks = new BABYLON.EffectFallbacks();
  113315. if (defines.FOG) {
  113316. fallbacks.addFallback(0, "FOG");
  113317. }
  113318. if (defines.POINTSIZE) {
  113319. fallbacks.addFallback(1, "POINTSIZE");
  113320. }
  113321. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  113322. if (defines.NUM_BONE_INFLUENCERS > 0) {
  113323. fallbacks.addCPUSkinningFallback(0, mesh);
  113324. }
  113325. //Attributes
  113326. var attribs = [BABYLON.VertexBuffer.PositionKind];
  113327. if (defines.NORMAL) {
  113328. attribs.push(BABYLON.VertexBuffer.NormalKind);
  113329. }
  113330. if (defines.UV1) {
  113331. attribs.push(BABYLON.VertexBuffer.UVKind);
  113332. }
  113333. if (defines.UV2) {
  113334. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  113335. }
  113336. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  113337. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  113338. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  113339. "vFogInfos", "vFogColor", "pointSize",
  113340. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  113341. "vPrimaryColor", "vPrimaryColorShadow",
  113342. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  113343. "shadowLevel", "alpha",
  113344. "vBackgroundCenter", "vReflectionControl",
  113345. "vDiffuseInfos", "diffuseMatrix",
  113346. ];
  113347. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  113348. var uniformBuffers = ["Material", "Scene"];
  113349. if (BABYLON.ImageProcessingConfiguration) {
  113350. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  113351. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  113352. }
  113353. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  113354. uniformsNames: uniforms,
  113355. uniformBuffersNames: uniformBuffers,
  113356. samplers: samplers,
  113357. defines: defines,
  113358. maxSimultaneousLights: this._maxSimultaneousLights
  113359. });
  113360. var onCompiled = function (effect) {
  113361. if (_this.onCompiled) {
  113362. _this.onCompiled(effect);
  113363. }
  113364. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  113365. };
  113366. var join = defines.toString();
  113367. subMesh.setEffect(scene.getEngine().createEffect("background", {
  113368. attributes: attribs,
  113369. uniformsNames: uniforms,
  113370. uniformBuffersNames: uniformBuffers,
  113371. samplers: samplers,
  113372. defines: join,
  113373. fallbacks: fallbacks,
  113374. onCompiled: onCompiled,
  113375. onError: this.onError,
  113376. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  113377. }, engine), defines);
  113378. this.buildUniformLayout();
  113379. }
  113380. if (!subMesh.effect || !subMesh.effect.isReady()) {
  113381. return false;
  113382. }
  113383. defines._renderId = scene.getRenderId();
  113384. this._wasPreviouslyReady = true;
  113385. return true;
  113386. };
  113387. /**
  113388. * Compute the primary color according to the chosen perceptual color.
  113389. */
  113390. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  113391. if (!this.__perceptualColor) {
  113392. return;
  113393. }
  113394. this._primaryColor.copyFrom(this.__perceptualColor);
  113395. // Revert gamma space.
  113396. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  113397. // Revert image processing configuration.
  113398. if (this._imageProcessingConfiguration) {
  113399. // Revert Exposure.
  113400. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  113401. }
  113402. this._computePrimaryColors();
  113403. };
  113404. /**
  113405. * Compute the highlights and shadow colors according to their chosen levels.
  113406. */
  113407. BackgroundMaterial.prototype._computePrimaryColors = function () {
  113408. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  113409. return;
  113410. }
  113411. // Find the highlight color based on the configuration.
  113412. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  113413. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  113414. // Find the shadow color based on the configuration.
  113415. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  113416. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  113417. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  113418. };
  113419. /**
  113420. * Build the uniform buffer used in the material.
  113421. */
  113422. BackgroundMaterial.prototype.buildUniformLayout = function () {
  113423. // Order is important !
  113424. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  113425. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  113426. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  113427. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  113428. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  113429. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  113430. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  113431. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  113432. this._uniformBuffer.addUniform("pointSize", 1);
  113433. this._uniformBuffer.addUniform("shadowLevel", 1);
  113434. this._uniformBuffer.addUniform("alpha", 1);
  113435. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  113436. this._uniformBuffer.addUniform("vReflectionControl", 4);
  113437. this._uniformBuffer.create();
  113438. };
  113439. /**
  113440. * Unbind the material.
  113441. */
  113442. BackgroundMaterial.prototype.unbind = function () {
  113443. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  113444. this._uniformBuffer.setTexture("diffuseSampler", null);
  113445. }
  113446. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  113447. this._uniformBuffer.setTexture("reflectionSampler", null);
  113448. }
  113449. _super.prototype.unbind.call(this);
  113450. };
  113451. /**
  113452. * Bind only the world matrix to the material.
  113453. * @param world The world matrix to bind.
  113454. */
  113455. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  113456. this._activeEffect.setMatrix("world", world);
  113457. };
  113458. /**
  113459. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  113460. * @param world The world matrix to bind.
  113461. * @param subMesh The submesh to bind for.
  113462. */
  113463. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  113464. var scene = this.getScene();
  113465. var defines = subMesh._materialDefines;
  113466. if (!defines) {
  113467. return;
  113468. }
  113469. var effect = subMesh.effect;
  113470. if (!effect) {
  113471. return;
  113472. }
  113473. this._activeEffect = effect;
  113474. // Matrices
  113475. this.bindOnlyWorldMatrix(world);
  113476. // Bones
  113477. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  113478. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  113479. if (mustRebind) {
  113480. this._uniformBuffer.bindToEffect(effect, "Material");
  113481. this.bindViewProjection(effect);
  113482. var reflectionTexture = this._reflectionTexture;
  113483. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  113484. // Texture uniforms
  113485. if (scene.texturesEnabled) {
  113486. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  113487. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  113488. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  113489. }
  113490. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  113491. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  113492. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  113493. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  113494. }
  113495. }
  113496. if (this.shadowLevel > 0) {
  113497. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  113498. }
  113499. this._uniformBuffer.updateFloat("alpha", this.alpha);
  113500. // Point size
  113501. if (this.pointsCloud) {
  113502. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  113503. }
  113504. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  113505. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  113506. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  113507. }
  113508. else {
  113509. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  113510. }
  113511. }
  113512. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  113513. // Textures
  113514. if (scene.texturesEnabled) {
  113515. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  113516. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  113517. }
  113518. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  113519. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  113520. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  113521. }
  113522. else if (!defines.REFLECTIONBLUR) {
  113523. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  113524. }
  113525. else {
  113526. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  113527. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  113528. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  113529. }
  113530. if (defines.REFLECTIONFRESNEL) {
  113531. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  113532. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  113533. }
  113534. }
  113535. }
  113536. // Clip plane
  113537. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  113538. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  113539. }
  113540. if (mustRebind || !this.isFrozen) {
  113541. if (scene.lightsEnabled) {
  113542. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  113543. }
  113544. // View
  113545. this.bindView(effect);
  113546. // Fog
  113547. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  113548. // image processing
  113549. if (this._imageProcessingConfiguration) {
  113550. this._imageProcessingConfiguration.bind(this._activeEffect);
  113551. }
  113552. }
  113553. this._uniformBuffer.update();
  113554. this._afterBind(mesh, this._activeEffect);
  113555. };
  113556. /**
  113557. * Dispose the material.
  113558. * @param forceDisposeEffect Force disposal of the associated effect.
  113559. * @param forceDisposeTextures Force disposal of the associated textures.
  113560. */
  113561. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  113562. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  113563. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  113564. if (forceDisposeTextures) {
  113565. if (this.diffuseTexture) {
  113566. this.diffuseTexture.dispose();
  113567. }
  113568. if (this.reflectionTexture) {
  113569. this.reflectionTexture.dispose();
  113570. }
  113571. }
  113572. this._renderTargets.dispose();
  113573. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  113574. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  113575. }
  113576. _super.prototype.dispose.call(this, forceDisposeEffect);
  113577. };
  113578. /**
  113579. * Clones the material.
  113580. * @param name The cloned name.
  113581. * @returns The cloned material.
  113582. */
  113583. BackgroundMaterial.prototype.clone = function (name) {
  113584. var _this = this;
  113585. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  113586. };
  113587. /**
  113588. * Serializes the current material to its JSON representation.
  113589. * @returns The JSON representation.
  113590. */
  113591. BackgroundMaterial.prototype.serialize = function () {
  113592. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  113593. serializationObject.customType = "BABYLON.BackgroundMaterial";
  113594. return serializationObject;
  113595. };
  113596. /**
  113597. * Gets the class name of the material
  113598. * @returns "BackgroundMaterial"
  113599. */
  113600. BackgroundMaterial.prototype.getClassName = function () {
  113601. return "BackgroundMaterial";
  113602. };
  113603. /**
  113604. * Parse a JSON input to create back a background material.
  113605. * @param source The JSON data to parse
  113606. * @param scene The scene to create the parsed material in
  113607. * @param rootUrl The root url of the assets the material depends upon
  113608. * @returns the instantiated BackgroundMaterial.
  113609. */
  113610. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  113611. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  113612. };
  113613. /**
  113614. * Standard reflectance value at parallel view angle.
  113615. */
  113616. BackgroundMaterial.StandardReflectance0 = 0.05;
  113617. /**
  113618. * Standard reflectance value at grazing angle.
  113619. */
  113620. BackgroundMaterial.StandardReflectance90 = 0.5;
  113621. __decorate([
  113622. BABYLON.serializeAsColor3()
  113623. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  113624. __decorate([
  113625. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  113626. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  113627. __decorate([
  113628. BABYLON.serializeAsColor3()
  113629. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  113630. __decorate([
  113631. BABYLON.serialize()
  113632. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  113633. __decorate([
  113634. BABYLON.serialize()
  113635. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  113636. __decorate([
  113637. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  113638. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  113639. __decorate([
  113640. BABYLON.serializeAsTexture()
  113641. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  113642. __decorate([
  113643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113644. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  113645. __decorate([
  113646. BABYLON.serialize()
  113647. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  113648. __decorate([
  113649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113650. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  113651. __decorate([
  113652. BABYLON.serializeAsTexture()
  113653. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  113654. __decorate([
  113655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113656. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  113657. __decorate([
  113658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113659. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  113660. __decorate([
  113661. BABYLON.serialize()
  113662. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  113663. __decorate([
  113664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113665. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  113666. __decorate([
  113667. BABYLON.serializeAsVector3()
  113668. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  113669. __decorate([
  113670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113671. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  113672. __decorate([
  113673. BABYLON.serialize()
  113674. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  113675. __decorate([
  113676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113677. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  113678. __decorate([
  113679. BABYLON.serialize()
  113680. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  113681. __decorate([
  113682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113683. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  113684. __decorate([
  113685. BABYLON.serialize()
  113686. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  113687. __decorate([
  113688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113689. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  113690. __decorate([
  113691. BABYLON.serialize()
  113692. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  113693. __decorate([
  113694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113695. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  113696. __decorate([
  113697. BABYLON.serialize()
  113698. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  113699. __decorate([
  113700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113701. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  113702. __decorate([
  113703. BABYLON.serialize()
  113704. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  113705. __decorate([
  113706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113707. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  113708. __decorate([
  113709. BABYLON.serialize()
  113710. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  113711. __decorate([
  113712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113713. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  113714. __decorate([
  113715. BABYLON.serialize()
  113716. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  113717. __decorate([
  113718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113719. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  113720. __decorate([
  113721. BABYLON.serialize()
  113722. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  113723. __decorate([
  113724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  113725. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  113726. __decorate([
  113727. BABYLON.serializeAsImageProcessingConfiguration()
  113728. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  113729. return BackgroundMaterial;
  113730. }(BABYLON.PushMaterial));
  113731. BABYLON.BackgroundMaterial = BackgroundMaterial;
  113732. })(BABYLON || (BABYLON = {}));
  113733. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  113734. var __assign = (this && this.__assign) || function () {
  113735. __assign = Object.assign || function(t) {
  113736. for (var s, i = 1, n = arguments.length; i < n; i++) {
  113737. s = arguments[i];
  113738. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  113739. t[p] = s[p];
  113740. }
  113741. return t;
  113742. };
  113743. return __assign.apply(this, arguments);
  113744. };
  113745. var BABYLON;
  113746. (function (BABYLON) {
  113747. /**
  113748. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  113749. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  113750. * It also helps with the default setup of your imageProcessing configuration.
  113751. */
  113752. var EnvironmentHelper = /** @class */ (function () {
  113753. /**
  113754. * constructor
  113755. * @param options
  113756. * @param scene The scene to add the material to
  113757. */
  113758. function EnvironmentHelper(options, scene) {
  113759. var _this = this;
  113760. this._errorHandler = function (message, exception) {
  113761. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  113762. };
  113763. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  113764. this._scene = scene;
  113765. this.onErrorObservable = new BABYLON.Observable();
  113766. this._setupBackground();
  113767. this._setupImageProcessing();
  113768. }
  113769. /**
  113770. * Creates the default options for the helper.
  113771. */
  113772. EnvironmentHelper._getDefaultOptions = function () {
  113773. return {
  113774. createGround: true,
  113775. groundSize: 15,
  113776. groundTexture: this._groundTextureCDNUrl,
  113777. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  113778. groundOpacity: 0.9,
  113779. enableGroundShadow: true,
  113780. groundShadowLevel: 0.5,
  113781. enableGroundMirror: false,
  113782. groundMirrorSizeRatio: 0.3,
  113783. groundMirrorBlurKernel: 64,
  113784. groundMirrorAmount: 1,
  113785. groundMirrorFresnelWeight: 1,
  113786. groundMirrorFallOffDistance: 0,
  113787. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  113788. groundYBias: 0.00001,
  113789. createSkybox: true,
  113790. skyboxSize: 20,
  113791. skyboxTexture: this._skyboxTextureCDNUrl,
  113792. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  113793. backgroundYRotation: 0,
  113794. sizeAuto: true,
  113795. rootPosition: BABYLON.Vector3.Zero(),
  113796. setupImageProcessing: true,
  113797. environmentTexture: this._environmentTextureCDNUrl,
  113798. cameraExposure: 0.8,
  113799. cameraContrast: 1.2,
  113800. toneMappingEnabled: true,
  113801. };
  113802. };
  113803. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  113804. /**
  113805. * Gets the root mesh created by the helper.
  113806. */
  113807. get: function () {
  113808. return this._rootMesh;
  113809. },
  113810. enumerable: true,
  113811. configurable: true
  113812. });
  113813. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  113814. /**
  113815. * Gets the skybox created by the helper.
  113816. */
  113817. get: function () {
  113818. return this._skybox;
  113819. },
  113820. enumerable: true,
  113821. configurable: true
  113822. });
  113823. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  113824. /**
  113825. * Gets the skybox texture created by the helper.
  113826. */
  113827. get: function () {
  113828. return this._skyboxTexture;
  113829. },
  113830. enumerable: true,
  113831. configurable: true
  113832. });
  113833. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  113834. /**
  113835. * Gets the skybox material created by the helper.
  113836. */
  113837. get: function () {
  113838. return this._skyboxMaterial;
  113839. },
  113840. enumerable: true,
  113841. configurable: true
  113842. });
  113843. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  113844. /**
  113845. * Gets the ground mesh created by the helper.
  113846. */
  113847. get: function () {
  113848. return this._ground;
  113849. },
  113850. enumerable: true,
  113851. configurable: true
  113852. });
  113853. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  113854. /**
  113855. * Gets the ground texture created by the helper.
  113856. */
  113857. get: function () {
  113858. return this._groundTexture;
  113859. },
  113860. enumerable: true,
  113861. configurable: true
  113862. });
  113863. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  113864. /**
  113865. * Gets the ground mirror created by the helper.
  113866. */
  113867. get: function () {
  113868. return this._groundMirror;
  113869. },
  113870. enumerable: true,
  113871. configurable: true
  113872. });
  113873. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  113874. /**
  113875. * Gets the ground mirror render list to helps pushing the meshes
  113876. * you wish in the ground reflection.
  113877. */
  113878. get: function () {
  113879. if (this._groundMirror) {
  113880. return this._groundMirror.renderList;
  113881. }
  113882. return null;
  113883. },
  113884. enumerable: true,
  113885. configurable: true
  113886. });
  113887. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  113888. /**
  113889. * Gets the ground material created by the helper.
  113890. */
  113891. get: function () {
  113892. return this._groundMaterial;
  113893. },
  113894. enumerable: true,
  113895. configurable: true
  113896. });
  113897. /**
  113898. * Updates the background according to the new options
  113899. * @param options
  113900. */
  113901. EnvironmentHelper.prototype.updateOptions = function (options) {
  113902. var newOptions = __assign({}, this._options, options);
  113903. if (this._ground && !newOptions.createGround) {
  113904. this._ground.dispose();
  113905. this._ground = null;
  113906. }
  113907. if (this._groundMaterial && !newOptions.createGround) {
  113908. this._groundMaterial.dispose();
  113909. this._groundMaterial = null;
  113910. }
  113911. if (this._groundTexture) {
  113912. if (this._options.groundTexture != newOptions.groundTexture) {
  113913. this._groundTexture.dispose();
  113914. this._groundTexture = null;
  113915. }
  113916. }
  113917. if (this._skybox && !newOptions.createSkybox) {
  113918. this._skybox.dispose();
  113919. this._skybox = null;
  113920. }
  113921. if (this._skyboxMaterial && !newOptions.createSkybox) {
  113922. this._skyboxMaterial.dispose();
  113923. this._skyboxMaterial = null;
  113924. }
  113925. if (this._skyboxTexture) {
  113926. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  113927. this._skyboxTexture.dispose();
  113928. this._skyboxTexture = null;
  113929. }
  113930. }
  113931. if (this._groundMirror && !newOptions.enableGroundMirror) {
  113932. this._groundMirror.dispose();
  113933. this._groundMirror = null;
  113934. }
  113935. if (this._scene.environmentTexture) {
  113936. if (this._options.environmentTexture != newOptions.environmentTexture) {
  113937. this._scene.environmentTexture.dispose();
  113938. }
  113939. }
  113940. this._options = newOptions;
  113941. this._setupBackground();
  113942. this._setupImageProcessing();
  113943. };
  113944. /**
  113945. * Sets the primary color of all the available elements.
  113946. * @param color the main color to affect to the ground and the background
  113947. */
  113948. EnvironmentHelper.prototype.setMainColor = function (color) {
  113949. if (this.groundMaterial) {
  113950. this.groundMaterial.primaryColor = color;
  113951. }
  113952. if (this.skyboxMaterial) {
  113953. this.skyboxMaterial.primaryColor = color;
  113954. }
  113955. if (this.groundMirror) {
  113956. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  113957. }
  113958. };
  113959. /**
  113960. * Setup the image processing according to the specified options.
  113961. */
  113962. EnvironmentHelper.prototype._setupImageProcessing = function () {
  113963. if (this._options.setupImageProcessing) {
  113964. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  113965. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  113966. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  113967. this._setupEnvironmentTexture();
  113968. }
  113969. };
  113970. /**
  113971. * Setup the environment texture according to the specified options.
  113972. */
  113973. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  113974. if (this._scene.environmentTexture) {
  113975. return;
  113976. }
  113977. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  113978. this._scene.environmentTexture = this._options.environmentTexture;
  113979. return;
  113980. }
  113981. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  113982. this._scene.environmentTexture = environmentTexture;
  113983. };
  113984. /**
  113985. * Setup the background according to the specified options.
  113986. */
  113987. EnvironmentHelper.prototype._setupBackground = function () {
  113988. if (!this._rootMesh) {
  113989. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  113990. }
  113991. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  113992. var sceneSize = this._getSceneSize();
  113993. if (this._options.createGround) {
  113994. this._setupGround(sceneSize);
  113995. this._setupGroundMaterial();
  113996. this._setupGroundDiffuseTexture();
  113997. if (this._options.enableGroundMirror) {
  113998. this._setupGroundMirrorTexture(sceneSize);
  113999. }
  114000. this._setupMirrorInGroundMaterial();
  114001. }
  114002. if (this._options.createSkybox) {
  114003. this._setupSkybox(sceneSize);
  114004. this._setupSkyboxMaterial();
  114005. this._setupSkyboxReflectionTexture();
  114006. }
  114007. this._rootMesh.position.x = sceneSize.rootPosition.x;
  114008. this._rootMesh.position.z = sceneSize.rootPosition.z;
  114009. this._rootMesh.position.y = sceneSize.rootPosition.y;
  114010. };
  114011. /**
  114012. * Get the scene sizes according to the setup.
  114013. */
  114014. EnvironmentHelper.prototype._getSceneSize = function () {
  114015. var _this = this;
  114016. var groundSize = this._options.groundSize;
  114017. var skyboxSize = this._options.skyboxSize;
  114018. var rootPosition = this._options.rootPosition;
  114019. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  114020. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  114021. }
  114022. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  114023. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  114024. });
  114025. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  114026. if (this._options.sizeAuto) {
  114027. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  114028. this._scene.activeCamera.upperRadiusLimit) {
  114029. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  114030. skyboxSize = groundSize;
  114031. }
  114032. var sceneDiagonalLenght = sceneDiagonal.length();
  114033. if (sceneDiagonalLenght > groundSize) {
  114034. groundSize = sceneDiagonalLenght * 2;
  114035. skyboxSize = groundSize;
  114036. }
  114037. // 10 % bigger.
  114038. groundSize *= 1.1;
  114039. skyboxSize *= 1.5;
  114040. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  114041. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  114042. }
  114043. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  114044. };
  114045. /**
  114046. * Setup the ground according to the specified options.
  114047. */
  114048. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  114049. var _this = this;
  114050. if (!this._ground || this._ground.isDisposed()) {
  114051. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  114052. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  114053. this._ground.parent = this._rootMesh;
  114054. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  114055. }
  114056. this._ground.receiveShadows = this._options.enableGroundShadow;
  114057. };
  114058. /**
  114059. * Setup the ground material according to the specified options.
  114060. */
  114061. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  114062. if (!this._groundMaterial) {
  114063. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  114064. }
  114065. this._groundMaterial.alpha = this._options.groundOpacity;
  114066. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  114067. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  114068. this._groundMaterial.primaryColor = this._options.groundColor;
  114069. this._groundMaterial.useRGBColor = false;
  114070. this._groundMaterial.enableNoise = true;
  114071. if (this._ground) {
  114072. this._ground.material = this._groundMaterial;
  114073. }
  114074. };
  114075. /**
  114076. * Setup the ground diffuse texture according to the specified options.
  114077. */
  114078. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  114079. if (!this._groundMaterial) {
  114080. return;
  114081. }
  114082. if (this._groundTexture) {
  114083. return;
  114084. }
  114085. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  114086. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  114087. return;
  114088. }
  114089. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  114090. diffuseTexture.gammaSpace = false;
  114091. diffuseTexture.hasAlpha = true;
  114092. this._groundMaterial.diffuseTexture = diffuseTexture;
  114093. };
  114094. /**
  114095. * Setup the ground mirror texture according to the specified options.
  114096. */
  114097. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  114098. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114099. if (!this._groundMirror) {
  114100. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  114101. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  114102. this._groundMirror.anisotropicFilteringLevel = 1;
  114103. this._groundMirror.wrapU = wrapping;
  114104. this._groundMirror.wrapV = wrapping;
  114105. this._groundMirror.gammaSpace = false;
  114106. if (this._groundMirror.renderList) {
  114107. for (var i = 0; i < this._scene.meshes.length; i++) {
  114108. var mesh = this._scene.meshes[i];
  114109. if (mesh !== this._ground &&
  114110. mesh !== this._skybox &&
  114111. mesh !== this._rootMesh) {
  114112. this._groundMirror.renderList.push(mesh);
  114113. }
  114114. }
  114115. }
  114116. }
  114117. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  114118. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  114119. };
  114120. /**
  114121. * Setup the ground to receive the mirror texture.
  114122. */
  114123. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  114124. if (this._groundMaterial) {
  114125. this._groundMaterial.reflectionTexture = this._groundMirror;
  114126. this._groundMaterial.reflectionFresnel = true;
  114127. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  114128. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  114129. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  114130. }
  114131. };
  114132. /**
  114133. * Setup the skybox according to the specified options.
  114134. */
  114135. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  114136. var _this = this;
  114137. if (!this._skybox || this._skybox.isDisposed()) {
  114138. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  114139. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  114140. }
  114141. this._skybox.parent = this._rootMesh;
  114142. };
  114143. /**
  114144. * Setup the skybox material according to the specified options.
  114145. */
  114146. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  114147. if (!this._skybox) {
  114148. return;
  114149. }
  114150. if (!this._skyboxMaterial) {
  114151. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  114152. }
  114153. this._skyboxMaterial.useRGBColor = false;
  114154. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  114155. this._skyboxMaterial.enableNoise = true;
  114156. this._skybox.material = this._skyboxMaterial;
  114157. };
  114158. /**
  114159. * Setup the skybox reflection texture according to the specified options.
  114160. */
  114161. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  114162. if (!this._skyboxMaterial) {
  114163. return;
  114164. }
  114165. if (this._skyboxTexture) {
  114166. return;
  114167. }
  114168. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  114169. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  114170. return;
  114171. }
  114172. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  114173. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  114174. this._skyboxTexture.gammaSpace = false;
  114175. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  114176. };
  114177. /**
  114178. * Dispose all the elements created by the Helper.
  114179. */
  114180. EnvironmentHelper.prototype.dispose = function () {
  114181. if (this._groundMaterial) {
  114182. this._groundMaterial.dispose(true, true);
  114183. }
  114184. if (this._skyboxMaterial) {
  114185. this._skyboxMaterial.dispose(true, true);
  114186. }
  114187. this._rootMesh.dispose(false);
  114188. };
  114189. /**
  114190. * Default ground texture URL.
  114191. */
  114192. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  114193. /**
  114194. * Default skybox texture URL.
  114195. */
  114196. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  114197. /**
  114198. * Default environment texture URL.
  114199. */
  114200. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  114201. return EnvironmentHelper;
  114202. }());
  114203. BABYLON.EnvironmentHelper = EnvironmentHelper;
  114204. })(BABYLON || (BABYLON = {}));
  114205. //# sourceMappingURL=babylon.environmentHelper.js.map
  114206. var BABYLON;
  114207. (function (BABYLON) {
  114208. /** Internal class used to store shapes for emitters */
  114209. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  114210. function ParticleSystemSetEmitterCreationOptions() {
  114211. }
  114212. return ParticleSystemSetEmitterCreationOptions;
  114213. }());
  114214. /**
  114215. * Represents a set of particle systems working together to create a specific effect
  114216. */
  114217. var ParticleSystemSet = /** @class */ (function () {
  114218. function ParticleSystemSet() {
  114219. /**
  114220. * Gets the particle system list
  114221. */
  114222. this.systems = new Array();
  114223. }
  114224. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  114225. /**
  114226. * Gets the emitter node used with this set
  114227. */
  114228. get: function () {
  114229. return this._emitterNode;
  114230. },
  114231. enumerable: true,
  114232. configurable: true
  114233. });
  114234. /**
  114235. * Creates a new emitter mesh as a sphere
  114236. * @param options defines the options used to create the sphere
  114237. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  114238. * @param scene defines the hosting scene
  114239. */
  114240. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  114241. if (this._emitterNode) {
  114242. this._emitterNode.dispose();
  114243. }
  114244. this._emitterCreationOptions = {
  114245. kind: "Sphere",
  114246. options: options,
  114247. renderingGroupId: renderingGroupId
  114248. };
  114249. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  114250. emitterMesh.renderingGroupId = renderingGroupId;
  114251. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  114252. material.emissiveColor = options.color;
  114253. emitterMesh.material = material;
  114254. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  114255. var system = _a[_i];
  114256. system.emitter = emitterMesh;
  114257. }
  114258. this._emitterNode = emitterMesh;
  114259. };
  114260. /**
  114261. * Starts all particle systems of the set
  114262. * @param emitter defines an optional mesh to use as emitter for the particle systems
  114263. */
  114264. ParticleSystemSet.prototype.start = function (emitter) {
  114265. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  114266. var system = _a[_i];
  114267. if (emitter) {
  114268. system.emitter = emitter;
  114269. }
  114270. system.start();
  114271. }
  114272. };
  114273. /**
  114274. * Release all associated resources
  114275. */
  114276. ParticleSystemSet.prototype.dispose = function () {
  114277. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  114278. var system = _a[_i];
  114279. system.dispose();
  114280. }
  114281. this.systems = [];
  114282. if (this._emitterNode) {
  114283. this._emitterNode.dispose();
  114284. this._emitterNode = null;
  114285. }
  114286. };
  114287. /**
  114288. * Serialize the set into a JSON compatible object
  114289. * @returns a JSON compatible representation of the set
  114290. */
  114291. ParticleSystemSet.prototype.serialize = function () {
  114292. var result = {};
  114293. result.systems = [];
  114294. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  114295. var system = _a[_i];
  114296. result.systems.push(system.serialize());
  114297. }
  114298. if (this._emitterNode) {
  114299. result.emitter = this._emitterCreationOptions;
  114300. }
  114301. return result;
  114302. };
  114303. /**
  114304. * Parse a new ParticleSystemSet from a serialized source
  114305. * @param data defines a JSON compatible representation of the set
  114306. * @param scene defines the hosting scene
  114307. * @param gpu defines if we want GPU particles or CPU particles
  114308. * @returns a new ParticleSystemSet
  114309. */
  114310. ParticleSystemSet.Parse = function (data, scene, gpu) {
  114311. if (gpu === void 0) { gpu = false; }
  114312. var result = new ParticleSystemSet();
  114313. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  114314. scene = scene || BABYLON.Engine.LastCreatedScene;
  114315. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  114316. var system = _a[_i];
  114317. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  114318. }
  114319. if (data.emitter) {
  114320. var options = data.emitter.options;
  114321. switch (data.emitter.kind) {
  114322. case "Sphere":
  114323. result.setEmitterAsSphere({
  114324. diameter: options.diameter,
  114325. segments: options.segments,
  114326. color: BABYLON.Color3.FromArray(options.color)
  114327. }, data.emitter.renderingGroupId, scene);
  114328. break;
  114329. }
  114330. }
  114331. return result;
  114332. };
  114333. return ParticleSystemSet;
  114334. }());
  114335. BABYLON.ParticleSystemSet = ParticleSystemSet;
  114336. })(BABYLON || (BABYLON = {}));
  114337. //# sourceMappingURL=babylon.particleSystemSet.js.map
  114338. var BABYLON;
  114339. (function (BABYLON) {
  114340. /**
  114341. * This class is made for on one-liner static method to help creating particle system set.
  114342. */
  114343. var ParticleHelper = /** @class */ (function () {
  114344. function ParticleHelper() {
  114345. }
  114346. /**
  114347. * Create a default particle system that you can tweak
  114348. * @param emitter defines the emitter to use
  114349. * @param capacity defines the system capacity (default is 500 particles)
  114350. * @param scene defines the hosting scene
  114351. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  114352. * @returns the new Particle system
  114353. */
  114354. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  114355. if (capacity === void 0) { capacity = 500; }
  114356. if (useGPU === void 0) { useGPU = false; }
  114357. var system;
  114358. if (useGPU) {
  114359. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  114360. }
  114361. else {
  114362. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  114363. }
  114364. system.emitter = emitter;
  114365. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  114366. system.createConeEmitter(0.1, Math.PI / 4);
  114367. // Particle color
  114368. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  114369. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  114370. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  114371. // Particle Size
  114372. system.minSize = 0.1;
  114373. system.maxSize = 0.1;
  114374. // Emission speed
  114375. system.minEmitPower = 2;
  114376. system.maxEmitPower = 2;
  114377. // Update speed
  114378. system.updateSpeed = 1 / 60;
  114379. system.emitRate = 30;
  114380. return system;
  114381. };
  114382. /**
  114383. * This is the main static method (one-liner) of this helper to create different particle systems
  114384. * @param type This string represents the type to the particle system to create
  114385. * @param scene The scene where the particle system should live
  114386. * @param gpu If the system will use gpu
  114387. * @returns the ParticleSystemSet created
  114388. */
  114389. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  114390. if (gpu === void 0) { gpu = false; }
  114391. if (!scene) {
  114392. scene = BABYLON.Engine.LastCreatedScene;
  114393. ;
  114394. }
  114395. var token = {};
  114396. scene._addPendingData(token);
  114397. return new Promise(function (resolve, reject) {
  114398. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  114399. scene._removePendingData(token);
  114400. return reject("Particle system with GPU is not supported.");
  114401. }
  114402. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  114403. scene._removePendingData(token);
  114404. var newData = JSON.parse(data.toString());
  114405. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  114406. }, undefined, undefined, undefined, function (req, exception) {
  114407. scene._removePendingData(token);
  114408. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  114409. });
  114410. });
  114411. };
  114412. /**
  114413. * Static function used to export a particle system to a ParticleSystemSet variable.
  114414. * Please note that the emitter shape is not exported
  114415. * @param systems defines the particle systems to export
  114416. * @returns the created particle system set
  114417. */
  114418. ParticleHelper.ExportSet = function (systems) {
  114419. var set = new BABYLON.ParticleSystemSet();
  114420. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  114421. var system = systems_1[_i];
  114422. set.systems.push(system);
  114423. }
  114424. return set;
  114425. };
  114426. /**
  114427. * Gets or sets base Assets URL
  114428. */
  114429. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  114430. return ParticleHelper;
  114431. }());
  114432. BABYLON.ParticleHelper = ParticleHelper;
  114433. })(BABYLON || (BABYLON = {}));
  114434. //# sourceMappingURL=babylon.particleHelper.js.map
  114435. var BABYLON;
  114436. (function (BABYLON) {
  114437. /**
  114438. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  114439. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  114440. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  114441. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  114442. */
  114443. var VideoDome = /** @class */ (function (_super) {
  114444. __extends(VideoDome, _super);
  114445. /**
  114446. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  114447. * @param name Element's name, child elements will append suffixes for their own names.
  114448. * @param urlsOrVideo defines the url(s) or the video element to use
  114449. * @param options An object containing optional or exposed sub element properties
  114450. */
  114451. function VideoDome(name, urlsOrVideo, options, scene) {
  114452. var _this = _super.call(this, name, scene) || this;
  114453. _this._useDirectMapping = false;
  114454. // set defaults and manage values
  114455. name = name || "videoDome";
  114456. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  114457. options.clickToPlay = Boolean(options.clickToPlay);
  114458. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  114459. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  114460. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  114461. if (options.useDirectMapping === undefined) {
  114462. _this._useDirectMapping = true;
  114463. }
  114464. else {
  114465. _this._useDirectMapping = options.useDirectMapping;
  114466. }
  114467. _this._setReady(false);
  114468. // create
  114469. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  114470. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  114471. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  114472. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  114473. texture.onLoadObservable.addOnce(function () {
  114474. _this._setReady(true);
  114475. });
  114476. // configure material
  114477. material.useEquirectangularFOV = true;
  114478. material.fovMultiplier = 1.0;
  114479. material.opacityFresnel = false;
  114480. if (_this._useDirectMapping) {
  114481. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114482. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114483. material.diffuseTexture = texture;
  114484. }
  114485. else {
  114486. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  114487. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114488. material.reflectionTexture = texture;
  114489. }
  114490. // configure mesh
  114491. _this._mesh.material = material;
  114492. _this._mesh.parent = _this;
  114493. // optional configuration
  114494. if (options.clickToPlay) {
  114495. scene.onPointerUp = function () {
  114496. _this._videoTexture.video.play();
  114497. };
  114498. }
  114499. return _this;
  114500. }
  114501. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  114502. /**
  114503. * Gets the video texture being displayed on the sphere
  114504. */
  114505. get: function () {
  114506. return this._videoTexture;
  114507. },
  114508. enumerable: true,
  114509. configurable: true
  114510. });
  114511. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  114512. /**
  114513. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  114514. * Also see the options.resolution property.
  114515. */
  114516. get: function () {
  114517. return this._material.fovMultiplier;
  114518. },
  114519. set: function (value) {
  114520. this._material.fovMultiplier = value;
  114521. },
  114522. enumerable: true,
  114523. configurable: true
  114524. });
  114525. /**
  114526. * Releases resources associated with this node.
  114527. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  114528. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  114529. */
  114530. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  114531. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  114532. this._videoTexture.dispose();
  114533. this._mesh.dispose();
  114534. this._material.dispose();
  114535. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  114536. };
  114537. return VideoDome;
  114538. }(BABYLON.TransformNode));
  114539. BABYLON.VideoDome = VideoDome;
  114540. })(BABYLON || (BABYLON = {}));
  114541. //# sourceMappingURL=babylon.videoDome.js.map
  114542. var BABYLON;
  114543. (function (BABYLON) {
  114544. /**
  114545. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  114546. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  114547. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  114548. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  114549. */
  114550. var PhotoDome = /** @class */ (function (_super) {
  114551. __extends(PhotoDome, _super);
  114552. /**
  114553. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  114554. * @param name Element's name, child elements will append suffixes for their own names.
  114555. * @param urlsOfPhoto defines the url of the photo to display
  114556. * @param options defines an object containing optional or exposed sub element properties
  114557. * @param onError defines a callback called when an error occured while loading the texture
  114558. */
  114559. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  114560. if (onError === void 0) { onError = null; }
  114561. var _this = _super.call(this, name, scene) || this;
  114562. _this._useDirectMapping = false;
  114563. /**
  114564. * Observable raised when an error occured while loading the 360 image
  114565. */
  114566. _this.onLoadErrorObservable = new BABYLON.Observable();
  114567. // set defaults and manage values
  114568. name = name || "photoDome";
  114569. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  114570. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  114571. if (options.useDirectMapping === undefined) {
  114572. _this._useDirectMapping = true;
  114573. }
  114574. else {
  114575. _this._useDirectMapping = options.useDirectMapping;
  114576. }
  114577. _this._setReady(false);
  114578. // create
  114579. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  114580. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  114581. // configure material
  114582. material.opacityFresnel = false;
  114583. material.useEquirectangularFOV = true;
  114584. material.fovMultiplier = 1.0;
  114585. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  114586. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  114587. if (onError) {
  114588. onError(message, exception);
  114589. }
  114590. });
  114591. _this.photoTexture.onLoadObservable.addOnce(function () {
  114592. _this._setReady(true);
  114593. });
  114594. // configure mesh
  114595. _this._mesh.material = material;
  114596. _this._mesh.parent = _this;
  114597. return _this;
  114598. }
  114599. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  114600. /**
  114601. * Gets or sets the texture being displayed on the sphere
  114602. */
  114603. get: function () {
  114604. return this._photoTexture;
  114605. },
  114606. set: function (value) {
  114607. if (this._photoTexture === value) {
  114608. return;
  114609. }
  114610. this._photoTexture = value;
  114611. if (this._useDirectMapping) {
  114612. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114613. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114614. this._material.diffuseTexture = this._photoTexture;
  114615. }
  114616. else {
  114617. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  114618. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  114619. this._material.reflectionTexture = this._photoTexture;
  114620. }
  114621. },
  114622. enumerable: true,
  114623. configurable: true
  114624. });
  114625. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  114626. /**
  114627. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  114628. * Also see the options.resolution property.
  114629. */
  114630. get: function () {
  114631. return this._material.fovMultiplier;
  114632. },
  114633. set: function (value) {
  114634. this._material.fovMultiplier = value;
  114635. },
  114636. enumerable: true,
  114637. configurable: true
  114638. });
  114639. /**
  114640. * Releases resources associated with this node.
  114641. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  114642. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  114643. */
  114644. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  114645. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  114646. this._photoTexture.dispose();
  114647. this._mesh.dispose();
  114648. this._material.dispose();
  114649. this.onLoadErrorObservable.clear();
  114650. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  114651. };
  114652. return PhotoDome;
  114653. }(BABYLON.TransformNode));
  114654. BABYLON.PhotoDome = PhotoDome;
  114655. })(BABYLON || (BABYLON = {}));
  114656. //# sourceMappingURL=babylon.photoDome.js.map
  114657. var BABYLON;
  114658. (function (BABYLON) {
  114659. /** @hidden */
  114660. var _OcclusionDataStorage = /** @class */ (function () {
  114661. function _OcclusionDataStorage() {
  114662. /** @hidden */
  114663. this.occlusionInternalRetryCounter = 0;
  114664. /** @hidden */
  114665. this.isOcclusionQueryInProgress = false;
  114666. /** @hidden */
  114667. this.isOccluded = false;
  114668. /** @hidden */
  114669. this.occlusionRetryCount = -1;
  114670. /** @hidden */
  114671. this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
  114672. /** @hidden */
  114673. this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  114674. }
  114675. return _OcclusionDataStorage;
  114676. }());
  114677. BABYLON.Engine.prototype.createQuery = function () {
  114678. return this._gl.createQuery();
  114679. };
  114680. BABYLON.Engine.prototype.deleteQuery = function (query) {
  114681. this._gl.deleteQuery(query);
  114682. return this;
  114683. };
  114684. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  114685. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  114686. };
  114687. BABYLON.Engine.prototype.getQueryResult = function (query) {
  114688. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  114689. };
  114690. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  114691. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  114692. this._gl.beginQuery(glAlgorithm, query);
  114693. return this;
  114694. };
  114695. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  114696. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  114697. this._gl.endQuery(glAlgorithm);
  114698. return this;
  114699. };
  114700. BABYLON.Engine.prototype._createTimeQuery = function () {
  114701. var timerQuery = this.getCaps().timerQuery;
  114702. if (timerQuery.createQueryEXT) {
  114703. return timerQuery.createQueryEXT();
  114704. }
  114705. return this.createQuery();
  114706. };
  114707. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  114708. var timerQuery = this.getCaps().timerQuery;
  114709. if (timerQuery.deleteQueryEXT) {
  114710. timerQuery.deleteQueryEXT(query);
  114711. return;
  114712. }
  114713. this.deleteQuery(query);
  114714. };
  114715. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  114716. var timerQuery = this.getCaps().timerQuery;
  114717. if (timerQuery.getQueryObjectEXT) {
  114718. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  114719. }
  114720. return this.getQueryResult(query);
  114721. };
  114722. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  114723. var timerQuery = this.getCaps().timerQuery;
  114724. if (timerQuery.getQueryObjectEXT) {
  114725. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  114726. }
  114727. return this.isQueryResultAvailable(query);
  114728. };
  114729. BABYLON.Engine.prototype.startTimeQuery = function () {
  114730. var caps = this.getCaps();
  114731. var timerQuery = caps.timerQuery;
  114732. if (!timerQuery) {
  114733. return null;
  114734. }
  114735. var token = new BABYLON._TimeToken();
  114736. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  114737. if (caps.canUseTimestampForTimerQuery) {
  114738. token._startTimeQuery = this._createTimeQuery();
  114739. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  114740. }
  114741. else {
  114742. if (this._currentNonTimestampToken) {
  114743. return this._currentNonTimestampToken;
  114744. }
  114745. token._timeElapsedQuery = this._createTimeQuery();
  114746. if (timerQuery.beginQueryEXT) {
  114747. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  114748. }
  114749. else {
  114750. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  114751. }
  114752. this._currentNonTimestampToken = token;
  114753. }
  114754. return token;
  114755. };
  114756. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  114757. var caps = this.getCaps();
  114758. var timerQuery = caps.timerQuery;
  114759. if (!timerQuery || !token) {
  114760. return -1;
  114761. }
  114762. if (caps.canUseTimestampForTimerQuery) {
  114763. if (!token._startTimeQuery) {
  114764. return -1;
  114765. }
  114766. if (!token._endTimeQuery) {
  114767. token._endTimeQuery = this._createTimeQuery();
  114768. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  114769. }
  114770. }
  114771. else if (!token._timeElapsedQueryEnded) {
  114772. if (!token._timeElapsedQuery) {
  114773. return -1;
  114774. }
  114775. if (timerQuery.endQueryEXT) {
  114776. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  114777. }
  114778. else {
  114779. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  114780. }
  114781. token._timeElapsedQueryEnded = true;
  114782. }
  114783. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  114784. var available = false;
  114785. if (token._endTimeQuery) {
  114786. available = this._getTimeQueryAvailability(token._endTimeQuery);
  114787. }
  114788. else if (token._timeElapsedQuery) {
  114789. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  114790. }
  114791. if (available && !disjoint) {
  114792. var result = 0;
  114793. if (caps.canUseTimestampForTimerQuery) {
  114794. if (!token._startTimeQuery || !token._endTimeQuery) {
  114795. return -1;
  114796. }
  114797. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  114798. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  114799. result = timeEnd - timeStart;
  114800. this._deleteTimeQuery(token._startTimeQuery);
  114801. this._deleteTimeQuery(token._endTimeQuery);
  114802. token._startTimeQuery = null;
  114803. token._endTimeQuery = null;
  114804. }
  114805. else {
  114806. if (!token._timeElapsedQuery) {
  114807. return -1;
  114808. }
  114809. result = this._getTimeQueryResult(token._timeElapsedQuery);
  114810. this._deleteTimeQuery(token._timeElapsedQuery);
  114811. token._timeElapsedQuery = null;
  114812. token._timeElapsedQueryEnded = false;
  114813. this._currentNonTimestampToken = null;
  114814. }
  114815. return result;
  114816. }
  114817. return -1;
  114818. };
  114819. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  114820. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  114821. };
  114822. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  114823. get: function () {
  114824. return this._occlusionDataStorage.isOcclusionQueryInProgress;
  114825. },
  114826. enumerable: false,
  114827. configurable: true
  114828. });
  114829. Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
  114830. get: function () {
  114831. if (!this.__occlusionDataStorage) {
  114832. this.__occlusionDataStorage = new _OcclusionDataStorage();
  114833. }
  114834. return this.__occlusionDataStorage;
  114835. },
  114836. enumerable: false,
  114837. configurable: true
  114838. });
  114839. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
  114840. get: function () {
  114841. return this._occlusionDataStorage.isOccluded;
  114842. },
  114843. set: function (value) {
  114844. this._occlusionDataStorage.isOccluded = value;
  114845. },
  114846. enumerable: true,
  114847. configurable: true
  114848. });
  114849. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  114850. get: function () {
  114851. return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  114852. },
  114853. set: function (value) {
  114854. this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  114855. },
  114856. enumerable: true,
  114857. configurable: true
  114858. });
  114859. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
  114860. get: function () {
  114861. return this._occlusionDataStorage.occlusionType;
  114862. },
  114863. set: function (value) {
  114864. this._occlusionDataStorage.occlusionType = value;
  114865. },
  114866. enumerable: true,
  114867. configurable: true
  114868. });
  114869. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
  114870. get: function () {
  114871. return this._occlusionDataStorage.occlusionRetryCount;
  114872. },
  114873. set: function (value) {
  114874. this._occlusionDataStorage.occlusionRetryCount = value;
  114875. },
  114876. enumerable: true,
  114877. configurable: true
  114878. });
  114879. // We also need to update AbstractMesh as there is a portion of the code there
  114880. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  114881. var dataStorage = this._occlusionDataStorage;
  114882. if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  114883. dataStorage.isOccluded = false;
  114884. return false;
  114885. }
  114886. var engine = this.getEngine();
  114887. if (engine.webGLVersion < 2) {
  114888. dataStorage.isOccluded = false;
  114889. return false;
  114890. }
  114891. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  114892. dataStorage.isOccluded = false;
  114893. return false;
  114894. }
  114895. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  114896. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  114897. if (isOcclusionQueryAvailable) {
  114898. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  114899. dataStorage.isOcclusionQueryInProgress = false;
  114900. dataStorage.occlusionInternalRetryCounter = 0;
  114901. dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
  114902. }
  114903. else {
  114904. dataStorage.occlusionInternalRetryCounter++;
  114905. if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
  114906. dataStorage.isOcclusionQueryInProgress = false;
  114907. dataStorage.occlusionInternalRetryCounter = 0;
  114908. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  114909. // if strict continue the last state of the object.
  114910. dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
  114911. }
  114912. else {
  114913. return false;
  114914. }
  114915. }
  114916. }
  114917. var scene = this.getScene();
  114918. if (scene.getBoundingBoxRenderer) {
  114919. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  114920. if (!this._occlusionQuery) {
  114921. this._occlusionQuery = engine.createQuery();
  114922. }
  114923. engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
  114924. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  114925. engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
  114926. this._occlusionDataStorage.isOcclusionQueryInProgress = true;
  114927. }
  114928. return dataStorage.isOccluded;
  114929. };
  114930. })(BABYLON || (BABYLON = {}));
  114931. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  114932. var BABYLON;
  114933. (function (BABYLON) {
  114934. /**
  114935. * Class used to generate noise procedural textures
  114936. */
  114937. var NoiseProceduralTexture = /** @class */ (function (_super) {
  114938. __extends(NoiseProceduralTexture, _super);
  114939. /**
  114940. * Creates a new NoiseProceduralTexture
  114941. * @param name defines the name fo the texture
  114942. * @param size defines the size of the texture (default is 256)
  114943. * @param scene defines the hosting scene
  114944. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  114945. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  114946. */
  114947. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  114948. if (size === void 0) { size = 256; }
  114949. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  114950. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  114951. _this._time = 0;
  114952. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  114953. _this.brightness = 0.2;
  114954. /** Defines the number of octaves to process */
  114955. _this.octaves = 3;
  114956. /** Defines the level of persistence (0.8 by default) */
  114957. _this.persistence = 0.8;
  114958. /** Gets or sets animation speed factor (default is 1) */
  114959. _this.animationSpeedFactor = 1;
  114960. _this._updateShaderUniforms();
  114961. return _this;
  114962. }
  114963. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  114964. var scene = this.getScene();
  114965. if (!scene) {
  114966. return;
  114967. }
  114968. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  114969. this.setFloat("brightness", this.brightness);
  114970. this.setFloat("persistence", this.persistence);
  114971. this.setFloat("timeScale", this._time);
  114972. };
  114973. NoiseProceduralTexture.prototype._getDefines = function () {
  114974. return "#define OCTAVES " + (this.octaves | 0);
  114975. };
  114976. /** Generate the current state of the procedural texture */
  114977. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  114978. this._updateShaderUniforms();
  114979. _super.prototype.render.call(this, useCameraPostProcess);
  114980. };
  114981. /**
  114982. * Serializes this noise procedural texture
  114983. * @returns a serialized noise procedural texture object
  114984. */
  114985. NoiseProceduralTexture.prototype.serialize = function () {
  114986. var serializationObject = {};
  114987. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  114988. serializationObject.brightness = this.brightness;
  114989. serializationObject.octaves = this.octaves;
  114990. serializationObject.persistence = this.persistence;
  114991. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  114992. serializationObject.size = this.getSize().width;
  114993. serializationObject.generateMipMaps = this._generateMipMaps;
  114994. return serializationObject;
  114995. };
  114996. /**
  114997. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  114998. * @param parsedTexture defines parsed texture data
  114999. * @param scene defines the current scene
  115000. * @param rootUrl defines the root URL containing noise procedural texture information
  115001. * @returns a parsed NoiseProceduralTexture
  115002. */
  115003. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  115004. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  115005. texture.brightness = parsedTexture.brightness;
  115006. texture.octaves = parsedTexture.octaves;
  115007. texture.persistence = parsedTexture.persistence;
  115008. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  115009. return texture;
  115010. };
  115011. return NoiseProceduralTexture;
  115012. }(BABYLON.ProceduralTexture));
  115013. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  115014. })(BABYLON || (BABYLON = {}));
  115015. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  115016. var __assign = (this && this.__assign) || function () {
  115017. __assign = Object.assign || function(t) {
  115018. for (var s, i = 1, n = arguments.length; i < n; i++) {
  115019. s = arguments[i];
  115020. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  115021. t[p] = s[p];
  115022. }
  115023. return t;
  115024. };
  115025. return __assign.apply(this, arguments);
  115026. };
  115027. var BABYLON;
  115028. (function (BABYLON) {
  115029. /**
  115030. * This can helps recording videos from BabylonJS.
  115031. * This is based on the available WebRTC functionalities of the browser.
  115032. *
  115033. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  115034. */
  115035. var VideoRecorder = /** @class */ (function () {
  115036. /**
  115037. * Create a new VideoCapture object which can help converting what you see in Babylon to
  115038. * a video file.
  115039. * @param engine Defines the BabylonJS Engine you wish to record
  115040. * @param options Defines options that can be used to customized the capture
  115041. */
  115042. function VideoRecorder(engine, options) {
  115043. if (options === void 0) { options = null; }
  115044. if (!VideoRecorder.IsSupported(engine)) {
  115045. throw "Your browser does not support recording so far.";
  115046. }
  115047. var canvas = engine.getRenderingCanvas();
  115048. if (!canvas) {
  115049. throw "The babylon engine must have a canvas to be recorded";
  115050. }
  115051. this._canvas = canvas;
  115052. this._canvas.isRecording = false;
  115053. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  115054. var stream = this._canvas.captureStream(this._options.fps);
  115055. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  115056. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  115057. this._mediaRecorder.onerror = this._handleError.bind(this);
  115058. this._mediaRecorder.onstop = this._handleStop.bind(this);
  115059. }
  115060. /**
  115061. * Returns wehther or not the VideoRecorder is available in your browser.
  115062. * @param engine Defines the Babylon Engine to check the support for
  115063. * @returns true if supported otherwise false
  115064. */
  115065. VideoRecorder.IsSupported = function (engine) {
  115066. var canvas = engine.getRenderingCanvas();
  115067. return (!!canvas && typeof canvas.captureStream === "function");
  115068. };
  115069. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  115070. /**
  115071. * True wether a recording is already in progress.
  115072. */
  115073. get: function () {
  115074. return !!this._canvas && this._canvas.isRecording;
  115075. },
  115076. enumerable: true,
  115077. configurable: true
  115078. });
  115079. /**
  115080. * Stops the current recording before the default capture timeout passed in the startRecording
  115081. * functions.
  115082. */
  115083. VideoRecorder.prototype.stopRecording = function () {
  115084. if (!this._canvas || !this._mediaRecorder) {
  115085. return;
  115086. }
  115087. if (!this.isRecording) {
  115088. return;
  115089. }
  115090. this._canvas.isRecording = false;
  115091. this._mediaRecorder.stop();
  115092. };
  115093. /**
  115094. * Starts recording the canvas for a max duration specified in parameters.
  115095. * @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.
  115096. * @param maxDuration Defines the maximum recording time in seconds.
  115097. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  115098. * @return a promise callback at the end of the recording with the video data in Blob.
  115099. */
  115100. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  115101. var _this = this;
  115102. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  115103. if (maxDuration === void 0) { maxDuration = 7; }
  115104. if (!this._canvas || !this._mediaRecorder) {
  115105. throw "Recorder has already been disposed";
  115106. }
  115107. if (this.isRecording) {
  115108. throw "Recording already in progress";
  115109. }
  115110. if (maxDuration > 0) {
  115111. setTimeout(function () {
  115112. _this.stopRecording();
  115113. }, maxDuration * 1000);
  115114. }
  115115. this._fileName = fileName;
  115116. this._recordedChunks = [];
  115117. this._resolve = null;
  115118. this._reject = null;
  115119. this._canvas.isRecording = true;
  115120. this._mediaRecorder.start(this._options.recordChunckSize);
  115121. return new Promise(function (resolve, reject) {
  115122. _this._resolve = resolve;
  115123. _this._reject = reject;
  115124. });
  115125. };
  115126. /**
  115127. * Releases internal resources used during the recording.
  115128. */
  115129. VideoRecorder.prototype.dispose = function () {
  115130. this._canvas = null;
  115131. this._mediaRecorder = null;
  115132. this._recordedChunks = [];
  115133. this._fileName = null;
  115134. this._resolve = null;
  115135. this._reject = null;
  115136. };
  115137. VideoRecorder.prototype._handleDataAvailable = function (event) {
  115138. if (event.data.size > 0) {
  115139. this._recordedChunks.push(event.data);
  115140. }
  115141. };
  115142. VideoRecorder.prototype._handleError = function (event) {
  115143. this.stopRecording();
  115144. if (this._reject) {
  115145. this._reject(event.error);
  115146. }
  115147. else {
  115148. throw new event.error;
  115149. }
  115150. };
  115151. VideoRecorder.prototype._handleStop = function () {
  115152. this.stopRecording();
  115153. var superBuffer = new Blob(this._recordedChunks);
  115154. if (this._resolve) {
  115155. this._resolve(superBuffer);
  115156. }
  115157. window.URL.createObjectURL(superBuffer);
  115158. if (this._fileName) {
  115159. BABYLON.Tools.Download(superBuffer, this._fileName);
  115160. }
  115161. };
  115162. VideoRecorder._defaultOptions = {
  115163. mimeType: "video/webm",
  115164. fps: 25,
  115165. recordChunckSize: 3000
  115166. };
  115167. return VideoRecorder;
  115168. }());
  115169. BABYLON.VideoRecorder = VideoRecorder;
  115170. })(BABYLON || (BABYLON = {}));
  115171. //# sourceMappingURL=babylon.videoRecorder.js.map
  115172. var BABYLON;
  115173. (function (BABYLON) {
  115174. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  115175. if (replace === void 0) { replace = false; }
  115176. // Dispose existing light in replace mode.
  115177. if (replace) {
  115178. if (this.lights) {
  115179. for (var i = 0; i < this.lights.length; i++) {
  115180. this.lights[i].dispose();
  115181. }
  115182. }
  115183. }
  115184. // Light
  115185. if (this.lights.length === 0) {
  115186. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  115187. }
  115188. };
  115189. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  115190. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  115191. if (replace === void 0) { replace = false; }
  115192. if (attachCameraControls === void 0) { attachCameraControls = false; }
  115193. // Dispose existing camera in replace mode.
  115194. if (replace) {
  115195. if (this.activeCamera) {
  115196. this.activeCamera.dispose();
  115197. this.activeCamera = null;
  115198. }
  115199. }
  115200. // Camera
  115201. if (!this.activeCamera) {
  115202. var worldExtends = this.getWorldExtends();
  115203. var worldSize = worldExtends.max.subtract(worldExtends.min);
  115204. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  115205. var camera;
  115206. var radius = worldSize.length() * 1.5;
  115207. // empty scene scenario!
  115208. if (!isFinite(radius)) {
  115209. radius = 1;
  115210. worldCenter.copyFromFloats(0, 0, 0);
  115211. }
  115212. if (createArcRotateCamera) {
  115213. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  115214. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  115215. arcRotateCamera.wheelPrecision = 100 / radius;
  115216. camera = arcRotateCamera;
  115217. }
  115218. else {
  115219. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  115220. freeCamera.setTarget(worldCenter);
  115221. camera = freeCamera;
  115222. }
  115223. camera.minZ = radius * 0.01;
  115224. camera.maxZ = radius * 1000;
  115225. camera.speed = radius * 0.2;
  115226. this.activeCamera = camera;
  115227. var canvas = this.getEngine().getRenderingCanvas();
  115228. if (attachCameraControls && canvas) {
  115229. camera.attachControl(canvas);
  115230. }
  115231. }
  115232. };
  115233. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  115234. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  115235. if (replace === void 0) { replace = false; }
  115236. if (attachCameraControls === void 0) { attachCameraControls = false; }
  115237. this.createDefaultLight(replace);
  115238. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  115239. };
  115240. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  115241. if (pbr === void 0) { pbr = false; }
  115242. if (scale === void 0) { scale = 1000; }
  115243. if (blur === void 0) { blur = 0; }
  115244. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  115245. if (!environmentTexture) {
  115246. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  115247. return null;
  115248. }
  115249. if (setGlobalEnvTexture) {
  115250. if (environmentTexture) {
  115251. this.environmentTexture = environmentTexture;
  115252. }
  115253. }
  115254. // Skybox
  115255. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  115256. if (pbr) {
  115257. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  115258. hdrSkyboxMaterial.backFaceCulling = false;
  115259. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  115260. if (hdrSkyboxMaterial.reflectionTexture) {
  115261. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  115262. }
  115263. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  115264. hdrSkyboxMaterial.disableLighting = true;
  115265. hdrSkyboxMaterial.twoSidedLighting = true;
  115266. hdrSkybox.infiniteDistance = true;
  115267. hdrSkybox.material = hdrSkyboxMaterial;
  115268. }
  115269. else {
  115270. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  115271. skyboxMaterial.backFaceCulling = false;
  115272. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  115273. if (skyboxMaterial.reflectionTexture) {
  115274. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  115275. }
  115276. skyboxMaterial.disableLighting = true;
  115277. hdrSkybox.infiniteDistance = true;
  115278. hdrSkybox.material = skyboxMaterial;
  115279. }
  115280. return hdrSkybox;
  115281. };
  115282. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  115283. if (BABYLON.EnvironmentHelper) {
  115284. return new BABYLON.EnvironmentHelper(options, this);
  115285. }
  115286. return null;
  115287. };
  115288. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  115289. if (webVROptions === void 0) { webVROptions = {}; }
  115290. return new BABYLON.VRExperienceHelper(this, webVROptions);
  115291. };
  115292. })(BABYLON || (BABYLON = {}));
  115293. //# sourceMappingURL=babylon.sceneHelpers.js.map
  115294. 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 BILLBOARDSTRETCHED\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}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\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#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,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\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\n#include<instancesVertex>\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\n#ifdef BILLBOARDSTRETCHED\nin vec3 direction;\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}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\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#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,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(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"};
  115295. 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};"};